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.

The if-then and if-then-else Statements

The if-then statement.

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true . For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.

In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false . You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.

The following program, IfElseDemo , assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.

The output from the program is:

You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60 . However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

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

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

  • Java One Line if Statement
  • Java Howtos

Ternary Operator in Java

One line if-else statement using filter in java 8.

Java One Line if Statement

The if-else statement in Java is a fundamental construct used to conditionally execute blocks of code based on certain conditions. However, it often requires multiple lines to define a simple if-else block, which may not always be ideal, especially for concise and readable code.

Fortunately, Java provides a shorthand form called the ternary operator, which allows us to write a one-line if-else statement.

The ternary operator in Java, denoted as ? : , provides a compact way to represent an if-else statement. Its syntax is as follows:

Here, condition is evaluated first. If condition is true, expression1 is executed; otherwise, expression2 is executed.

Example 1: Assigning a Value Based on a Condition

This code uses the ternary operator to determine if a student has made a distinction based on their exam marks.

If marks is greater than 70 , the string Yes is assigned to the distinction variable and the output will be:

If marks is less than or equal to 70 , the string No is assigned to the distinction variable and the output will be:

Example 2: Printing a Message Conditionally

This code defines a Boolean variable isRaining with the value true and uses a ternary operator to print a message based on the value of isRaining .

If isRaining is true , it prints Bring an umbrella ; otherwise, it prints No need for an umbrella .

Example 3: Returning a Value from a Method

In this code, we’re assigning the maximum of a and b to the variable max using a ternary operator. The maximum value is then printed to the console.

You can try it yourself by replacing the values of a and b with your desired values to find the maximum between them.

Java 8 introduced streams and the filter method, which operates similarly to an if-else statement. It allows us to filter elements based on a condition.

Here’s its syntax:

Predicate is a functional interface that takes an argument and returns a Boolean. It’s often used with lambda expressions to define the condition for filtering.

Here’s a demonstration of a one-line if-else -like usage using the filter method in Java 8 streams.

As we can see, this example demonstrates a one-line usage of an if-else -like structure using the filter method. It first defines a list of words and then applies a stream to this list.

Within the map function, a lambda expression is used to check if each word starts with the letter b . If a word meets this condition, it remains unchanged; otherwise, it is replaced with the string Not available .

Finally, the resulting stream is collected back into a list using collect(Collectors.toList()) . The output shows the effect of this one-line if-else -like usage, modifying the words based on the specified condition.

Let’s see another example.

This example code also showcases the use of Java 8 streams to filter and print elements from a list based on a condition. The code begins by importing necessary packages and defining a class named Java8Streams .

Inside the main method, a list of strings, stringList , is created with elements 1 and 2 . The stream is then created from this list using the stream() method.

Next, the filter method is applied to this stream, utilizing a lambda expression as the predicate. The lambda expression checks if the string is equal to 1 .

If this condition is true, the string is allowed to pass through the filter; otherwise, it is discarded.

Finally, the forEach method is used to iterate over the filtered stream and print each element that passed the filter. It uses a method reference System.out::println to achieve this.

In summary, one-line if statements in Java offer a compact and efficient way to handle simple conditional logic. By understanding the syntax and appropriate usage, you can write concise code while maintaining readability and clarity.

Rashmi Patidar avatar

Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.

Related Article - Java Statement

  • Difference Between break and continue Statements in Java
  • The continue Statement in Java

Home » Java Tutorial » Java Variables

Java Variables

Summary : in this tutorial, you’ll learn about how to use Java variables to store and manage data in programs.

Introduction to Java variables

In Java, variables are used to store and manage data. Java is strongly typed, therefore, you need to specify the type of variables when you define them.

To define a variable, you specify its data type e.g., integer, followed by a name. For example, the following defines a variable named age:

In this example, int is the integer type and age is the name of the variable. Later you’ll learn more about other types in Java .

After defining a variable, you can assign a value to it. For example:

In this example, we assign 22 to the age variable. If you print out the variable age using the System.out.println() method, you’ll see the number 22 in the output:

Here’s a complete program:

Java allows you to define a variable and initialize its value at the same time like this:

That one line of code is equivalent to two lines of code and is more concise:

Java is statically typed. It means that once you define a variable, you cannot assign a value of a different type to it.

For example, the following attempts to assign a string to an integer variable, which results in an error:

