Array Operations in Java

Last updated: January 8, 2024

array assignment operators in java

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

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

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

Improve Java application performance with CRaC support

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

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

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

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

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

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

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

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

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

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

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

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

>> Become an efficient full-stack developer with Jmix

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

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

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

>> Take a look at DBSchema

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

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

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

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

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

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

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

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

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

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

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

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

>> The New “REST With Spring Boot”

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

>> LEARN SPRING

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

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

You can explore the course here:

>> Learn Spring Security

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

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

>> CHECK OUT THE COURSE

1. Overview

Any Java developer knows that producing a clean, efficient solution when working with array operations isn’t always easy to achieve. Still, they’re a central piece in the Java ecosystem – and we’ll have to deal with them on several occasions.

For this reason, it’s good to have a ‘cheat sheet’ – a summary of the most common procedures to help us tackle the puzzle quickly. This tutorial will come in handy in those situations.

2. Arrays and Helper Classes

Before proceeding, it’s useful to understand what is an array in Java, and how to use it. If it’s your first time working with it in Java, we suggest having a look at  this previous post  where we covered all basic concepts.

Please note that the basic operations that an array supports are, in a certain way, limited. It’s not uncommon to see complex algorithms to execute relatively simple tasks when it comes to arrays.

For this reason, for most of our operations, we’ll be using helper classes and methods to assist us: the  Arrays class provided by Java and the Apache’s ArrayUtils  one.

To include the latter in our project, we’ll have to add the  Apache Commons dependency:

We can check out the latest version of this artifact on Maven Central .

3. Get the First and Last Element of an Array

This is one of the most common and simple tasks thanks to the access-by-index nature of arrays.

Let’s start by declaring and initializing an int array that will be used in all our examples (unless we specify otherwise):

Knowing that the first item of an array is associated with the index value 0 and that it has a length attribute that we can use, then it’s simple to figure out how we can get these two elements:

4. Get a Random Value from an Array

By using the java.util.Random object we can easily get any value from our array:

5. Append a New Item to an Array

As we know, arrays hold a fixed size of values. Therefore, we can’t just add an item and exceed this limit.

We’ll need to start by declaring a new, larger array, and copy the elements of the base array to the second one.

Fortunately, the Arrays class provides a handy method to replicate the values of an array to a new different-sized structure:

Optionally, if the ArrayUtils class is accessible in our project, we can make use of its add method  (or its addAll alternative) to accomplish our objective in a one-line statement:

As we can imagine, this method doesn’t modify the original array object; we have to assign its output to a new variable.

6. Insert a Value Between Two Values

Because of its indexed-values character, inserting an item in an array between two others is not a trivial job.

Apache considered this a typical scenario and implemented a method in its ArrayUtils class to simplify the solution:

We have to specify the index in which we want to insert the value, and the output will be a new array containing a larger number of elements.

The last argument is a variable argument (a.k.a. vararg ) thus we can insert any number of items in the array.

7. Compare Two Arrays

Even though arrays are Object s and therefore provide an equals method, they use the default implementation of it, relying only on reference equality.

We can anyhow invoke the java.util.Arrays ‘ equals method to check if two array objects contain the same values:

Note: this method is not effective for jagged arrays . The appropriate method to verify multi-dimensional structures’ equality is the Arrays.deepEquals one.

8. Check if an Array Is Empty

This is an uncomplicated assignment having in mind that we can use the  length attribute of arrays:

Moreover, we also have a null-safe method in the ArrayUtils helper class that we can use:

This function still depends on the length of the data structure, which considers nulls and empty sub-arrays as valid values too, so we’ll have to keep an eye on these edge cases:

9. How to Shuffle the Elements of an Array

In order to shuffle the items in an array, we can use the  ArrayUtil ‘s feature:

This is a void method and operates on the actual values of the array.

10. Box and Unbox Arrays

We often come across methods that support only Object -based arrays.

Again the ArrayUtils helper class comes in handy to get a boxed version of our primitive array:

The inverse operation is also possible:

11. Remove Duplicates from an Array

The easiest way of removing duplicates is by converting the array to a Set implementation.

