Learn Java practically and Get Certified .

Popular Tutorials

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

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

Java Flow Control

  • Java if...else

Java switch Statement

  • Java for Loop
  • Java for-each Loop
  • Java while Loop

Java break Statement

  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

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

Java OOP (III)

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

Java Reader/Writer

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

Additional Topics

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

Java Tutorials

Java Ternary Operator

Java Expressions, Statements and Blocks

Java if...else Statement

In programming, we use the if..else statement to run a block of code among more than one alternatives.

For example, assigning grades (A, B, C) based on the percentage obtained by a student.

  • if the percentage is above 90 , assign grade A
  • if the percentage is above 75 , assign grade B
  • if the percentage is above 65 , assign grade C

1. Java if (if-then) Statement

The syntax of an if-then statement is:

Here, condition is a boolean expression such as age >= 18 .

  • if condition evaluates to true , statements are executed
  • if condition evaluates to false , statements are skipped

Working of if Statement

if the number is greater than 0, code inside if block is executed, otherwise code inside if block is skipped

Example 1: Java if Statement

In the program, number < 0 is false . Hence, the code inside the body of the if statement is skipped .

Note: If you want to learn more about about test conditions, visit Java Relational Operators and Java Logical Operators .

We can also use Java Strings as the test condition.

Example 2: Java if with String

In the above example, we are comparing two strings in the if block.

2. Java if...else (if-then-else) Statement

The if statement executes a certain section of code if the test expression is evaluated to true . However, if the test expression is evaluated to false , it does nothing.

In this case, we can use an optional else block. Statements inside the body of else block are executed if the test expression is evaluated to false . This is known as the if-...else statement in Java.

The syntax of the if...else statement is:

Here, the program will do one task (codes inside if block) if the condition is true and another task (codes inside else block) if the condition is false .

How the if...else statement works?

If the condition is true, the code inside the if block is executed, otherwise, code inside the else block is executed

Example 3: Java if...else Statement

In the above example, we have a variable named number . Here, the test expression number > 0 checks if number is greater than 0.

Since the value of the number is 10 , the test expression evaluates to true . Hence code inside the body of if is executed.

Now, change the value of the number to a negative integer. Let's say -5 .

If we run the program with the new value of number , the output will be:

Here, the value of number is -5 . So the test expression evaluates to false . Hence code inside the body of else is executed.

3. Java if...else...if Statement

In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple other blocks.

Here, if statements are executed from the top towards the bottom. When the test condition is true , codes inside the body of that if block is executed. And, program control jumps outside the if...else...if ladder.

If all test expressions are false , codes inside the body of else are executed.

How the if...else...if ladder works?

If the first test condition if true, code inside first if block is executed, if the second condition is true, block inside second if is executed, and if all conditions are false, the else block is executed

Example 4: Java if...else...if Statement

In the above example, we are checking whether number is positive, negative, or zero . Here, we have two condition expressions:

  • number > 0 - checks if number is greater than 0
  • number < 0 - checks if number is less than 0

Here, the value of number is 0 . So both the conditions evaluate to false . Hence the statement inside the body of else is executed.

Note : Java provides a special operator called ternary operator , which is a kind of shorthand notation of if...else...if statement. To learn about the ternary operator, visit Java Ternary Operator .

4. Java Nested if..else Statement

In Java, it is also possible to use if..else statements inside an if...else statement. It's called the nested if...else statement.

Here's a program to find the largest of 3 numbers using the nested if...else statement.

Example 5: Nested if...else Statement

In the above programs, we have assigned the value of variables ourselves to make this easier.

However, in real-world applications, these values may come from user input data, log files, form submission, etc.

Table of Contents

  • Introduction
  • Java if (if-then) Statement
  • Example: Java if Statement
  • Java if...else (if-then-else) Statement
  • Example: Java if else Statement
  • Java if..else..if Statement
  • Example: Java if..else..if Statement
  • Java Nested if..else Statement

Sorry about that.

Related Tutorials

Java Tutorial

Chapter 7. Conditional execution

Recall our MovingBall program of Figure 6.3 , in which a red ball moved steadily down and to the right, eventually moving off the screen. Suppose that instead we want the ball to bounce when it reaches the window's edge. To do this, we need some way to test whether it has reached the edge. The most natural way of accomplishing this in Java is to use the if statement that we study in this chapter.

7.1. The if statement

