Computer Science

Java Assignment Operators

Java Assignment Operators are used to assign values to variables. They combine the assignment operator (=) with other operators such as addition, subtraction, multiplication, division, and modulus. These operators allow for concise and efficient code when assigning values to variables.

Written by Perlego with AI-assistance

10 Key excerpts on "Java Assignment Operators"

  • OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2019(Publication Date)
    • Sybex
      (Publisher)
    Compilation errors from assignment operators are often overlooked on the exam, in part because of how subtle these errors can be. To master the assignment operators, you should be fluent in understanding how the compiler handles numeric promotion and when casting is required. Being able to spot these issues is critical to passing the exam, as assignment operators appear in nearly every question with a code snippet.

    Assignment Operator

    An
    assignment operator
    is a binary operator that modifies, or assigns, the variable on the left side of the operator, with the result of the value on the right side of the equation. The simplest assignment operator is the = assignment, which you have seen already:
    int herd = 1;
    This statement assigns the herd variable the value of 1 .
    Java will automatically promote from smaller to larger data types, as you saw in the previous section on arithmetic operators, but it will throw a compiler exception if it detects that you are trying to convert from larger to smaller data types without casting. Table 3.4 lists the first assignment operator that you need to know for the exam. We will present additional assignment operators later in this section.
    Table 3.4
    Simple assignment operator
    Operator Description
    = Assigns the value on the right to the variable on the left

    Casting Values

    Seems easy so far, right? Well, we can’t really talk about the assignment operator in detail until we’ve covered casting.
    Casting
    is a unary operation where one data type is explicitly interpreted as another data type. Casting is optional and unnecessary when converting to a larger or widening data type, but it is required when converting to a smaller or narrowing data type. Without casting, the compiler will generate an error when trying to put a larger data type inside a smaller one.
    Casting is performed by placing the data type, enclosed in parentheses, to the left of the value you want to cast. Here are some examples of casting:
  • OCP Oracle Certified Professional Java SE 11 Developer Complete Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2020(Publication Date)
    • Sybex
      (Publisher)
    Compilation errors from assignment operators are often overlooked on the exam, in part because of how subtle these errors can be. To master the assignment operators, you should be fluent in understanding how the compiler handles numeric promotion and when casting is required. Being able to spot these issues is critical to passing the exam, as assignment operators appear in nearly every question with a code snippet.

    Assignment Operator

    An
    assignment operator
    is a binary operator that modifies, or assigns, the variable on the left side of the operator, with the result of the value on the right side of the equation. The simplest assignment operator is the = assignment, which you have seen already:
    int herd = 1;
    This statement assigns the herd variable the value of 1 .
    Java will automatically promote from smaller to larger data types, as you saw in the previous section on arithmetic operators, but it will throw a compiler exception if it detects that you are trying to convert from larger to smaller data types without casting. Table 3.4 lists the first assignment operator that you need to know for the exam. We will present additional assignment operators later in this section.
    TABLE 3.4
    Simple assignment operator
    Operator Description
    = Assigns the value on the right to the variable on the left

    Casting Values

    Seems easy so far, right? Well, we can’t really talk about the assignment operator in detail until we’ve covered casting.
    Casting
    is a unary operation where one data type is explicitly interpreted as another data type. Casting is optional and unnecessary when converting to a larger or widening data type, but it is required when converting to a smaller or narrowing data type. Without casting, the compiler will generate an error when trying to put a larger data type inside a smaller one.
    Casting is performed by placing the data type, enclosed in parentheses, to the left of the value you want to cast. Here are some examples of casting:
  • 100+ Solutions in Java
    eBook - ePub

    100+ Solutions in Java

    A Hands-On Introduction to Programming in Java: A Hands-On Introduction to Programming in Java (English Edition)

    The assignment operator = is used to assign the value of the operand on its right to the operand on its left. More than one variable can be assigned a value simultaneously. For example, int a =10; int b = c = 20; Java also supports compound assignment to assign the result of an expression to a variable. For example, int a = 10; a += 6; // this is resolved as a = a + 6;

    Arithmetic

    Arithmetic operators operate on numeric data. However, they can be used with character data as well. These are binary operators which means that they operate on two operands. The following are the arithmetic operators in Java:
    • Addition (+): Performs the addition operation on the operands.
    • Subtraction (-): Performs the subtraction operation on the operands.
    • Multiplication (*): Performs the multiplication operation on the operands.
    • Division (/): Performs the division operation on the operands.
    • Modulo (%): Returns the remainder of a division operation.
    The following example shows the use of assignment and arithmetic operators: public class OperatorsDemo { public static void main(String[] args) { int add, sub, mul, div, mod; add = 3 + 5; sub = 6 - 4; mul = 2 * 2; div = 6 / 3; mod = 4 % 2; System.out.println("Addition is " + add); System.out.println("Subtraction is " + sub); System.out.println("Multiplication is " + mul); System.out.println("Division is " + div); System.out.println("Modulo is " + mod); } } The output of the code is shown in the following screenshot:
    Figure 2.4: Using Arithmetic operators
    Note that the modulo operation returned a 0 because 4 is directly divisible by 2.

    Unary

    Unary operators operate on a single operand. Java supports different types of unary operators which are as follows:
    • Unary plus (+): Indicates a positive value.
    • Unary minus (-): Negates an expression.
    • Increment (++): Increments the value of a variable by 1.
    • Decrement (--): Decrements the value of a variable by 1.
    • Logical complement (!): Inverts a boolean value.
    There are two ways of using increment and decrement operators, that is, prefix or postfix notation. Both will increment the value of a variable by 1. However, the prefix version will first increment the value and then assign it, whereas, the postfix version will first assign the value and then increment it.
  • Java
    eBook - ePub

    Java

    The Comprehensive Guide

    • Christian Ullenboom(Author)
    • 2022(Publication Date)
    • SAP PRESS
      (Publisher)

    2.4     Expressions, Operands, and Operators

    Let’s start with some mathematical expressions and then illustrate how they are written in Java. A mathematical formula, such as the expression -27 * 9 , consists of operands and operators . For example, an operand is a variable, a literal, or the return of a method call. In the case of a variable, the value is read from the variable and the calculation is performed with it.
    The operators link the operands. Depending on the number of operands, the following types of operators are distinguished:
    • An operator defined on exactly one operand is referred to as a unary operator (or monadic operator ). The minus (negative sign ) before an operand is a unary operator since it applies to exactly the following operand.
    • The usual operators (plus, minus, multiply, and divide) by are binary ( dyadic ) operators .
    • A question mark operator is used for conditional expressions, which have 3 characters.
    Operators allow the connection of individual expressions to new expressions. Some operators are familiar from school, such as addition, comparison, assignment, and others. C(++) programmers will recognize many old friends.

    2.4.1    Assignment Operator

    In Java, the equal sign = is used for an assignment . [ 57 ] The assignment operator is a binary operator with the variable to be assigned on the left and an expression on the right.
    [eg]   Example Let’s look at some expressions with assignments:
    int quantity = 12 , total ; total = quantity * 2 ;
    The multiplication calculates the product of 12 and 2 and stores the result in total . From all primitive variables that occur in the expression, the value is read and inserted into the expression. [ 58 ] This process is also called a value operation because the value of the variable is considered (and not its location or even its variable name).
    Only after the expression has been evaluated does the assignment operator copy the result into the variable. If runtime errors occur, for example, due to a division by zero, no write access to the variable is possible.
  • Android Programming for Beginners
    eBook - ePub

    Android Programming for Beginners

    Build in-depth, full-featured Android apps starting from zero programming experience, 3rd Edition

    Object-Oriented Programming ; however, it is good practice to both declare and initialize variables.

    Changing values in variables with operators

    Of course, in almost any program, we are going to need to "do things" with these variables' values. We manipulate (change) variables with operators . Here is a list of perhaps the most common Java operators that allow us to manipulate variables. You do not need to memorize them as we will look at every line of code as and when we use them for the first time. We have already seen the first operator when we initialized our variables, but we will see it again, this time being a bit more adventurous.

    The assignment operator

    This is the assignment operator: =
    It makes the variable to the left of the operator the same as the value to the right—for example, like in this line of code: unreadMessages = newMessages;
    After the previous line of code has executed, the value stored in unreadMessages will be the same as the value stored in newMessages .

    The addition operator

    This is the addition operator: +
    It will add together values on either side of the operator and is usually used in conjunction with the assignment operator. For example, it can add together two variables that have numeric values, like in this next line of code:
    unreadMessages = newMessages + unreadMessages;
    Once the previous code has executed the combined value of the values held by newMessages and unreadMessages , this is now stored in unreadMessages . As another example of the same thing, look at this line of code:
    accountBalance = yesterdaysBalance + todaysDeposits; Important note Notice that it is perfectly acceptable to use the same variable simultaneously on both sides of an operator.

    The subtraction operator

    This is the subtraction operator: -
    It will subtract the value on the right side of the operator from the value on the left. This is usually used in conjunction with the assignment operator, as in this code example:
  • OCA Java SE 8 Programmer I Certification Guide
    figure 2.14 as a conversation between a girl and a boy. The girl represents an object reference variable and the boy represents a primitive variable. (Don’t worry if you don’t understand all of these analogies. They’ll make much more sense after you read related topics in later chapters.)
    In the next section, you’ll start manipulating these variables using operators.
    Figure 2.14. Differences between object reference variables and primitive variables
    Passage contains an image

    2.4. Operators

    [3.1 ] Use Java operators; including parentheses to override operator precedence
    In this section, you’ll use different types of operators—assignment, arithmetic, relational, and logical—to manipulate the values of variables. You’ll write code to determine the equality of two primitive data types. You’ll also learn how to modify the default precedence of an operator by using parentheses. For the OCA Java SE 8 Programmer I exam, you should be able to work with the operators listed in table 2.9 .
    Table 2.9. Operator types and the relevant operators
    Operator type Operators Purpose
    Assignment =, +=, -=, *=, /=, %= Assign value to a variable
    Arithmetic +, -, *, /, %, ++, -- Add, subtract, multiply, divide, and modulus primitives
    Relational <, <=, >, >=, ==, != Compare primitives
    Logical !, &&, || Apply NOT, AND, and OR logic to primitives
    Note
    Not all operators can be used with all types of operands. For example, you can determine whether a number is greater than another number, but you can’t determine whether true is greater than false or a number is greater than true. Take note of this as you learn the usage of all the operators on this exam.
    2.4.1. Assignment operators
    The assignment operators that you need to know for the exam are =, +=, -=, *=, and /=. The simple assignment operator, =, is the most frequently used operator. It’s used to initialize variables with values and to reassign new values to them.
    The +=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication, and division with assignment. The += operator can be read as “first add and then assign,” and -= can be read as “first subtract and then assign.” Similarly, *= can be read as “first multiply and then assign,” /= can be read as “first divide and then assign,” and %= can be read as “first modulus and then assign.” If you apply these operators to two operands, a and b, they can be represented as follows:
  • The C++ Workshop
    eBook - ePub

    The C++ Workshop

    A New, Interactive Approach to Learning C++

    • Dale Green, Kurt Guntheroth, Shaun Ross Mitchell(Authors)
    • 2020(Publication Date)
    • Packt Publishing
      (Publisher)
    We'll then move on to looking at assignment operators. These allow us to assign data to our variables, and our variables to one another. This is the operator we've used the most so far, but there's certainly more to learn about this and the multiple variations that combine both assignment and arithmetic operators.
    The final operator types that we'll be looking at are logical and unary operators. Logical operators allow us to check conditions, resulting in a Boolean value for us to check. Unary operators are operators that operate on a single value, changing it in some way.
    We'll end the chapter by looking at overloading and assigning our own operators. While we have a wide range of operators available, it may sometimes be necessary for us to overload them, providing our own behavior for a certain type. C++ allows us to do that. It also allows us to define operators for our own user-defined types.
    At the end of this chapter, we'll put our understanding of operators to the test in a final activity in which we create the Fizz Buzz application, which is a common activity that is used to test C++ proficiency. When complete, we'll have a well-rounded understanding of the operators that we have available, allowing us to confidently and competently interact with the data within our systems.

    Arithmetic Operators

    Arithmetic operators are those that allow us to perform mathematical operations on our data. These are very self-explanatory and straightforward to use as, aside from the modulus operator, they have the same symbol that we'd use for everyday mathematics. For example, in order to add a number, you simply use the "+" sign as you would anywhere. Generally, these operators are going to be used with numeric data types, however, there's nothing stopping a type from implementing this operator. This will be covered as the final topic of the chapter.
    Let's take a quick look at our four basic operators: addition, subtraction, multiplication, and division. As stated previously, these four operators have the same symbols that you'd use day to day, so they should be familiar. The following example implements all four types of arithmetic operators:
  • Learn Java with Projects
    eBook - ePub

    Learn Java with Projects

    A concise practical guide to learning everything a Java professional really needs to know

    • Dr. Seán Kennedy, Maaike van Putten(Authors)
    • 2023(Publication Date)
    • Packt Publishing
      (Publisher)

    3

    Operators and Casting

    In Chapter 2 , we learned that variables are simply named pigeonholes and contain values. These values vary and Java provides eight primitive data types accordingly. These primitive types cater for whole numbers (byte , char , short , int , and long ), decimal numbers (float and double ), and the literals true and false ( boolean ).
    We also learned how to declare a variable. As Java is a strongly typed language, this means you must give every variable a data type immediately upon declaration. This is where primitive data types are very useful.
    Now that we know how to declare variables, let’s do something interesting with them. By the end of this chapter, you will be able to combine variables using Java’s various operators. In addition, you will understand Java casting, including what it is, and when and why it occurs.
    In this chapter, we are going to cover the following main topics:
    • Learning how Java’s operators cooperate
    • Understanding Java’s operators
    • Explaining Java casting

    Technical requirements

    The code for this chapter can be found on GitHub at https://github.com/PacktPublishing/Learn-Java-with-Projects/tree/main/ch3 .

    Learning how Java’s operators cooperate

    Java provides numerous operators for us to work with. By way of definition, if we have an expression 3 + 4 , the + is the operator , whereas 3 and 4 are the operands . Since + has two operands, it is known as a binary operator.
    Before we discuss the operators themselves, we must first discuss two important features relating to Java operators, namely order of precedence and associativity .

    Order of precedence

    Order of precedence specifies how operands are grouped with operators. This becomes important when you have shared operands in a complex expression. In the following code segment, we have an expression of 2 + 3 * 4 , where * represents multiplication and + represents addition:
    int a = 2 + 3 * 4;System.out.println(a);
    In the preceding code, 3 is shared by both 2 and 4 . So, the question arises, do we group 3 with 2 , where the expression is (2 + 3) * 4 , giving us 20 ; or do we group 3 with 4 , where the expression is 2 + (3 * 4) , giving us 14 ? This is where the order of precedence applies. As * has higher precedence than + , 3 is grouped with 4 and therefore the expression evaluates to 2 + (3 * 4)
  • C Programming
    eBook - ePub

    C Programming

    Learn to Code

    6 Operators and Expressions
    DOI: 10.1201/9781003188254-6

    6.1 Introduction

    This chapter will discuss the two most essential parts of any programming language: operators and expressions. An operator is a symbol that tells the computer to perform specific mathematical or logical operations. Operators are used in programs to manipulate data and variables. C is very rich in built-in operators.
    An operator is a symbol that tells the computer to perform specific mathematical or logical operations.
    Operators can be either binary or unary. Binary operators are the operators where one operator will act upon two operands.
    For example:
    12 + 14
    In this example, the operator + is acted upon two operands 12 and 14. Hence + is a binary operator here. Similarly, a unary operator has one operator and one operand.
    For example:
    25
    In this example, the operator – is acted upon one operand 25. Hence – is a unary operator here. The following are the operators used in C. These operators may be used as binary or unary operators.
    1. Arithmetic operators;
    2. Relational operators;
    3. Assignment operators;
    4. Logical operators;
    5. Increment or decrement operators;
    6. Conditional operators;
    7. Bitwise operators;
    8. Special operators.
    In the subsequent section, we will discuss the feature of all these operators, how to form expressions, how they are executed, and in what order. Finally, we will introduce the precedence of operators.
    On completion of this chapter, students will have learnt the working of different operators, the precedence of operators, and the way the C compiler executes an expression. Some new operators like increment, decrement, ternary, and other special operators are also a part of this chapter.
  • Introduction to Programming
    eBook - ePub

    Introduction to Programming

    Learn to program in Java with data structures, algorithms, and logic

    Java Language Elements and Types , we introduced input elements, those that are identified by the Java specification: whitespace, comment, and token. That is how the Java compiler parses the source code and makes sense of it. The list of tokens includes identifiers, keywords, separators, literals, and operators. That is how the Java compiler adds more meaning to the tokens it encounters.
    While discussing the input elements, we explained that they are used to build more complex elements of language. In this chapter, we will start with the operator token and show how an expression—a more complex Java element—is constructed with it.
    But, not all Java operators are tokens. The instanceof and new operators are keywords, while the . operator (field access or method invocation), the :: method reference operator , and the ( type ) cast operator are separators.
    As we said in Chapter 2 , Java Language Basics , a statement in Java plays a role similar to a sentence in the English language, which expresses a complete thought. In a programming language, a statement is a complete line of code that performs some action .
    An expression, on the other hand, is a part of a statement that evaluates to a value. Every expression can be a statement (if the resulting value is ignored), while most statements do not include expressions.
    That is how the three core elements of Java—operator, expression, and statementare related.
    Passage contains an image

    Operators

    Here is the list of all 44 operators in Java:
    Operators
    Description
    +, -, *, /, % Arithmetic unary and binary operators
    ++, -- Increment and decrement unary operators
    ==, != Equality operators
    <, >, <=, >= Relational operators
    !, &, | Logical operators
    &&, ||, ?, : Conditional operators
    =, +=, -=, *=, /=, %= Assignment operators
    &=, |=, ^=, <<=, >>=, >>>= Assignment operators
    &, |, ~, ^, <<, >>, >>> Bitwise operators
    ->, :: Arrow and method reference operators
    new Instance creation operator
    . Field access/method invocation operator
    instanceof Type comparison operator
    ( target type ) Cast operator
    Unary means used with a single operand, while binary means it requires two operands. In the following subsections, we will define and demonstrate most of the operators, except the rarely used assignment operators &=, |=, ^=, <<=, >>=, and >>>=, and the bitwise operators.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.