As we may know, Collection s use Generics and hence don’t support primitive types.

For this reason, if we’re not handling object-based arrays as in our example, we’ll first need to box our values:

Note: we can use  other techniques to convert between an array and a Set object as well.

Also, if we need to preserve the order of our elements, we must use a different Set implementation, such as a  LinkedHashSet .

12. How to Print an Array

Same as with the equals method, the array’s toString function uses the default implementation provided by the Object class, which isn’t very useful.

Both Arrays and ArrayUtils  classes ship with their implementations to convert the data structures to a readable String .

Apart from the slightly different format they use, the most important distinction is how they treat multi-dimensional objects.

The Java Util’s class provides two static methods we can use:

  • toString : doesn’t work well with jagged arrays
  • deepToString : supports any Object -based arrays but doesn’t compile with primitive array arguments

On the other hand, Apache’s implementation offers a single toString method that works correctly in any case:

13. Map an Array to Another Type

It’s often useful to apply operations on all array items, possibly converting them to another type of object.

With this objective in mind, we’ll try to create a flexible helper method using Generics:

If we don’t use Java 8 in our project, we can discard the  Function argument, and create a method for each mapping that we need to carry out.

We can now reuse our generic method for different operations. Let’s create two test cases to illustrate this:

For primitive types, we’ll have to box our values first.

As an alternative, we can turn to Java 8’s Streams  to carry out the mapping for us.

We’ll need to transform the array into a Stream  of Object s first. We can do so with the Arrays.stream method.

For example, if we want to map our int values to a custom String representation, we’ll implement this:

14. Filter Values in an Array

Filtering out values from a collection is a common task that we might have to perform in more than one occasion.

This is because at the time we create the array that will receive the values, we can’t be sure of its final size. Therefore, we’ll rely on the Stream s approach again.

Imagine we want to remove all odd numbers from an array:

15. Other Common Array Operations

There are, of course, plenty of other array operations that we might need to perform.

Apart from the ones shown in this tutorial, we’ve extensively covered other operations in the dedicated posts:

  • Check if a Java Array Contains a Value
  • How to Copy an Array in Java
  • Removing the First Element of an Array
  • Finding the Min and Max in an Array with Java
  • Find Sum and Average in a Java Array
  • How to Invert an Array in Java
  • Join and Split Arrays and Collections in Java
  • Combining Different Types of Collections in Java
  • Find All Pairs of Numbers in an Array That Add Up to a Given Sum
  • Sorting in Java
  • Efficient Word Frequency Calculator in Java
  • Insertion Sort in Java

16. Conclusion

Arrays are one of the core functionalities of Java, and therefore it’s really important to understand how they work and to know what we can and can’t do with them.

In this tutorial, we learned how we can handle array operations appropriately in common scenarios.

As always, the full source code of the working examples is available over on  our Github repo .

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

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

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

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

>> Try Alpaquita Containers now.

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

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

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

Build your API with SPRING - book cover

Javatpoint Logo

Java Tutorial

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

JavaTpoint

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

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

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

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

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

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

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

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

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

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

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

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

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





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

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

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

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

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

The Arithmetic Operators

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

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

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

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

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

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

The Unary Operators

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

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