Naming variables in Java

By convention, you should use only letters and numbers to name variables. Note that you can use some special symbols for naming variables technically but it is not widely used in practice.

Keep in mind that the variable names cannot start with numbers like:

In Java, variable names use camel case style. It means that you start each word after the first with upper case and all other letters are lower case. For example:

Assign a variable to another variable

It’s possible to assign a variable to another. For example:

In this example, we have two variables with type int and values 100 and 80 respectively. In the third line, we assign the value of the variable cost to the variable price.

Final variables in Java

Final variables are variables whose values cannot be changed once set. To define a final variable, you use the final modifier before the data type. For example:

In this example, we define the maxAge as a final variable. Since we initialize its value immediately, later we cannot modify its value like this:

It’s possible to define a final variable without initialization and set its value later as follows:

The final variables are useful for creating constants and ensuring immutability. As you progress to more complex Java applications, you’ll find them very valuable for writing robust and more maintainable code.

“variable might not have been initialized” error

Java doesn’t allow you to use uninitialized variables. If you declare a variable but don’t initialize its value or assign a value to it, and you attempt to access its value, you’ll get the error: “variable might not have been initialized”. For example:

If you build the program, you’ll get the error. To fix it, you can initialize the variable a value. For example:

  • Use variables to store and manage data in a program.
  • To define a variable, specify a data type, followed by a name and an optional initial value.
  • Use only letters and numbers to name variables.
  • Use camel case for naming variables.
  • Final variables cannot changed once set.

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 Best Keyboard Tilt for Reducing Wrist Pain to Zero

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.

Live Training, Prepare for Interviews, and Get Hired

01 Career Opportunities

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

02 Beginner

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

Assignment operator in Java

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

03 Intermediate

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

04 Training Programs

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

Assignment operator in Java

Java Programming For Beginners Free Course

Assignment operators in java: an overview.

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

What are the Assignment Operators in Java?

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

The general syntax for a simple assignment statement is:

And for a compound assignment statement:

Read More - Advanced Java Interview Questions

Types of Assignment Operators in Java

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

1. Simple Assignment Operator (=):

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

Explanation

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

Read More - Java Developer Salary

5. Division Operator (/=):

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

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

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

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

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

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

About Author

Author image

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

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

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

Java variables.

  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory location name for the data.

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.
  • In Java, all variables must be declared before use.

How to Declare Variables in Java?

We can declare variables in Java as pictorially depicted below as a visual aid.

Variables in Java

From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are:

  • datatype : Type of data that can be stored in this variable. 
  • data_name: Name was given to the variable. 

In this way, a name can only be given to a memory location. It can be assigned values in two ways: 

  • Variable Initialization
  • Assigning value by taking input

How to Initialize Variables in Java?

It can be perceived with the help of 3 components that are as follows:

  • datatype : Type of data that can be stored in this variable.
  • variable_name : Name given to the variable.
  • value : It is the initial value stored in the variable.

Java Variables Syntax

Illustrations:  

Types of Variables in Java

Now let us discuss different types of variables  which are listed as follows: 

  • Local Variables
  • Instance Variables
  • Static Variables

Types of Variables in Java

Let us discuss the traits of every type of variable listed here in detail.

1. Local Variables  

A variable defined within a block or method or constructor is called a local variable. 

  • These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function.
  • The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
  • Initialization of the local variable is mandatory before using it in the defined scope.

Time Complexity of the Method:

Below is the implementation of the above approach:

2. Instance Variables

Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block. 

  • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
  • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used.
  • Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
  • Instance variables can be accessed only by creating objects.
  • We initialize instance variables using constructors while creating an object. We can also use instance blocks to initialize the instance variables.

The complexity of the method:

3. static variables.

Static variables are also known as class variables. 

  • These variables are declared similarly to instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor, or block.
  • Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many objects we create.
  • Static variables are created at the start of program execution and destroyed automatically when execution ends.
  • Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null , for float it is 0.0f , for int it is 0 , for Wrapper classes like Integer it is null, etc.
  • If we access a static variable like an instance variable (through an object), the compiler will show a warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically.
  • If we access a static variable without the class name, the compiler will automatically append the class name. But for accessing the static variable of a different class, we must mention the class name as 2 different classes might have a static variable with the same name.
  • Static variables cannot be declared locally inside an instance method.
  • Static blocks can be used to initialize static variables.