An if statement tells the computer to execute a sequence of statements only if a particular condition holds. It is sometimes called a conditional statement , since it allows us to indicate that the computer should execute some statements only in some conditions.

if ( <thisIsTrue> ) {      <statementsToDoIfTrue> }

When the computer reaches the if statement, it evaluates the condition in parentheses. If the condition turns out to be true , then the computer executes the if statement's body and then continues to any statements following. If the condition turns out to be false , it skips over the body and goes directly to whatever follows the closing brace. This corresponds to the flowchart in Figure 7.1 .

Figure 7.1: A flowchart for the if statement.

An if statement looks a lot like a while loop: The only visual difference is that it uses the if keyword in place of while . And it acts like a while loop also, except that after completing the if statement's body, the computer does not consider whether to execute the body again.

The following fragment includes a simple example of an if statement in action.

double   num  =  readDouble (); if ( num  < 0.0) {      num  = - num ; }

In this fragment, we have a variable num referring to a number typed by the user. If num is less than 0, then we change num to refer to the value of - num instead, so that num will now be the absolute value of what the user typed. But if num is not negative, the computer will skip the num  = - num statement; num will still be the absolute value of what the user typed.

7.2. The bouncing ball

We can now turn to our MovingBall program, modifying it so that the ball will bounce off the edges of the window. To accomplish this, before each movement, we will test whether the ball has crossed an edge of the window: The movement in the x direction should invert if the ball has crossed the east or west side, and the movement in the y direction should invert if the ball has crossed the north or south side. The program of Figure 7.2 accomplishes this.

Figure 7.2: The BouncingBall program.   1    import   acm . program .*;   2    import   acm . graphics .*;   3    import   java . awt .*;   4      5    public   class   BouncingBall   extends   GraphicsProgram  {   6        public   void   run () {   7            GOval   ball  =  new   GOval (25, 25, 50, 50);   8            ball . setFilled ( true );   9            ball . setFillColor ( new   Color (255, 0, 0));  10            add ( ball );  11     12            double   dx  = 3;  13            double   dy  = -4;  14            while ( true ) {  15                pause (40);  16                if ( ball . getX () +  ball . getWidth () >=  getWidth ()  17                       ||  ball . getX () <= 0.0) {  18                    dx  = - dx ;  19               }  20                if ( ball . getY () +  ball . getHeight () >=  getHeight ()  21                       ||  ball . getY () <= 0.0) {  22                    dy  = - dy ;  23               }  24                ball . move ( dx ,  dy );  25           }  26       }  27   }

If you think about it carefully, the simulation of this program isn't perfect: There will be frames where the ball has crossed over the edge, so that only part of the circle is visible. This isn't a big problem, for a combination of reasons: First, the ball will be over the border only for a single frame (i.e., for only a fleeting few milliseconds), and second, the effect is barely visible because it affects only a few pixels of the ball's total size. Anyway, our eye expects to see a rubber ball flatten against the surface briefly before bouncing back in the opposite direction. If we were to repair this problem, then we would perceive the ball to be behaving more like a billiard ball. In any case, we won't attempt to repair the problem here.

7.3. The else clause

Sometimes we want a program to do one thing if the condition is true and another thing if the condition is false. In this case the else keyword comes in handy.

if ( <thisIsTrue> ) {      <statementsToDoIfTrue> }  else  {      <statementsToDoIfFalse> }

Figure 7.3 contains a flowchart diagramming this type of statement.

Figure 7.3: A flowchart for the else clause.

For example, if we wanted to compute the larger of two values typed by the user, then we might use the following code fragment.

double   first  =  readDouble (); double   second  =  readDouble (); double   max ; if ( first  >  second ) {      max  =  first ; }  else  {      max  =  second ; } print ( max );

This fragment will first read the two numbers first and second from the user. It then creates a variable max that will end up holding the larger of the two. This function says assign the value of first to max if first holds a larger value than second ; otherwise — it says — assign max the value of second .

Sometimes it's useful to string several possibilities together. This is possible by inserting else   if clauses into the code.

double   score  =  readDouble (); double   gpa ; if ( score  >= 90.0) {      gpa  = 4.0; }  else   if ( score  >= 80.0) {      gpa  = 3.0; }  else   if ( score  >= 70.0) {      gpa  = 2.0; }  else   if ( score  >= 60.0) {      gpa  = 1.0; }  else  {      gpa  = 0.0; }

You can string together as many else   if clauses as you want. Having an else clause at the end is not required.