The following program, UnaryDemo , tests the unary operators:

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

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

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

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

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Java Basics
  • Java Tutorial
  • Java HelloWorld Program
  • Java Program Structure
  • Java Datatypes
  • Java Variable Types
  • Java Access Modifiers
  • Java Operators
  • Java Decision Making
  • Print array
  • Initialize array
  • Array of integers
  • Array of strings
  • Array of objects
  • Array of arrays
  • Iterate over array
  • Array For loop
  • Array while loop
  • Append element to array
  • Check if array is empty
  • Array average
  • Check if array contains
  • Array ForEach
  • Array - Find Index of Item
  • Concatenate arrays
  • Find smallest number in array
  • Find largest number in array
  • Array reverse
  • Classes and Objects
  • Inheritance
  • Polymorphism
  • Method Overloading
  • Method Overriding/
  • Abstraction
  • Abstract methods and classes
  • Encapsulation
  • Print string
  • Read string from console
  • Create string from Char array
  • Create string from Byte array
  • Concatenate two strings
  • Get index of the first Occurrence of substring
  • Get index of nth occurrence of substring
  • Check if two strings are equal
  • Check if string ends with specific suffix
  • Check if string starts with specific prefix
  • Check if string is blank
  • Check if string is empty
  • Check if string contains search substring
  • Validate if string is a Phone Number
  • Character Level
  • Get character at specific index in string
  • Get first character in string
  • Get last character from string
  • Transformations
  • Replace first occurrence of string
  • Replace all occurrences of a string
  • Join strings
  • Join strings in string array
  • Join strings in ArrayList
  • Reverse a string
  • Trim string
  • Split string
  • Remove whitespaces in string
  • Replace multiple spaces with single space
  • Comparisons
  • Compare strings lexicographically
  • Compare String and CharSequence
  • Compare String and StringBuffer
  • Java Exception Handling StringIndexOutOfBoundsException
  • Convert string to int
  • Convert string to float
  • Convert string to double
  • Convert string to long
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Convert int to double
  • Convert int to long
  • Convert int to char
  • Convert float to string
  • Convert float to int
  • Convert float to double
  • Convert float to long
  • Convert long to string
  • Convert long to float
  • Convert long to double
  • Convert long to int
  • Convert double to string
  • Convert double to float
  • Convert double to int
  • Convert double to long
  • Convert char to int
  • Convert boolean to string
  • Create a file
  • Read file as string
  • Write string to file
  • Delete File
  • Rename File
  • Download File from URL
  • Replace a String in File
  • Filter list of files or directories
  • Check if file is readable
  • Check if file is writable
  • Check if file is executable
  • Read contents of a file line by line using BufferedReader
  • Read contents of a File line by line using Stream
  • Check if n is positive or negative
  • Read integer from console
  • Add two integers
  • Count digits in number
  • Largest of three numbers
  • Smallest of three numbers
  • Even numbers
  • Odd numbers
  • Reverse a number
  • Prime Number
  • Print All Prime Numbers
  • Factors of a Number
  • Check Palindrome number
  • Check Palindrome string
  • Swap two numbers
  • Even or Odd number
  • Java Classes
  • ArrayList add()
  • ArrayList addAll()
  • ArrayList clear()
  • ArrayList clone()
  • ArrayList contains()
  • ArrayList ensureCapacity()
  • ArrayList forEach()
  • ArrayList get()
  • ArrayList indexOf()
  • ArrayList isEmpty()
  • ArrayList iterator()
  • ArrayList lastIndexOf()
  • ArrayList listIterator()
  • ArrayList remove()
  • ArrayList removeAll()
  • ArrayList removeIf()
  • ArrayList removeRange()
  • ArrayList retainAll()
  • ArrayList set()
  • ArrayList size()
  • ArrayList spliterator()
  • ArrayList subList()
  • ArrayList toArray()
  • ArrayList trimToSize()
  • HashMap clear()
  • HashMap clone()
  • HashMap compute()
  • HashMap computeIfAbsent()
  • HashMap computeIfPresent()
  • HashMap containsKey()
  • HashMap containsValue()
  • HashMap entrySet()
  • HashMap get()
  • HashMap isEmpty()
  • HashMap keySet()
  • HashMap merge()
  • HashMap put()
  • HashMap putAll()
  • HashMap remove()
  • HashMap size()
  • HashMap values()
  • HashSet add()
  • HashSet clear()
  • HashSet clone()
  • HashSet contains()
  • HashSet isEmpty()
  • HashSet iterator()
  • HashSet remove()
  • HashSet size()
  • HashSet spliterator()
  • Integer bitCount()
  • Integer byteValue()
  • Integer compare()
  • Integer compareTo()
  • Integer compareUnsigned()
  • Integer decode()
  • Integer divideUnsigned()
  • Integer doubleValue()
  • Integer equals()
  • Integer floatValue()
  • Integer getInteger()
  • Integer hashCode()
  • Integer highestOneBit()
  • Integer intValue()
  • Integer longValue()
  • Integer lowestOneBit()
  • Integer max()
  • Integer min()
  • Integer numberOfLeadingZeros()
  • Integer numberOfTrailingZeros()
  • Integer parseInt()
  • Integer parseUnsignedInt()
  • Integer remainderUnsigned()
  • Integer reverse()
  • Integer reverseBytes()
  • Integer rotateLeft()
  • Integer rotateRight()
  • Integer shortValue()
  • Integer signum()
  • Integer sum()
  • Integer toBinaryString()
  • Integer toHexString()
  • Integer toOctalString()
  • Integer toString()
  • Integer toUnsignedLong()
  • Integer toUnsignedString()
  • Integer valueOf()
  • StringBuilder append()
  • StringBuilder appendCodePoint()
  • StringBuilder capacity()
  • StringBuilder charAt()
  • StringBuilder chars()
  • StringBuilder codePointAt()
  • StringBuilder codePointBefore()
  • StringBuilder codePointCount()
  • StringBuilder codePoints()
  • StringBuilder delete()
  • StringBuilder deleteCharAt()
  • StringBuilder ensureCapacity()
  • StringBuilder getChars()
  • StringBuilder indexOf()
  • StringBuilder insert()
  • StringBuilder lastIndexOf()
  • StringBuilder length()
  • StringBuilder offsetByCodePoints()
  • StringBuilder replace()
  • StringBuilder reverse()
  • StringBuilder setCharAt()
  • StringBuilder setLength()
  • StringBuilder subSequence()
  • StringBuilder substring()
  • StringBuilder toString()
  • StringBuilder trimToSize()
  • Arrays.asList()
  • Arrays.binarySearch()
  • Arrays.copyOf()
  • Arrays.copyOfRange()
  • Arrays.deepEquals()
  • Arrays.deepToString()
  • Arrays.equals()
  • Arrays.fill()
  • Arrays.hashCode()
  • Arrays.sort()
  • Arrays.toString()
  • Random doubles()
  • Random ints()
  • Random longs()
  • Random next()
  • Random nextBoolean()
  • Random nextBytes()
  • Random nextDouble()
  • Random nextFloat()
  • Random nextGaussian()
  • Random nextInt()
  • Random nextLong()
  • Random setSeed()
  • Math random
  • Math signum
  • Math toDegrees
  • Math toRadians
  • Java Date & Time
  • ❯ Java Tutorial