Differences Between the Instance Variables and the Static Variables

Now let us discuss the differences between the Instance variables and the Static variables:

  • Each object will have its own copy of an instance variable, whereas we can only have one copy of a static variable per class, irrespective of how many objects we create. Thus, static variables are good for memory management .
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of a static variable, changes will be reflected in other objects as static variables are common to all objects of a class.
  • We can access instance variables through object references, and static variables can be accessed directly using the class name .
  • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops.

Syntax: Static and instance variables

The Important points to remember in the articles are mentioned below:

  • Variables in Java is a data container that saves the data values during Java program execution.
  • There are three types of variables in Java Local variables, static variables, and instance variables.

FAQs on Variables in Java

Q1. what are variables in java.

Variables are the containers in Java that can store data values inside them.

Q2. What are the 3 types of variables in Java?

There are three types of variables in Java are mentioned below: Local Variables Static Variables Instance Variables

Q3. How to declare variables in Java examples?

We can declare variables in java with syntax as mentioned below: data_type variable_name; Example: // Integer datatype with var1 name int var1;
  • Rules of Variable Declaration in Java
  • Scope of Variables in Java
  • Comparison of static keywords in C++ and Java
  • Are static local variables allowed in Java?
  • Instance Variable Hiding in Java

Please Login to comment...

Similar reads.

  • java-basics

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Java - variable types. how to create a variable in java, the history of java, why is java so popular.

IMAGES

  1. Variables in Java

    java if variable assignment

  2. Variables in Java

    java if variable assignment

  3. Java

    java if variable assignment

  4. How To Assign A File To A Variable In Java? Update New

    java if variable assignment

  5. 1.4. Expressions and Assignment Statements

    java if variable assignment

  6. Variables and Data Types in Java With Example

    java if variable assignment

VIDEO

  1. Java

  2. Assignment operators in java

  3. Java for Testers

  4. Mastering Java Variables: A Complete Guide

  5. Instance Variables

  6. variable in java and type of variable

COMMENTS

  1. java

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

  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. Programming via Java: Conditional execution

    Variable scope. Java allows you to declare variables within the body of a while or 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 parameter.

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

  5. The if-then and if-then-else Statements (The Java™ Tutorials > Learning

    The if-then Statement. The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true.For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as ...

  6. Java One Line if Statement

    In this code, we're assigning the maximum of a and b to the variable max using a ternary operator. The maximum value is then printed to the console. You can try it yourself by replacing the values of a and b with your desired values to find the maximum between them.. One Line if-else Statement Using filter in Java 8. Java 8 introduced streams and the filter method, which operates similarly ...

  7. Java if-else

    Java if-else Flowchart. if-else Program in Java Dry-Run of if-else statements 1. Program starts. 2. i is initialized to 20. 3. if-condition is checked. 20<15, yields false. 4. flow enters the else block. 4.a) "i is greater than 15" is printed 5. "Outside if-else block" is printed. Below is the implementation of the above statements: Java

  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. How can you assign a variable a value inside a if statement in Java

    In plain English, you can give a variable a value inside an if statement, but you cannot create a variable inside an if statement. The reason for this is because there is a possibility that the code inside the if statement will never run if the if conditions are never met.

  10. Java Variables

    It's possible to assign a variable to another. For example: int price = 100; int cost = 80; price = cost; Code language: Java (java) In this example, we have two variables with type int and values 100 and 80 respectively. In the third line, we assign the value of the variable cost to the variable price. Final variables in Java. Final ...

  11. 1.7 Java

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

  12. java

    It could be something like this: /** * Assumes the monetary value supplied is a floating point value. * * @param price (double) Will return null if 0 or less is supplied.

  13. Java if statement with Examples

    Decision Making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions. The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

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

  15. Assignment operator in Java

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

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

  17. Java Assignment Operators

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

  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. How do i do this? I've tried the following: import java.util.Scanner;

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

    char letter = 'M'; 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. 1. double sum = 145.34567;

  20. Java Assignment operators

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

  21. variable assignment

    However, with a JDK 1.4 on Solaris I think that that the value is null (like if the assignment was performed even though the exception is thrown). This is obviously linked to a bug and we will deploy a version without the assignment just to make sure but we would like to know if one of you also noticed this or have some kind of explanation to ...