Note that, if the user types 95 as the computer executes the above fragment, the computer would set gpa to refer to 4.0. It would not also set gpa to refer to 3.0, even though it's true that score  >= 80.0 . This is because the computer checks an else   if clause only if the preceding conditions all turn out to be false .

As an example using graphics, suppose we want our hot-air balloon animation to include a moment when the hot-air balloon is firing its burner, so it briefly goes up before it resumes its descent. To do this, we'll modify the loop in Figure 6.4 to track which frame is currently being drawn, and we'll use an if statement with else clauses to select in which direction the balloon should move for the current frame.

int   frame  = 0;  // tracks which frame we are on while ( balloon . getY () + 70 <  getHeight ()) {      pause (40);      if ( frame  < 100) {         // the balloon is in free-fall          balloon . move (1, 2);     }  else   if ( frame  < 200) {  // it fires its burner          balloon . move (1, -1);     }  else  {                  // it no longer fires its burner          balloon . move (1, 1);     }      frame ++; }

7.4. Braces

When the body of a while or if statement holds only a single statement, the braces are optional. Thus, we could write our max code fragment from earlier as follows, since both the if and the else clauses contain a single statement. (We could also include braces on just one of the two bodies.)

double   max ; if ( first  >  second )      max  =  first ; else      max  =  second ;

I recommend that you include the braces anyway. This saves you trouble later, should you decide to add additional statements into the body of the statement. And it makes it easier to keep track of braces, since each indentation level requires a closing right brace.

In fact, Java technically doesn't have an else   if clause. In our earlier gpa examples, Java would actually interpret the if statements as follows.

if ( score  >= 90.0) {      gpa  = 4.0; }  else      if ( score  >= 80.0) {          gpa  = 3.0;     }  else          if ( score  >= 70.0) {              gpa  = 2.0;         }  else              if ( score  >= 60.0) {                  gpa  = 1.0;             }  else  {                  gpa  = 0.0;             }

Each else clause includes exactly one statement — which happens to be an if statement with an accompanying else clause in each case. Thus, when we were talking about else   if clauses, we were really just talking about a more convenient way of inserting white space for the special case where an else clause contains a single if statement.

7.5. Variables and compile errors

7.5.1. variable scope.

Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared. This region of the program text where the variable is valid is called its scope .

Check out this illegal code fragment.

 29    if ( first  >  second ) {  30        double   max  =  first ;  31   }  else  {  32        double   max  =  second ;  33   }  34    print ( max );  // Illegal!

On trying to compile this, the compiler will point to line 34 and display a message saying something like, Cannot find symbol max . What's going on here is that the declaration of max inside the if 's body persists only until the brace closing that if statement's body; and the declaration of max in the else 's body persists only until the brace closing that body. Thus, at the end, outside either of these bodies, max does not exist as a variable.

A novice programmer might try to patch over this error by declaring max before the if statement.