Java Assignment Operators

Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand).

The syntax of any Assignment Operator with operands is

In this tutorial, we will learn about different Assignment Operators available in Java programming language and go through each of these Assignment Operations in detail, with the help of examples.

Operator Symbol – Example – Description

The following table specifies symbol, example, and description for each of the Assignment Operator in Java.

AssignmentOperationOperator SymbolExampleDescription
Simple Assignment=x = 2Assign x with 2.
Addition Assignment+=x += 3Add 3 to the value of x and assign the result to x.
Subtraction Assignment-=x -= 3Subtract 3 from x and assign the result to x.
Multiplication Assignment*=x *= 3Multiply x with 3 and assign the result to x.
Division Assignment/=x /= 3Divide x with 3 and assign the quotient to x.
Remainder Assignment%=x %= 3Divide x with 3 and assign the remainder to x.
Bitwise AND Assignment&=x &= 3Perform x & 3 and assign the result to x.
Bitwise OR Assignment|=x |= 3Perform x | 3 and assign the result to x.
Bitwise-exclusive-OR Assignment^=x ^= 3Perform x ^ 3 and assign the result to x.
Left-shift Assignment<<=x <<= 3Left-shift the value of x by 3 places and assign the result to x.
Right-shift Assignment>>=x >>= 3Right-shift the value of x by 3 places and assign the result to x.

Simple Assignment

In the following example, we assign a value of 2 to x using Simple Assignment Operator.

Addition Assignment

In the following example, we add 3 to x and assign the result to x using Addition Assignment Operator.

Subtraction Assignment

In the following example, we subtract 3 from x and assign the result to x using Subtraction Assignment Operator.

Multiplication Assignment

In the following example, we multiply 3 to x and assign the result to x using Multiplication Assignment Operator.

Division Assignment