double   max  = 0.0; if ( first  >  second ) {      double   max  =  first ;  // Illegal! }  else  {      double   max  =  second ;  // Illegal! } print ( max );

The Java compiler should respond by flagging the second and third declarations of max with a message like max is already defined. In Java, each time you label a variable with a type, it counts as a declaration; and you can only declare each variable name once. Thus, the compiler will understand the above as an attempt to declare two different variables with the same name. It will insist that each variable once and only once.

7.5.2. Variable initialization

Another common mistake of beginners is to use an else   if clause where an else clause is completely appropriate.

 46    double   max ;  47    if ( first  >  second ) {  48        max  =  first ;  49   }  else   if ( second  >=  first ) {  50        max  =  second ;  51   }  52    print ( max );

Surprisingly, the compiler will complain about line 52, with a message like variable max might not have been initialized. (Recall that initialization refers to the first assignment of a value to a variable.) The compiler is noticing that the print invocation uses the value of max , since it will send the variable's value as a parameter. But, it reasons, perhaps max may not yet have been assigned a value when it reaches that point.

In this particular fragment, the computer is reasoning that while the if and else   if bodies both initialize max , it may be possible for both conditions to be false ; and in that case, max will not be initialized. This may initially strike you as perplexing: Obviously, it can't be that both the if and the else   if condition turn out false . But our reasoning hinges on a mathematical fact that the compiler is not itself sophisticated enough to recognize.

You might hope for the compiler to be able to recognize such situations. But it is impossible for the compiler to reliably identify such situations. This results from what mathematicians and computer scientists call the halting problem . The halting problem asks for a program that reads another program and reliably predicts whether that other program will eventually reach its end. Such a program is provably impossible to write.

This result implies that there's no way to solve the initialization problem perfectly, because if we did have such a program, we could modify it to solve the halting problem. Our modification for solving the halting problem is fairly simple: Our modified program would first read the program for which we want to answer the halting question. Then we place a variable declaration at the program's beginning, and then at any point where the program would end we place a variable assignment. And finally we hand the resulting program into the supposed program for determining variable initialization. Out would pop the answer to the halting question for the program under inquiry.

That said, there's nothing preventing the compiler writers from trying at least to identify the easy cases. And you might hope that they'd be thorough enough to identify that given two numbers, the first is either less than, equal to, or greater than the second. But this would inevitably lead to a complex set of rules when the compiler identifies initialization and when not, and the Java designers felt it best to keep the rules simple enough for regular programmers to remember.

The solution in this case is to recognize that, in fact, we don't need the else   if condition: Whenever the if condition turns out to be false , we the else   if body to occur. Thus, doing that extra test both adds extra verbiage and slows down the program slightly. If use an else clause instead of an else   if , the compiler will reason successfully that max will be initialized, and it won't complain.

(Novice programmers are sometimes tempted to simply initialize max on line 46 to avoid the message. This removes the compiler message, and the program will work. But patching over compiler errors like this is a bad habit. You're better off addressing the problem at its root.)

By the way, Java compilers are some of strictest I've seen about uninitialized variables. It can occassionally be a bit irritating to have to repair a program with an alleged uninitialized variable, when we are certain that the program would run flawlessly as written. The reason the compiler is so aggressive is that it's aggressively trying to help you debug your programs. Suppose, for the sake of argument, that it was a real problem in the program. If the compiler didn't complain, you'd be relying on the test cases to catch the problem. If the test cases didn't catch it, you'd be misled into releasing a erroneous program. Even if they did catch it, you're stuck trying to figure out the cause, which can take quite a while. A problem like an uninitialized variable can be very difficult to track down by trial and error; but with the compiler pointing to it for you, it becomes much easier.

Describe all the errors in the following code fragment, and write a version correcting all of them.

int   k  =  readInt (); int   ch ; if   k  = 2 {      ch  = 1.0; } ch  *= 2;

Modify the BouncingBall program to provide the illusion of gravity. To do this, the y component of the ball's velocity should increase by a fixed amount (maybe 0.2 per frame), which accounts for the acceleration due to gravity. Also, when the ball bounces off an edge of the window, the velocity should become 90% of what it was previously; this way, each bounce will be successively smaller.

There are several subtleties involved with doing this well. Realistic bounces are relatively easy at the beginning, when the bounces are big; but as the bounces become much smaller, some peculiar behavior will likely appear: For example, the ball may appear to reach a point where bounces no longer become smaller, or it may appear to be stuck below the bottom border of the window.

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.

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.

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.

Vertex Academy

How to assign a value to a variable in java.

Facebook

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

Example No.1

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

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

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

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

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

Variables Announement Vertex Academy

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

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

int k = 10;

So, now you know that:

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

What is variable initialization?

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

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

Here's another example of variable initialization:

Example No.2

15 100 100000000 I love Java M 145.34567 3.14 true

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

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

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

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

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

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

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

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

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

LET’S SUMMARIZE:

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

assign value to a variable Vertex Academy

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

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

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

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

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

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

Facebook

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

You May Also Like

Software configuration, why is java so popular, software configuration on ubuntu.

variable assignment in if statement java

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

1.4. Expressions and Assignment Statements ¶

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

1.4.1. Assignment Statements ¶

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

Assignment statement

Figure 1: Assignment Statement (variable = expression) ¶

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

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

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

coding exercise

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

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

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

exercise

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

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

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

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

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

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

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

1.4.2. Incrementing the value of a variable ¶

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

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

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

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

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

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

1.4.3. Operators ¶

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

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

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

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

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

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

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

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

What is printed when the code segment is executed?

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

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

What is the value of the expression?

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

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

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

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

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

1.4.4. The Modulo Operator ¶

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

../_images/mod-py.png

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

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

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

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

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

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

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

1.4.5. FlowCharting ¶

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

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

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

Flow Chart

Figure 3: Example Flow Chart ¶

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

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

1.4.6. Storing User Input in Variables ¶

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

Program input and output

Figure 4: Program input and output ¶

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

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

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

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

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

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

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

Flow Chart

Figure 5: Flow Chart Reading User Input ¶

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

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

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

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

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

1.4.7. Programming Challenge : Dog Years ¶

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

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

1.4.8. Summary ¶

Arithmetic expressions include expressions of type int and double.

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

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

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

Operators can be used to construct compound expressions.

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

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

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

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

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

clear sunny desert yellow sand with celestial snow bridge

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

The 7 Layer OSI Model of IT Troubleshooting

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

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.

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

Array Variable Assignment in Java

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

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

1. Element Level Promotion

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

2. For Object Type Array

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

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

3. Dimension Matching

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

Please Login to comment...

Similar reads.

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java if statement

    variable assignment in if statement java

  2. Java if statement with Examples

    variable assignment in if statement java

  3. Java if Statement with Example

    variable assignment in if statement java

  4. Java If and Else

    variable assignment in if statement java

  5. Java If Statement

    variable assignment in if statement java

  6. If Statement in Java

    variable assignment in if statement java

VIDEO

  1. Assignment operators in java

  2. Assignment Statement and Constant Variable

  3. 6 storing values in variable, assignment statement

  4. Java

  5. Java for Testers

  6. Combining a Variable Definition and Assignment Statement

COMMENTS

  1. java

    Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it. Variables exist only in the scope they were created.

  2. Java if...else (With Examples)

    Output. The number is positive. Statement outside if...else block. In the above example, we have a variable named number.Here, the test expression number > 0 checks if number is greater than 0.. Since the value of the number is 10, the test expression evaluates to true.Hence code inside the body of if is executed.. Now, change the value of the number to a negative integer.

  3. Java if statement with Examples

    Working of if statement: Control falls into the if block. The flow jumps to Condition. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. The if-block or the body inside the if is executed. Flow steps out of the if block. Flowchart if statement:

  4. Programming via Java: Conditional execution

    The most natural way of accomplishing this in Java is to use the if statement that we study in this chapter. 7.1. The if statement. ... (Recall that initialization refers to the first assignment of a value to a variable.) The compiler is noticing that the print invocation uses the value of max, since it will send the variable's value as a ...

  5. Java if-else

    Java if-else. Decision-making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won't. In this article, we will learn about Java if-else.

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

    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.

  7. Java If ... Else

    Java has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of ...

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

  9. java

    15. You can use java ternary operator, this statement can be read as, If testCondition is true, assign the value of value1 to result; otherwise, assign the value of value2 to result. simple example would be, In above code, if the variable a is less than b, minVal is assigned the value of a; otherwise, minVal is assigned the value of b.

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

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

  11. 1.4. Expressions and Assignment Statements

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

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

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

  14. Java Assignment Operators

    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; The += is called the addition assignment operator. Other shorthand operators are shown below table. Operator. Name.

  15. java

    Java string assignment from if/else statement. 0. How do I declare String from result of IF Statement? 1. How to define variables in if statements and use them outside of that statement? 3. How can you assign a variable that is defined inside an if else statement. 0.

  16. Definite Assignment in Java

    The definite assignment will consider the structure of expressions and statements. The Java compiler will decide that "k" is assigned before its access, like an argument with the method invocation in the code. It is because the access will occur if the value of the expression is accurate.

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

  18. java

    Suppose i want to assign the variable named involved the value true if another variable, say the variable named p, has a value between 50 and 150. ... import java.util.Scanner; public class Main{...} - Vitaliy Tretyakov. ... if else statement assignment. 0. Boolean use in an if statement. Hot Network Questions

  19. java

    In java, you don't have implicit casting. So non-boolean values or not automatically transformed to booleans. In the first case, the result of the statements is an int, which is non-boolean, which will not work. The last case, the result is boolean, which can be evaluated in an if-statement.

  20. PDF Arrays

    java.util.Scanner input = new java.util.Scanner(System.in); ... •You still must use an index variable if you wish to traverse the array in a different order or change the elements in the array CSE 11, Spring 2024 16. Copying arrays •The assignment statement does not copy the contents, it only copies the reference value list2 = list1;

  21. Compound assignment operators in Java

    The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction assignment operator) 3. *= (compound multiplication assignment operator) 4. /= (compound division assignment operator) 5. %= (compound modulo assignment operator)

  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.