In the following example, we divide x by 3 and assign the quotient to x using Division Assignment Operator.

Remainder Assignment

In the following example, we divide x by 3 and assign the remainder to x using Remainder Assignment Operator.

Bitwise AND Assignment

In the following example, we do bitwise AND operation between x and 3 and assign the result to x using Bitwise AND Assignment Operator.

Bitwise OR Assignment

In the following example, we do bitwise OR operation between x and 3 and assign the result to x using Bitwise OR Assignment Operator.

Bitwise XOR Assignment

In the following example, we do bitwise XOR operation between x and 3 and assign the result to x using Bitwise XOR Assignment Operator.

Left-shift Assignment

In the following example, we left-shift x by 3 places and assign the result to x using Left-shift Assignment Operator.

Right-shift Assignment

In the following example, we right-shift x by 3 places and assign the result to x using Right-shift Assignment Operator.

In this Java Tutorial , we learned what Assignment Operators are, and how to use them in Java programs, with the help of examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

01 Career Opportunities

02 beginner, 03 intermediate, 04 questions, 05 training programs, assignment operator in java, java online course free with certificate (2024), assignment operators in java: an overview, what are the assignment operators in java, types of assignment operators in java, 1. simple assignment operator (=):, explanation, 2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):, 5. division operator (/=):, 6. modulus assignment operator (%=):, example of assignment operator 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, live classes schedule.

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

Java Tutorial

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

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type with square brackets :

We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:

To create an array of integers, you could write:

Access the Elements of an Array

You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Try it Yourself »

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index number:

Array Length

To find out how many elements an array has, use the length property:

Test Yourself With Exercises

Create an array of type String called cars .

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.

  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Interesting facts about Array assignment in Java

Prerequisite : Arrays in Java

While working with arrays we have to do 3 tasks namely declaration, creation, initialization or Assignment. Declaration of array :

Creation of array :

Initialization of array :

Some important facts while assigning elements to the array:

   
   
 
   
 
 

Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html

Please Login to comment...

Similar reads.

  • Interesting-Facts
  • Java-Array-Programs
  • Java-Arrays

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Array assignment and reference in Java

I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -

Anuj Gupta's user avatar

  • Thats fine this is how each programming language works. –  bit-shashank Commented Jun 24, 2017 at 4:27

5 Answers 5

Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

Array a is assigned with a new array:

Assigning a

Array b is assigned to the instance behind a :

Assigning b

Array c is assigned with a new array:

Assigning c

And finally a is assigned to the instance behind c , b was not re-assigned and still keeps a reference to the old a :

Re-Assigning a

Images taken from a visualization on pythontutor.com

Felix's user avatar

Suppose you think of an object as a house, and a reference as a piece of paper with the address of a house written on it. a , b , and c are all references. So when you say

you're building a house with 1, 2, 3, 4, and 5 in it; and a is a piece of paper with the address of that house.

b is another reference, which means it's another piece of paper. But it has the address of the same house on it.

Now we build a new house and put 6, 7, and 8 into it. c will be a piece of paper with the address of the new house. When we say a = c , then the slip of paper that used to be a is thrown out, and we make a new piece of paper with the address of the new house. That's the new value of a .

But b was a separate piece of paper. It hasn't changed. Nothing we've done has changed it.

References are like that.

ajb's user avatar

When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.

Nipun's user avatar

When you do b=a b references to a. However when you to a=c a is referring to c, but still b refers to the old object (address of this object as value been assigned and it is constant) a that you assigned because that is what it contains when you assigned.

Unless you reassign it, it won't change.

Suresh Atta's user avatar

This is why:

What is Object Reference Variable?

You have 2 objects (the arrays) and 3 references (a, b, c) to the objects. You're just swapping around where things are pointed.

Tim's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Reference of "she"
  • Would weightlessness (i.e. in thrill rides, planes, skydiving, etc.) be different on a Flat Earth?
  • Seven different digits are placed in a row. The products of the first 3, middle 3 and last 3 are all equal. What is the middle digit?
  • LoginForm submission which sends sign in link to email and then sets value in localStorage
  • What is this surface feature near Shackleton crater classified as?
  • Why is the identity of the actor voicing Spider-Man kept secret even in the commentary?
  • Is plausibility more fundamental than probability?
  • Who said "If you don't do politics, politics will do you"?
  • Is there a way to swap my longbow from being a ranger for a shortbow?
  • Is there a good explanation for the existence of the C19 globular cluster with its very low metallicity?
  • Should I be able to see light from a IR Led with my own eyes?
  • How to remove a file named "."?
  • How does DS18B20 temperature sensor get the temperature?
  • I can't select a certain record with like %value%
  • Does the overall mAh of the battery add up when batteries are parallel?
  • Does "any computer(s) you have" refer to one or all the computers?
  • What is the rationale behind requiring ATC to retire at age 56?
  • Can science inform philosophy?
  • Publishing extension work for a previous research (in Chemical physics)
  • Has any spacecraft ever been severely damaged by a micrometeorite?
  • For applying to a STEM research position at a U.S. research university, should a resume include a photo?
  • Find all pairs of positive compatible numbers less than 100 by proof
  • Why are swimming goggles typically made from a different material than diving masks?
  • result of a union between a decidable language and not recognizable one - disjoint

array assignment operators in java

IMAGES

  1. Java Assignment Operators

    array assignment operators in java

  2. PPT

    array assignment operators in java

  3. Operators in Java

    array assignment operators in java

  4. Java: Assignment Operators

    array assignment operators in java

  5. Java Assignment Operators

    array assignment operators in java

  6. Beginner Java Tutorial #11: Shorthand Assignment Operators

    array assignment operators in java

COMMENTS

  1. Java Assignment Operators with Examples

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

  2. Array Variable Assignment in Java

    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. ... The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a. 7 min read. Difference ...

  3. Array Operations in Java

    Copy. 4. Get a Random Value from an Array. By using the java.util.Random object we can easily get any value from our array: int anyValue = array[ new Random ().nextInt(array.length)]; Copy. 5. Append a New Item to an Array. As we know, arrays hold a fixed size of values.

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

  5. Assignment operator explanation in Java

    5. Java language Specification: 15.26.1. Simple Assignment Operator =. If the left-hand operand is an array access expression (§15.13), possibly enclosed in one or more pairs of parentheses, then: First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then ...

  6. Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

    For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class. For instance, the previous example can be modified to use the copyOfRange method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example.

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

    This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators. The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics.

  8. Java Assignment Operators

    Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand). The syntax of any Assignment Operator with operands is. operand1 operator_symbol operand2. In this tutorial, we will learn about different Assignment Operators available in Java programming language ...

  9. Assignment Operators

    Java Features Java Releases and LTS Support ... Assignment Operators Logical Operators Shift Operators Bitwise Operators Ternary Operator ... Arrays Assignment Operators Operators Assignment Operators ...

  10. Assignment operator in Java

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

  11. All Java Assignment Operators (Explained With Examples)

    The general format of a Java assignment operator is as follows: variable = expression; Explanation: variable: This is the name of the variable to which you want to assign a value. expression: This is the value or result that you want to assign to the variable. The assignment operator (=) is used to assign the value of the expression on the right-hand side to the variable on the left-hand side.

  12. Arrays in Java

    Do refer to default array values in Java. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

  13. Java Operators

    Java Break/Continue Java Arrays. Arrays Loop Through an Array Real-Life Examples Multidimensional Arrays. Java Methods Java Methods Java Method Parameters. Parameters Return Values. ... In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

  14. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  15. Operators in Java

    The general format of the assignment operator is: variable = value;. In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement.For example, instead of a = a+5, we can write a += 5. +=, for adding the left operand with the right operand and then assigning it to the variable on the left.

  16. Java Arrays

    Java Arrays. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside ...

  17. Interesting facts about Array assignment in Java

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a

  18. java

    Answer 3: If you want a copy, you have to implement it yourself. You could implement a copy constructor or Clonable, or for a simple deep copy, serialize and deserialize the object, but that requires it and all objects it consists of to be Serializable. Answer 4: It's exactly the same for all Java Objects: the reside on the heap, and the code ...

  19. Array assignment and reference in Java

    1. When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.