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

use of assignment statement in 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.

Method

Description

nextLine()

Scans all input up to the line break as a String

next()

Scans the next token of the input as a String

nextInt()

Scans the next token of the input as an int

nextDouble()

Scans the next token of the input as a double

nextBoolean()

Scans the next token of the input as a boolean

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.

Java Tutorial

Java Tutorial

  • Java - Home
  • Java - Overview
  • Java - History
  • Java - Features
  • Java Vs. C++
  • JVM - Java Virtual Machine
  • Java - JDK vs JRE vs JVM
  • Java - Hello World Program
  • Java - Environment Setup
  • Java - Basic Syntax
  • Java - Variable Types
  • Java - Data Types
  • Java - Type Casting
  • Java - Unicode System
  • Java - Basic Operators
  • Java - Comments
  • Java - User Input
  • Java - Date & Time

Java Control Statements

  • Java - Loop Control
  • Java - Decision Making
  • Java - If-else
  • Java - Switch
  • Java - For Loops
  • Java - For-Each Loops
  • Java - While Loops
  • Java - do-while Loops
  • Java - Break
  • Java - Continue

Object Oriented Programming

  • Java - OOPs Concepts
  • Java - Object & Classes
  • Java - Class Attributes
  • Java - Class Methods
  • Java - Methods
  • Java - Variables Scope
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Aggregation
  • Java - Polymorphism
  • Java - Overriding
  • Java - Method Overloading
  • Java - Dynamic Binding
  • Java - Static Binding
  • Java - Instance Initializer Block
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner Classes
  • Java - Static Class
  • Java - Anonymous Class
  • Java - Singleton Class
  • Java - Wrapper Classes
  • Java - Enums
  • Java - Enum Constructor
  • Java - Enum Strings
  • Java - Reflection

Java Built-in Classes

  • Java - Number
  • Java - Boolean
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Math Class

Java File Handling

  • Java - Files
  • Java - Create a File
  • Java - Write to File
  • Java - Read Files
  • Java - Delete Files
  • Java - Directories
  • Java - I/O Streams

Java Error & Exceptions

  • Java - Exceptions
  • Java - try-catch Block
  • Java - try-with-resources
  • Java - Multi-catch Block
  • Java - Nested try Block
  • Java - Finally Block
  • Java - throw Exception
  • Java - Exception Propagation
  • Java - Built-in Exceptions
  • Java - Custom Exception
  • Java - Annotations
  • Java - Logging
  • Java - Assertions

Java Multithreading

  • Java - Multithreading
  • Java - Thread Life Cycle
  • Java - Creating a Thread
  • Java - Starting a Thread
  • Java - Joining Threads
  • Java - Naming Thread
  • Java - Thread Scheduler
  • Java - Thread Pools
  • Java - Main Thread
  • Java - Thread Priority
  • Java - Daemon Threads
  • Java - Thread Group
  • Java - Shutdown Hook

Java Synchronization

  • Java - Synchronization
  • Java - Block Synchronization
  • Java - Static Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Interrupting a Thread
  • Java - Thread Control
  • Java - Reentrant Monitor

Java Networking

  • Java - Networking
  • Java - Socket Programming
  • Java - URL Processing
  • Java - URL Class
  • Java - URLConnection Class
  • Java - HttpURLConnection Class
  • Java - Socket Class
  • Java - ServerSocket Class
  • Java - InetAddress Class
  • Java - Generics

Java Collections

  • Java - Collections
  • Java - Collection Interface

Java Interfaces

  • Java - List Interface
  • Java - Queue Interface
  • Java - Map Interface
  • Java - SortedMap Interface
  • Java - Set Interface
  • Java - SortedSet Interface

Java Data Structures

  • Java - Data Structures
  • Java - Enumeration

Java Collections Algorithms

  • Java - Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Comparable Interface in Java

Advanced Java

  • Java - Command-Line Arguments
  • Java - Lambda Expressions
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Javadoc Comments
  • Java - Autoboxing and Unboxing
  • Java - File Mismatch Method
  • Java - REPL (JShell)
  • Java - Multi-Release Jar Files
  • Java - Private Interface Methods
  • Java - Inner Class Diamond Operator
  • Java - Multiresolution Image API
  • Java - Collection Factory Methods
  • Java - Module System
  • Java - Nashorn JavaScript
  • Java - Optional Class
  • Java - Method References
  • Java - Functional Interfaces
  • Java - Default Methods
  • Java - Base64 Encode Decode
  • Java - Switch Expressions
  • Java - Teeing Collectors
  • Java - Microbenchmark
  • Java - Text Blocks
  • Java - Dynamic CDS archive
  • Java - Z Garbage Collector (ZGC)
  • Java - Null Pointer Exception
  • Java - Packaging Tools
  • Java - NUMA Aware G1
  • Java - Sealed Classes
  • Java - Record Classes
  • Java - Hidden Classes
  • Java - Pattern Matching
  • Java - Compact Number Formatting
  • Java - Programming Examples
  • Java - Garbage Collection
  • Java - JIT Compiler

Java Miscellaneous

  • Java - Recursion
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Process API Improvements
  • Java - Stream API Improvements
  • Java - Enhanced @Deprecated Annotation
  • Java - CompletableFuture API Improvements
  • Java - Maths Methods
  • Java - Streams
  • Java - Datetime Api
  • Java 8 - New Features
  • Java 9 - New Features
  • Java 10 - New Features
  • Java 11 - New Features
  • Java 12 - New Features
  • Java 13 - New Features
  • Java 14 - New Features
  • Java 15 - New Features
  • Java 16 - New Features
  • Java - Keywords Reference

Java APIs & Frameworks

  • JDBC Tutorial
  • SWING Tutorial
  • AWT Tutorial
  • Servlets Tutorial
  • JSP Tutorial

Java Class References

  • Java - Scanner
  • Java - Date
  • Java - ArrayList
  • Java - Vector
  • Java - Stack
  • Java - PriorityQueue
  • Java - Deque Interface
  • Java - LinkedList
  • Java - ArrayDeque
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - TreeMap
  • Java - IdentityHashMap
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - TreeSet
  • Java - BitSet
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java - Collection
  • Java - Array

Java Useful Resources

  • Java Compiler
  • Java - Questions and Answers
  • Java 8 - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Java - Assignment Operators with Examples

Java assignment operators.

Following are the assignment operators supported by Java language −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C
+= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C − A
*= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −

In this example, we're creating three variables a,b and c and using assignment operators . We've performed simple assignment, addition AND assignment, subtraction AND assignment and multiplication AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Divide AND assignment, Multiply AND assignment, Modulus AND assignment, bitwise exclusive OR AND assignment, OR AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Left shift AND assignment, Right shift AND assignment, operations and printed the results.

refresh java logo

  • Basics of Java
  • ➤ Java Introduction
  • ➤ History of Java
  • ➤ Getting started with Java
  • ➤ What is Path and Classpath
  • ➤ Checking Java installation and Version
  • ➤ Syntax in Java
  • ➤ My First Java Program
  • ➤ Basic terms in Java Program
  • ➤ Runtime and Compile time
  • ➤ What is Bytecode
  • ➤ Features of Java
  • ➤ What is JDK JRE and JVM
  • ➤ Basic Program Examples
  • Variables and Data Types
  • ➤ What is Variable
  • ➤ Types of Java Variables
  • ➤ Naming conventions for Identifiers
  • ➤ Data Type in Java
  • ➤ Mathematical operators in Java
  • ➤ Assignment operator in Java
  • ➤ Arithmetic operators in Java
  • ➤ Unary operators in Java
  • ➤ Conditional and Relational Operators
  • ➤ Bitwise and Bit Shift Operators
  • ➤ Operator Precedence
  • ➤ Overflow Underflow Widening Narrowing
  • ➤ Variable and Data Type Programs
  • Control flow Statements
  • ➤ Java if and if else Statement
  • ➤ else if and nested if else Statement
  • ➤ Java for Loop
  • ➤ Java while and do-while Loop
  • ➤ Nested loops
  • ➤ Java break Statement
  • ➤ Java continue and return Statement
  • ➤ Java switch Statement
  • ➤ Control Flow Program Examples
  • Array and String in Java
  • ➤ Array in Java
  • ➤ Multi-Dimensional Arrays
  • ➤ for-each loop in java
  • ➤ Java String
  • ➤ Useful Methods of String Class
  • ➤ StringBuffer and StringBuilder
  • ➤ Array and String Program Examples
  • Classes and Objects
  • ➤ Classes in Java
  • ➤ Objects in Java
  • ➤ Methods in Java
  • ➤ Constructors in Java
  • ➤ static keyword in Java
  • ➤ Call By Value
  • ➤ Inner/nested classes in Java
  • ➤ Wrapper Classes
  • ➤ Enum in Java
  • ➤ Initializer blocks
  • ➤ Method Chaining and Recursion
  • Packages and Interfaces
  • ➤ What is package
  • ➤ Sub packages in java
  • ➤ built-in packages in java
  • ➤ Import packages
  • ➤ Access modifiers
  • ➤ Interfaces in Java
  • ➤ Key points about Interfaces
  • ➤ New features in Interfaces
  • ➤ Nested Interfaces
  • ➤ Structure of Java Program
  • OOPS Concepts
  • ➤ What is OOPS
  • ➤ Inheritance in Java
  • ➤ Inheritance types in Java
  • ➤ Abstraction in Java
  • ➤ Encapsulation in Java
  • ➤ Polymorphism in Java
  • ➤ Runtime and Compile-time Polymorphism
  • ➤ Method Overloading
  • ➤ Method Overriding
  • ➤ Overloading and Overriding Differences
  • ➤ Overriding using Covariant Return Type
  • ➤ this keyword in Java
  • ➤ super keyword in Java
  • ➤ final keyword in Java

Assignment Operator in Java with Example

Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types :

  • Assignment operator or simple assignment operator
  • Compound assignment operators

What is assignment operator in java

The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand(variable) on its left side. For example :

The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be in the form of a constant value, a variable name, an expression, a method call returning a compatible value or a combination of these.

The value at right side of assignment operator must be compatible with the data type of left side variable, otherwise compiler will throw compilation error. Following are incorrect assignment :

Another important thing about assignment operator is that, it is evaluated from right to left . If there is an expression at right side of assignment operator, it is evaluated first then the resulted value is assigned in left side variable.

Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted value( 60 ) is assigned into x . Similarly in statement a = b = c , first the value of c which is 30 is assigned into b and then the value of b which is now 30 is assigned into a .

The variable at left side of an assignment operator can also be a non-primitive variable. For example if we have a class MyFirstProgram , we can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.

Is == an assignment operator ?

No , it's not an assignment operator, it's a relational operator used to compare two values.

Is assignment operator a binary operator

Yes , as it requires two operands.

Assignment operator program in Java

a = 2 b = 2 c = 4 d = 4 e = false

Java compound assignment operators

The assignment operator can be mixed or compound with other operators like addition, subtraction, multiplication etc. We call such assignment operators as compound assignment operator. For example :

Here the statement a += 10; is the short version of a = a + 10; the operator += is basically addition compound assignment operator. Similarly b *= 5; is short version of b = b * 5; the operator *= is multiplication compound assignment operator. The compound assignment can be in more complex form as well, like below :

List of all assignment operators in Java

The table below shows the list of all possible assignment(simple and compound) operators in java. Consider a is an integer variable for this table.

Operator Example Same As
= a = 10 a = 10
+= a += 5 a = a + 5
-= a -= 3 a = a - 3
*= a *= 6 a = a * 6
/= a /= 5 a = a / 5
%= a %= 7 a = a % 7
&= a &= 3 a = a & 3
|= a |= 3 a = a | 3
^= a ^= 2 a = a ^ 2
>>= a >>= 3 a = a >> 3
>>>= a >>>= 3 a = a >>> 3
<<= a <<= 2 a = a << 2

How many assignment operators are there in Java ?

Including simple and compound assignment we have total 12 assignment operators in java as given in above table.

What is shorthand operator in Java ?

Shorthand operators are nothing new they are just a shorter way to write something that is already available in java language. For example the code a += 5 is shorter way to write a = a + 5 , so += is a shorthand operator. In java all the compound assignment operator(given above) and the increment/decrement operators are basically shorthand operators.

Compound assignment operator program in Java

a = 20 b = 80 c = 30 s = 64 s2 = 110 b2 = 15

What is the difference between += and =+ in Java?

An expression a += 1 will result as a = a + 1 while the expression a =+ 1 will result as a = +1 . The correct compound statement is += , not =+ , so do not use the later one.

facebook page

Java Assignment Operators

Java programming tutorial index.

The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign = .

In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:

Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables.

  • ▼Java Tutorial
  • Introduction
  • Java Program Structure
  • Java Primitive data type
  • ▼Development environment setup
  • Download and Install JDK, Eclipse (IDE)
  • Compiling, running and debugging Java programs
  • ▼Declaration and Access control
  • Class, methods, instance variables
  • Java Packages
  • ▼OOPS Concepts
  • Java Object Oriented Programming concepts
  • Is-A and Has-A relationship
  • ▼Assignments
  • Arrays - 2D array and Multi dimension array
  • Wrapper classes
  • ▼Operators
  • Assignment Operator
  • Arithmetic Operator
  • Conditional Operator
  • Logical Operator
  • ▼Flow Control
  • Switch Satement
  • While and Do loop
  • Java Branching Statements
  • ▼Exceptions
  • Handling Exceptions
  • Checked and unchecked
  • Custom Exception
  • Try with resource feature of Java 7
  • ▼String Class
  • String Class
  • Important methods of String class with example
  • String buffer class and string builder class
  • ▼File I/O and serialization
  • File Input and Output
  • Reading file
  • Writing file
  • Java Property File Processing
  • Java Serialization
  • ▼Java Collection
  • Java Collection Framework
  • Java ArrayList and Vector
  • Java LinkedList Class
  • Java HashSet
  • Java TreeSet
  • Java Linked HashSet
  • Java Utility Class
  • ▼Java Thread
  • Java Defining, Instantiating and Starting Thread
  • Java Thread States and Transitions
  • Java Thread Interaction
  • Java Code Synchronization
  • ▼Java Package
  • ▼Miscellaneous
  • Garbage Collection in Java
  • BigDecimal Method

Java Assignment Operators

Description.

Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.

Assignment can be of various types. Let’s discuss each in detail.

Primitive Assignment:

The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.

Primitive Casting

Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.

assignment operator image-1

For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.

assignment operator image-2

Assigning Literal that is too large for a variable

When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)

Java Code: Go to the editor

assignment operator image-3

Reference variable assignment

We can assign newly created object to object reference variable as below

First line will do following things,

  • Makes a reference variable named s of type String
  • Creates a new String object on the heap memory
  • Assigns the newly created String object to the reference variables

You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.

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:

The += is called the addition assignment operator. Other shorthand operators are shown below table

Operator Name Example Equivalent
+= Addition assignment i+=5; i=i+5
-= Subtraction assignment j-=10; j=j-10;
*= Multiplication assignment k*=2; k=k*2;
/= Division assignment x/=10; x=x/10;
%= Remainder assignment a%=4; a=a%4;

Below is the sample program explaining assignment operators:

assignment operator image-4

  • Assigning a value to can be straight forward or casting.
  • If we assign the value which is out of range of variable type then 2’s complement is assigned.
  • Java supports shortcut/compound assignment operator.

Java Code Editor:

Previous: Wrapper classes Next: Arithmetic Operator

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

JavaHyperText and Data Structures
  • Java HyperText
  • Style Guide
  • 0. Create project
  • 1. Show line numbers
  • 2. Import preferences for automatic formatting
  • 3. Reset layout
  • 4. Syntax help
  • 5. Open 2 files
  • 6. ToDO comments
  • 7. JUnit testing
  • 8. Assert statement
  • 9. Generating javadoc
  • 10. Red square: terminating programs
  • 11. Remove/add imports
  • 12. Use UTF-8 character encoding
  • 1. API documentation
  • 3. Using Strings
  • Introduction
  • 1. Assignment statement
  • 2. New-expression
  • 3. Method calls
  • 2. Try-statement
  • 1. Output of thrown exceptions
  • 2. Throwable objects
  • 3. Try-stmt/propagation
  • 4. Throw-statement
  • 5. Throws-clause
  • Abstract classes interfaces
  • Iterator & Iterable
  • Program correctness
  • 1. Introduction
  • 2. Developing loops
  • 3. Finding an invariant
  • Stepwise refinement
  • Intro to recursion
  • Recursion on linked lists
  • Recursion on trees
  • Backtracking
  • Shortest path

1. How to execute the assignment statement

1. explaining how to execute the assignment statement.

use of assignment statement in java

2. Homework assignment HW1

The first question is easy ---you can copy from the first video or its transcript on the pdf file. Questions 2 and 3 ask about the if-statement and if-else statement. These are the same as in just about any programming language, except for the syntax, of course. So use your knowledge of these statements in whatever programming language you know.

1. Write the algorithm for executing the Java assignment statement <variable>= <expression>; 2. Write the algorithm for executing the Java if-statement               if (<boolean-expression>) <statement 1> 3. Write the algorithm for executing the Java if-else-statement               if (<boolean-expression>) <statement 1> else <statement 2> 4. Tell us in a few words what you thought of the videos on presenting algorithms in English and executing the assignment statement, their message, and the homework.

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.

Expressions, Statements, and Blocks

Now that you understand variables and operators, it's time to learn about expressions , statements , and blocks . Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks.

Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below:

The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int . As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String .

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:

In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first:

You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following:

If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent:

When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( ; ).

  • Assignment expressions
  • Any use of ++ or --
  • Method invocations
  • Object creation expressions

Such statements are called expression statements . Here are some examples of expression statements.

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements . A declaration statement declares a variable. You've seen many examples of declaration statements already:

Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next section, Control Flow Statements

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo , illustrates the use of blocks:

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

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

What Is an Assignment Statement in Java?

...

Java programs store data values in variables. When a programmer creates a variable in a Java application, he declares the type and name of the variable, then assigns a value to it. The value of a variable can be altered at subsequent points in execution using further assignment operations. The assignment statement in Java involves using the assignment operator to set the value of a variable. The exact syntax depends on the type of variable receiving a value.

Advertisement

Video of the Day

In Java, variables are strongly typed. This means that when you declare a variable in a Java program, you must declare its type, followed by its name. The following sample Java code demonstrates declaring two variables, one of primitive-type integer and one of an object type for a class within the application: int num; ApplicationHelper myHelp;

Once a program contains a variable declaration, the kind of value assigned to the variable must be suited to the type declared. These variable declarations could be followed by assignment statements on subsequent lines. However, the assignment operation could also take place on the same line as the declaration.

Assignment in Java is the process of giving a value to a primitive-type variable or giving an object reference to an object-type variable. The equals sign acts as assignment operator in Java, followed by the value to assign. The following sample Java code demonstrates assigning a value to a primitive-type integer variable, which has already been declared: num = 5;

The assignment operation could alternatively appear within the same line of code as the declaration of the variable, as follows: int num = 5;

The value of the variable can be altered again in subsequent processing as in this example: num++;

This code increments the variable value, adding a value of one to it.

Instantiation

When the assignment statement appears with object references, the assignment operation may also involve object instantiation. When Java code creates a new object instance of a Java class in an application, the "new" keyword causes the constructor method of the class to execute, instantiating the object. The following sample code demonstrates instantiating an object variable: myHelp = new ApplicationHelper();

This could also appear within the same line as the variable declaration as follows: ApplicationHelper myHelp = new ApplicationHelper();

When this line of code executes, the class constructor method executes, returning an instance of the class, a reference to which is stored by the variable.

Referencing

Once a variable has been declared and assigned a value, a Java program can refer to the variable in subsequent processing. For primitive-type variables, the variable name refers to a stored value. For object types, the variable refers to the location of the object instance in memory. This means that two object variables can point to the same instance, as in the following sample code: ApplicationHelper myHelp = new ApplicationHelper(); ApplicationHelper sameHelp = myHelp;

This syntax appears commonly when programs pass object references as parameters to class methods.

  • Oracle: The Java Tutorials - Variables
  • Oracle: The Java Tutorials - Assignment, Arithmetic, and Unary Operators
  • Oracle: The Java Tutorials - Primitive Data Types
  • Oracle: The Java Tutorials - Creating Objects
  • Oracle: The Java Tutorials - What Is an Object?
  • Oracle: The Java Tutorials - Summary of Variables
  • Java Language Specification; Types, Values, and Variables; 2000
  • Oracle: The Java Tutorials - Understanding Instance and Class Members
  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Compound assignment operators in Java

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

Implementation of all compound assignment operator

Rules for resolving the Compound assignment operators

At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable.
  • First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Examples : Resolving the statements with Compound assignment operators

We all know that whenever we are assigning a bigger value to a smaller data type variable then we have to perform explicit type casting to get the result without any compile-time error. If we did not perform explicit type-casting then we will get compile time error. But in the case of compound assignment operators internally type-casting will be performed automatically, even we are assigning a bigger value to a smaller data-type variable but there may be a chance of loss of data information. The programmer will not responsible to perform explicit type-casting. Let’s see the below example to find the difference between normal assignment operator and compound assignment operator. A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

and results in x having the value 7 because it is equivalent to:

Because here 6.6 which is double is automatically converted to short type without explicit type-casting.

Refer: When is the Type-conversion required?

Explanation: In the above example, we are using normal assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) that’s results in compile time error. Here we have to do type-casting to get the result.

Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) apart from that we get the result as 20 because In compound assignment operator type-casting is automatically done by compile. Here we don’t have to do type-casting to get the result.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

Please Login to comment...

Similar reads.

  • Java-Operators
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

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

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Advertisement

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

Operator Name Example Try it
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example Try it
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001  1
| OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101  5
~ NOT - Inverts all the bits ~ 5  ~0101 1010  10
^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100  4
<< Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4

Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

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.

Learn Java practically and Get Certified .

Popular Tutorials

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

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)

Java Operators

  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement

Java Ternary Operator

  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion

Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

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

Additional Topics

  • Java Keywords and Identifiers

Java Operator Precedence

Java Bitwise and Shift Operators

  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

  • Java Math IEEEremainder()

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while * is also an operator used for multiplication.

Operators in Java can be classified into 5 types:

  • Arithmetic Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • Unary Operators
  • Bitwise Operators

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

Here, the + operator is used to add two variables a and b . Similarly, there are various other arithmetic operators in Java.

Operator Operation
Addition
Subtraction
Multiplication
Division
Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

In the above example, we have used + , - , and * operators to compute addition, subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division operator.

If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.

% Modulo Operator

The modulo operator % computes the remainder. When a = 7 is divided by b = 4 , the remainder is 3 .

Note : The % operator is mainly used with integers.

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age .

Let's see some more assignment operators available in Java.

Operator Example Equivalent to

Example 2: Assignment Operators

3. java relational operators.

Relational operators are used to check the relationship between two operands. For example,

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false .

Operator Description Example
Is Equal To returns
Not Equal To returns
Greater Than returns
Less Than returns
Greater Than or Equal To returns
Less Than or Equal To returns

Example 3: Relational Operators

Note : Relational operators are used in decision making and loops.

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false . They are used in decision making.

Operator Example Meaning
(Logical AND) expression1 expression2 only if both and are
(Logical OR) expression1 expression2 if either or is
(Logical NOT) expression if is and vice versa

Example 4: Logical Operators

Working of Program

  • (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .
  • (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .
  • (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .
  • (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .
  • (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .
  • !(5 == 3) returns true because 5 == 3 is false .
  • !(5 > 3) returns false because 5 > 3 is true .

5. Java Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1 . That is, ++5 will return 6 .

Different types of unary operators are:

Operator Meaning
: not necessary to use since numbers are positive without using it
: inverts the sign of an expression
: increments value by 1
: decrements value by 1
: inverts the value of a boolean
  • Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1 , while -- decrease it by 1 . For example,

Here, the value of num gets increased to 6 from its initial value of 5 .

Example 5: Increment and Decrement Operators

In the above program, we have used the ++ and -- operator as prefixes (++a, --b) . We can also use these operators as postfix (a++, b++) .

There is a slight difference when these operators are used as prefix versus when they are used as a postfix.

To learn more about these operators, visit increment and decrement operators .

6. Java Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits. For example,

Here, ~ is a bitwise operator. It inverts the value of each bit ( 0 to 1 and 1 to 0 ).

The various bitwise operators present in Java are:

Operator Description
Bitwise Complement
Left Shift
Right Shift
Unsigned Right Shift
Bitwise AND
Bitwise exclusive OR

These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators .

Other operators

Besides these operators, there are other additional operators in Java.

The instanceof operator checks whether an object is an instanceof a particular class. For example,

Here, str is an instance of the String class. Hence, the instanceof operator returns true . To learn more, visit Java instanceof .

The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,

Here's how it works.

  • If the Expression is true , expression1 is assigned to the variable .
  • If the Expression is false , expression2 is assigned to the variable .

Let's see an example of a ternary operator.

In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator .

Now that you know about Java operators, it's time to know about the order in which operators are evaluated. To learn more, visit Java Operator Precedence .

Table of Contents

  • Introduction
  • Java Arithmetic Operators
  • Java Assignment Operators
  • Java Relational Operators
  • Java Logical Operators
  • Java Unary Operators
  • Java Bitwise Operators

Before we wrap up, let’s put your knowledge of Java Operators: Arithmetic, Relational, Logical and more to the test! Can you solve the following challenge?

Write a function to return the largest of two given numbers.

  • Return the largest of two given numbers num1 and num2 .
  • For example, if num1 = 4 and num2 = 5 , the expected output is 5 .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

home

Java Tutorial

  • What is Java
  • History of Java
  • Features of Java
  • C++ vs Java
  • Hello Java Program
  • Program Internal
  • How to set path?
  • JDK, JRE and JVM
  • JVM: Java Virtual Machine
  • Java Variables
  • Java Data Types
  • Unicode System

Control Statements

  • Java Control Statements
  • Java If-else
  • Java Switch
  • Java For Loop
  • Java While Loop
  • Java Do While Loop
  • Java Continue
  • Java Comments

Java Programs

Java object class.

  • Java OOPs Concepts
  • Naming Convention
  • Object and Class
  • Constructor
  • static keyword
  • this keyword

Java Inheritance

  • Inheritance(IS-A)
  • Aggregation(HAS-A)

Java Polymorphism

  • Method Overloading
  • Method Overriding
  • Covariant Return Type
  • super keyword
  • Instance Initializer block
  • final keyword
  • Runtime Polymorphism
  • Dynamic Binding
  • instanceof operator

Java Abstraction

  • Abstract class
  • Abstract vs Interface

Java Encapsulation

  • Access Modifiers
  • Encapsulation

Java OOPs Misc

  • Object class
  • Object Cloning
  • Wrapper Class
  • Java Recursion
  • Call By Value
  • strictfp keyword
  • javadoc tool
  • Command Line Arg
  • Object vs Class
  • Overloading vs Overriding

Java String

  • What is String
  • Immutable String
  • String Comparison
  • String Concatenation
  • Methods of String class
  • StringBuffer class
  • StringBuilder class
  • String vs StringBuffer
  • StringBuffer vs Builder
  • Creating Immutable class
  • toString method
  • StringTokenizer class
  • Java String FAQs

Java String Methods

  • String charAt()
  • String compareTo()
  • String concat()
  • String contains()
  • String endsWith()
  • String equals()
  • equalsIgnoreCase()
  • String format()
  • String getBytes()
  • String getChars()
  • String indexOf()
  • String intern()
  • String isEmpty()
  • String join()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String replaceAll()
  • String split()
  • String startsWith()
  • String substring()
  • String toCharArray()
  • String toLowerCase()
  • String toUpperCase()
  • String trim()

Exception Handling

  • Java Exceptions
  • Java Try-catch block
  • Java Multiple Catch Block
  • Java Nested try
  • Java Finally Block
  • Java Throw Keyword
  • Java Exception Propagation
  • Java Throws Keyword
  • Java Throw vs Throws
  • Final vs Finally vs Finalize
  • Exception Handling with Method Overriding
  • Java Custom Exceptions

Java Inner Class

  • What is inner class
  • Member Inner class
  • Anonymous Inner class
  • Local Inner class
  • static nested class
  • Nested Interface

Java Multithreading

  • What is Multithreading
  • Life Cycle of a Thread
  • How to Create Thread
  • Thread Scheduler
  • Sleeping a thread
  • Start a thread twice
  • Calling run() method
  • Joining a thread
  • Naming a thread
  • Thread Priority
  • Daemon Thread
  • Thread Pool
  • Thread Group
  • ShutdownHook
  • Performing multiple task
  • Garbage Collection
  • Runtime class

Java Synchronization

  • Synchronization in java
  • synchronized block
  • static synchronization
  • Deadlock in Java
  • Inter-thread Comm
  • Interrupting Thread
  • Reentrant Monitor

Java Networking

  • Networking Concepts
  • Socket Programming
  • URLConnection class
  • HttpURLConnection
  • InetAddress class

Java Applet

  • Applet Basics
  • Graphics in Applet
  • Displaying image in Applet
  • Animation in Applet
  • EventHandling in Applet
  • JApplet class
  • Painting in Applet
  • Digital Clock in Applet
  • Analog Clock in Applet
  • Parameter in Applet
  • Applet Communication

Java Reflection

  • Reflection API
  • newInstance() method
  • creating javap tool
  • creating appletviewer
  • Call private method

Java Conversion

  • Java String to int
  • Java int to String
  • Java String to long
  • Java long to String
  • Java String to float
  • Java float to String
  • Java String to double
  • Java double to String
  • Java String to Date
  • Java Date to String
  • Java String to char
  • Java char to String
  • Java String to Object
  • Java Object to String
  • Java int to long
  • Java long to int
  • Java int to double
  • Java double to int
  • Java char to int
  • Java int to char
  • Java String to boolean
  • Java boolean to String
  • Date to Timestamp
  • Timestamp to Date
  • Binary to Decimal
  • Decimal to Binary
  • Hex to Decimal
  • Decimal to Hex
  • Octal to Decimal
  • Decimal to Octal
  • JDBC Introduction
  • JDBC Driver
  • DB Connectivity Steps
  • Connectivity with Oracle
  • Connectivity with MySQL
  • Access without DSN
  • DriverManager
  • PreparedStatement
  • ResultSetMetaData
  • DatabaseMetaData
  • Store image
  • Retrieve image
  • Retrieve file
  • CallableStatement
  • Transaction Management
  • Batch Processing
  • RowSet Interface
  • Internationalization
  • ResourceBundle class
  • I18N with Date
  • I18N with Time
  • I18N with Number
  • I18N with Currency
  • Java Array Class
  • getBoolean()
  • getDouble()
  • getLength()
  • newInstance()
  • setBoolean()
  • setDouble()
  • Java AtomicInteger Class
  • addAndGet(int delta)
  • compareAndSet(int expect, int update)
  • decrementAndGet()
  • doubleValue()
  • floatValue()
  • getAndAdd()
  • getAndDecrement()
  • getAndSet()
  • incrementAndGet()
  • getAndIncrement()
  • lazySet(int newValue)
  • longValue()
  • set(int newValue)
  • weakCompareAndSet(int expect,int newValue)
  • Java AtomicLong Methods
  • addAndGet()
  • compareAndSet()
  • weakCompareAndSet()
  • Java Authenticator
  • getPasswordAuthentication()
  • getRequestingHost()
  • getRequestingPort()
  • getRequestingPrompt()
  • getRequestingProtocol()
  • getRequestingScheme()
  • getRequestingSite()
  • getRequestingURL()
  • getRequestorType()
  • setDefault()
  • Java BigDecimal class
  • intValueExact()
  • movePointLeft()
  • movePointRight()
  • Big Integer Class
  • bitLength()
  • compareTo()
  • divideAndRemainder()
  • getLowestSetBit()
  • isProbablePrime()
  • modInverse()
  • nextProbablePrime()
  • probablePrime()
  • shiftLeft()
  • shiftRight()
  • toByteArray()
  • Java Boolean class
  • booleanValue()
  • logicalAnd()
  • logicalOr()
  • logicalXor()
  • parseBoolean()

Java Byte Class

  • byteValue()
  • compareUnsigned()
  • parseByte()
  • shortValue()
  • toUnsignedInt()
  • toUnsignedLong()
  • asSubclass()
  • desiredAssertionStatus()
  • getAnnotatedInterfaces()
  • getAnnotatedSuperclass()
  • getAnnotation()
  • getAnnotationsByType()
  • getAnnotations()
  • getCanonicalName()
  • getClasses()
  • getClassLoader()
  • getComponentType
  • getConstructor()
  • getConstructors()
  • getDeclaredAnnotation()
  • getDeclaredAnnotationsByType()
  • getDeclaredAnnotations()
  • getDeclaredConstructor()
  • getDeclaredConstructors()
  • getDeclaredField()
  • getDeclaredFields()
  • getDeclaredMethod()
  • getDeclaredMethods()
  • getDeclaringClass()
  • getFields()
  • getGenericInterfaces()
  • getGenericSuperClass()
  • getInterfaces()
  • getMethod()
  • getMethods()
  • getModifiers()
  • getPackage()
  • getPackageName()
  • getProtectionDomain()
  • getResource()
  • getSigners()
  • getSimpleName()
  • getSuperClass()
  • isAnnotation()
  • isAnnotationPresent()
  • isAnonymousClass()
  • isInstance()
  • isInterface()
  • isPrimitive()
  • isSynthetic()
  • Java Collections class
  • asLifoQueue()
  • binarySearch()
  • checkedCollection()
  • checkedList()
  • checkedMap()
  • checkedNavigableMap()
  • checkedNavigableSet()
  • checkedQueue()
  • checkedSet()
  • checkedSortedMap()
  • checkedSortedSet()
  • emptyEnumeration()
  • emptyIterator()
  • emptyList()
  • emptyListIterator()
  • emptyNavigableMap()
  • emptyNavigableSet()
  • emptySortedMap()
  • emptySortedSet()
  • enumeration()
  • frequency()
  • indexOfSubList()
  • lastIndexOfSubList()
  • newSetFromMap()
  • replaceAll()
  • reverseOrder()
  • singleton()
  • singletonList()
  • singletonMap()
  • synchronizedCollection()
  • synchronizedList()
  • synchronizedMap()
  • synchronizedNavigableMap()
  • synchronizedNavigableSet()
  • synchronizedSet()
  • synchronizedSortedMap()
  • synchronizedSortedSet()
  • unmodifiableCollection()
  • unmodifiableList()
  • unmodifiableMap()
  • unmodifiableNavigableMap()
  • unmodifiableNavigableSet()
  • unmodifiableSet()
  • unmodifiableSortedMap()
  • unmodifiableSortedSet()

Java Compiler Class

  • Java Compiler
  • compileClass()
  • compileClasses()

CopyOnWriteArrayList

  • Java CopyOnWriteArrayList
  • lastIndexOf()

Java Math Methods

  • Math.round()
  • Math.sqrt()
  • Math.cbrt()
  • Math.signum()
  • Math.ceil()
  • Math.copySign()
  • Math.nextAfter()
  • Math.nextUp()
  • Math.nextDown()
  • Math.floor()
  • Math.floorDiv()
  • Math.random()
  • Math.rint()
  • Math.hypot()
  • Math.getExponent()
  • Math.IEEEremainder()
  • Math.addExact()
  • Math.subtractExact()
  • Math.multiplyExact()
  • Math.incrementExact()
  • Math.decrementExact()
  • Math.negateExact()
  • Math.toIntExact()
  • Math.log10()
  • Math.log1p()
  • Math.expm1()
  • Math.asin()
  • Math.acos()
  • Math.atan()
  • Math.sinh()
  • Math.cosh()
  • Math.tanh()
  • Math.toDegrees
  • Math.toRadians

LinkedBlockingDeque

  • Java LinkedBlockingDeque
  • descendingIterator()
  • offerFirst()
  • offerLast()
  • peekFirst()
  • pollFirst()
  • Java Long class

LinkedTransferQueue

  • Java LinkedTransferQueue
  • spliterator()
  • Difference between Array and ArrayList
  • When to use ArrayList and LinkedList in Java
  • Difference between ArrayList and Vector
  • How to Compare Two ArrayList in Java
  • How to reverse ArrayList in Java
  • How to make ArrayList Read Only
  • Difference between length of array and size() of ArrayList in Java
  • How to Synchronize ArrayList in Java
  • How to convert ArrayList to Array and Array to ArrayList in java
  • Array vs ArrayList in Java
  • How to Sort Java ArrayList in Descending Order
  • How to remove duplicates from ArrayList in Java
  • Java MulticastSocket
  • getInterface()
  • getLoopbackMode()
  • getNetworkInterface()
  • getTimeToLive()
  • joinGroup()
  • leaveGroup()
  • setInterface()
  • setLoopbackMode()
  • setNetworkInterface()
  • setTimeToLive()
  • Java Number Class

Java Phaser Class

  • Java Phaser
  • arriveAndAwaitAdvance()
  • arriveAndDeregister()
  • getParent()
  • awaitAdvanceInterruptibly()
  • awaitAdvance()
  • bulkRegister()
  • forceTermination()
  • getArrivedParties()
  • getRegisteredParties()
  • getUnarrivedParties()
  • isTerminated()

ArrayList Methods

  • listIterator()
  • removeRange

Java Thread Methods

  • currentThread()
  • getPriority()
  • setPriority()
  • setDaemon()
  • interrupt()
  • isinterrupted()
  • interrupted()
  • activeCount()
  • checkAccess()
  • dumpStack()
  • getStackTrace()
  • enumerate()
  • getThreadGroup()
  • notifyAll()
  • setContextClassLoader()
  • getContextClassLoader()
  • getDefaultUncaughtExceptionHandler()
  • setDefaultUncaughtExceptionHandler()

Java Projects

  • Free Java Projects
  • Payment Bill(JSP)
  • Transport (JSP)
  • Connect Globe (JSP)
  • Online Banking (JSP)
  • Online Quiz (JSP)
  • Classified (JSP)
  • Mailcasting (JSP)
  • Online Library (JSP)
  • Pharmacy (JSP)
  • Mailer (Servlet)
  • Baby Care (Servlet)
  • Chat Server (Core)
  • Library (Core)
  • Exam System (Core)
  • Java Apps (Core)
  • Fee Report (Core)
  • Fee (Servlet)
  • eLibrary (Servlet)
  • Fire Detection
  • Attendance System
  • Fibonacci Series in Java
  • Prime Number Program in Java
  • Palindrome Program in Java
  • Factorial Program in Java
  • Armstrong Number in Java
  • How to Generate Random Number in Java
  • How to Print Pattern in Java
  • How to Compare Two Objects in Java
  • How to Create Object in Java
  • How to Print ASCII Value in Java
  • How to Reverse a Number in Java
  • Java Program to convert Number to Word
  • Automorphic Number Program in Java
  • Peterson Number in Java
  • Sunny Number in Java
  • Tech Number in Java
  • Fascinating Number in Java
  • Keith Number in Java
  • Neon Number in Java
  • Spy Number in Java
  • ATM program Java
  • Autobiographical Number in Java
  • Emirp Number in Java
  • Sphenic Number in Java
  • Buzz Number Java
  • Duck Number Java
  • Evil Number Java
  • ISBN Number Java
  • Krishnamurthy Number Java
  • Bouncy Number in Java
  • Mystery Number in Java
  • Smith Number in Java
  • Strontio Number in Java
  • Xylem and Phloem Number in Java
  • nth Prime Number Java
  • Java Program to Display Alternate Prime Numbers
  • Java Program to Find Square Root of a Number Without sqrt Method
  • Java Program to Swap Two Numbers Using Bitwise Operator
  • Java Program to Find GCD of Two Numbers
  • Java Program to Find Largest of Three Numbers
  • Java Program to Find Smallest of Three Numbers Using Ternary Operator
  • Java Program to Check if a Number is Positive or Negative
  • Java Program to Check if a Given Number is Perfect Square
  • Java Program to Display Even Numbers From 1 to 100
  • Java Program to Display Odd Numbers From 1 to 100
  • Java Program to Find Sum of Natural Numbers
  • Java Program to copy all elements of one array into another array
  • Java Program to find the frequency of each element in the array
  • Java Program to left rotate the elements of an array
  • Java Program to print the duplicate elements of an array
  • Java Program to print the elements of an array
  • Java Program to print the elements of an array in reverse order
  • Java Program to print the elements of an array present on even position
  • Java Program to print the elements of an array present on odd position
  • Java Program to print the largest element in an array
  • Java Program to print the smallest element in an array
  • Java Program to print the number of elements present in an array
  • Java Program to print the sum of all the items of the array
  • Java Program to right rotate the elements of an array
  • Java Program to sort the elements of an array in ascending order
  • Java Program to sort the elements of an array in descending order
  • Java Program to Find 3rd Largest Number in an array
  • Java Program to Find 2nd Largest Number in an array
  • Java Program to Find Largest Number in an array
  • Java to Program Find 2nd Smallest Number in an array
  • Java Program to Find Smallest Number in an array
  • Java Program to Remove Duplicate Element in an array
  • Java Program to Print Odd and Even Numbers from an array
  • How to Sort an Array in Java
  • Java Matrix Programs
  • Java Program to Add Two Matrices
  • Java Program to Multiply Two Matrices
  • Java Program to subtract the two matrices
  • Java Program to determine whether two matrices are equal
  • Java Program to display the lower triangular matrix
  • Java Program to display the upper triangular matrix
  • Java Program to find the frequency of odd & even numbers in the given matrix
  • Java Program to find the product of two matrices
  • Java Program to find the sum of each row and each column of a matrix
  • Java Program to find the transpose of a given matrix
  • Java Program to determine whether a given matrix is an identity matrix
  • Java Program to determine whether a given matrix is a sparse matrix
  • Java Program to Transpose matrix
  • Java Program to count the total number of characters in a string
  • Java Program to count the total number of characters in a string 2
  • Java Program to count the total number of punctuation characters exists in a String
  • Java Program to count the total number of vowels and consonants in a string
  • Java Program to determine whether two strings are the anagram
  • Java Program to divide a string in 'N' equal parts.
  • Java Program to find all subsets of a string
  • Java Program to find the longest repeating sequence in a string
  • Java Program to find all the permutations of a string
  • Java Program to remove all the white spaces from a string
  • Java Program to replace lower-case characters with upper-case and vice-versa
  • Java Program to replace the spaces of a string with a specific character
  • Java Program to determine whether a given string is palindrome
  • Java Program to determine whether one string is a rotation of another
  • Java Program to find maximum and minimum occurring character in a string
  • Java Program to find Reverse of the string
  • Java program to find the duplicate characters in a string
  • Java program to find the duplicate words in a string
  • Java Program to find the frequency of characters
  • Java Program to find the largest and smallest word in a string
  • Java Program to find the most repeated word in a text file
  • Java Program to find the number of the words in the given text file
  • Java Program to separate the Individual Characters from a String
  • Java Program to swap two string variables without using third or temp variable.
  • Java Program to print smallest and biggest possible palindrome word in a given string
  • Reverse String in Java Word by Word
  • Reserve String without reverse() function
  • Linear Search in Java
  • Binary Search in Java
  • Bubble Sort in Java
  • Selection Sort in Java
  • Insertion Sort in Java
  • How to convert String to int in Java
  • How to convert int to String in Java
  • How to convert String to long in Java
  • How to convert long to String in Java
  • How to convert String to float in Java
  • How to convert float to String in Java
  • How to convert String to double in Java
  • How to convert double to String in Java
  • How to convert String to Date in Java
  • How to convert Date to String in Java
  • How to convert String to char in Java
  • How to convert char to String in Java
  • How to convert String to Object in Java
  • How to convert Object to String in Java
  • How to convert int to long in Java
  • How to convert long to int in Java
  • How to convert int to double in Java
  • How to convert double to int in Java
  • How to convert char to int in Java
  • How to convert int to char in Java
  • How to convert String to boolean in Java
  • How to convert boolean to String in Java
  • How to convert Date to Timestamp in Java
  • How to convert Timestamp to Date in Java
  • How to convert Binary to Decimal in Java
  • How to convert Decimal to Binary in Java
  • How to convert Hex to Decimal in Java
  • How to convert Decimal to Hex in Java
  • How to convert Octal to Decimal in Java
  • How to convert Decimal to Octal in Java
  • Java program to print the following spiral pattern on the console
  • Java program to print the following pattern
  • Java program to print the following pattern 2
  • Java program to print the following pattern 3
  • Java program to print the following pattern 4
  • Java program to print the following pattern 5
  • Java program to print the following pattern on the console
  • Java program to print the following pattern on the console 2
  • Java program to print the following pattern on the console 3
  • Java program to print the following pattern on the console 4
  • Java program to print the following pattern on the console 5
  • Java program to print the following pattern on the console 6
  • Java program to print the following pattern on the console 7
  • Java program to print the following pattern on the console 8
  • Java program to print the following pattern on the console 9
  • Java program to print the following pattern on the console 10
  • Java program to print the following pattern on the console 11
  • Java program to print the following pattern on the console 12
  • Singly linked list Examples in Java
  • Java Program to create and display a singly linked list
  • Java program to create a singly linked list of n nodes and count the number of nodes
  • Java program to create a singly linked list of n nodes and display it in reverse order
  • Java program to delete a node from the beginning of the singly linked list
  • Java program to delete a node from the middle of the singly linked list
  • Java program to delete a node from the end of the singly linked list
  • Java program to determine whether a singly linked list is the palindrome
  • Java program to find the maximum and minimum value node from a linked list
  • Java Program to insert a new node at the middle of the singly linked list
  • Java program to insert a new node at the beginning of the singly linked list
  • Java program to insert a new node at the end of the singly linked list
  • Java program to remove duplicate elements from a singly linked list
  • Java Program to search an element in a singly linked list
  • Java program to create and display a Circular Linked List
  • Java program to create a Circular Linked List of N nodes and count the number of nodes
  • Java program to create a Circular Linked List of n nodes and display it in reverse order
  • Java program to delete a node from the beginning of the Circular Linked List
  • Java program to delete a node from the end of the Circular Linked List
  • Java program to delete a node from the middle of the Circular Linked List
  • Java program to find the maximum and minimum value node from a circular linked list
  • Java program to insert a new node at the beginning of the Circular Linked List
  • Java program to insert a new node at the end of the Circular Linked List
  • Java program to insert a new node at the middle of the Circular Linked List
  • Java program to remove duplicate elements from a Circular Linked List
  • Java program to search an element in a Circular Linked List
  • Java program to sort the elements of the Circular Linked List
  • Java program to convert a given binary tree to doubly linked list
  • Java program to create a doubly linked list from a ternary tree
  • Java program to create a doubly linked list of n nodes and count the number of nodes
  • Java program to create a doubly linked list of n nodes and display it in reverse order
  • Java program to create and display a doubly linked list
  • Java program to delete a new node from the beginning of the doubly linked list
  • Java program to delete a new node from the end of the doubly linked list
  • Java program to delete a new node from the middle of the doubly linked list
  • Java program to find the maximum and minimum value node from a doubly linked list
  • Java program to insert a new node at the beginning of the Doubly Linked list
  • Java program to insert a new node at the end of the Doubly Linked List
  • Java program to insert a new node at the middle of the Doubly Linked List
  • Java program to remove duplicate elements from a Doubly Linked List
  • Java program to rotate doubly linked list by N nodes
  • Java program to search an element in a doubly linked list
  • Java program to sort the elements of the doubly linked list
  • Java Program to calculate the Difference between the Sum of the Odd Level and the Even Level Nodes of a Binary Tree
  • Java program to construct a Binary Search Tree and perform deletion and In-order traversal
  • Java program to convert Binary Tree to Binary Search Tree
  • Java program to determine whether all leaves are at same level
  • Java program to determine whether two trees are identical
  • Java program to find maximum width of a binary tree
  • Java program to find the largest element in a Binary Tree
  • Java program to find the maximum depth or height of a tree
  • Java program to find the nodes which are at the maximum distance in a Binary Tree
  • Java program to find the smallest element in a tree
  • Java program to find the sum of all the nodes of a binary tree
  • Java program to find the total number of possible Binary Search Trees with N keys
  • Java program to implement Binary Tree using the Linked List
  • Java program to search a node in a Binary Tree
  • Java Main Method
  • System.out.println()
  • Java Memory Management
  • Java ClassLoader
  • Java Decompiler
  • Java vs. JavaScript
  • Java vs. Kotlin
  • Java vs. Python
  • Java Absolute Value
  • How to Create File
  • Delete a File in Java
  • Open a File in Java
  • Sort a List in Java
  • Convert byte Array to String
  • Java Basics
  • How to Compile & Run Java Program
  • How to Run Java Program in Eclipse
  • How to Verify Java Version
  • Ways to Create an Object in Java
  • How to Run a Java program in Windows 10
  • Runnable Interface in Java
  • Java Keystore
  • Get input from user in Java
  • Read file line by line in Java
  • Take String input in Java
  • How to Read Excel File in Java
  • Read XML File in Java
  • CompletableFuture in Java
  • Java ExecutorService
  • How to iterate Map in Java
  • How to Return an Array in Java
  • How to Sort HashMap by Value
  • How to Sort HashMap in Java
  • Load Factor in HashMap
  • Array vs ArrayList
  • HashMap vs TreeMap
  • HashSet vs HashMap class
  • Compare Two ArrayList in Java
  • Merge Two Arrays in Java
  • Print Array in Java
  • Read CSV File in Java
  • Remove Special Characters from String
  • ArrayIndexOutOfBoundsException
  • ConcurrentModificationException
  • NoSuchElementException
  • NumberFormatException
  • How to Sort ArrayList in Java
  • How to Download Java
  • How to Call a Method in Java
  • How to Create Singleton Class in Java
  • How to Find Array Length in Java
  • How to Read Character in Java
  • Can We Overload main() Method in Java
  • How to Convert Char Array to String in Java
  • How to Run Java Program in CMD Using Notepad
  • How to Sort String Array in Java
  • How to Compare Dates in Java
  • How to Take Multiple String Input in Java Using Scanner
  • How to Remove Last Character from String in Java
  • How TreeMap Works Internally in Java
  • Java Program to Break Integer into Digits
  • Java Program to Calculate Area and Circumference of Circle
  • What is Diamond Problem in Java
  • Java Program to Read Number from Standard Input
  • How to Download Minecraft Java Edition
  • Can We Override Static Method in Java
  • How to Avoid Deadlock in Java
  • How to Achieve Abstraction in Java
  • How Garbage Collection Works in Java
  • How to Take Array Input in Java
  • How to Create Array of Objects in Java
  • How to Create Package in Java
  • How to Print in Java
  • What is Framework in Java
  • Why Java is Secure
  • How to Iterate List in Java
  • How to Use Eclipse for Java
  • Which Package is Imported by Default in Java
  • Could Not Find or Load Main Class in Java
  • How to Compare Two Arrays in Java
  • How to Convert String to JSON Object in Java
  • Which is Better Java or Python
  • How to Update Java
  • How to Get Value from JSON Object in Java Example
  • How to Split a String in Java with Delimiter
  • Structure of Java Program
  • Why We Use Constructor in Java
  • Java Create Excel File
  • Java Interpreter
  • javac is not Recognized
  • Dynamic Array in Java
  • Shunting yard algorithm
  • Java Destructor
  • Custom ArrayList in Java
  • ArrayList vs HashMap
  • Java Constant
  • Java Tokens
  • How to Enable Java in Chrome
  • Java Semaphore
  • Array to List in Java
  • JIT in Java
  • How to Clear Screen in Java
  • Java Logger
  • Reverse a String Using Recursion in Java
  • Java Path Vs File
  • Float Vs Double Java
  • Stack vs Heap Java
  • Abstraction vs Encapsulation
  • Top 10 Java Books
  • Public vs Private
  • What is Java Used For
  • Bitwise Operator in Java
  • SOLID Principles Java
  • Type Casting in Java
  • Conditional Operator in Java
  • Ternary Operator Java
  • Java Architecture
  • REPL in Java
  • Types of Exception in Java
  • Why String is Immutable or Final in Java
  • Java vs Kotlin
  • Set in Java
  • Why non-static variable cannot be referenced from a static context in Java
  • Java Developer Roles and Responsibilities
  • Types of Classes in Java
  • Marker Interface in Java
  • Static Function in Java
  • Unary Operators in Java
  • What is Advance Java
  • ArrayList Implementation
  • Convert ArrayList to String Array
  • Hashmap vs ConcurrentHashMap
  • List vs ArrayList
  • Map vs HashMap
  • HashSet vs LinkedHashSet
  • How TreeSet Works Internally
  • LinkedHashMap vs HashMap
  • Java Program to Solve Quadratic Equation
  • Scope Resolution Operator in Java
  • Composition in Java
  • File Operations in Java
  • NoClassDefFoundError in Java
  • Thread Concept in Java
  • Upcasting and Downcasting in Java
  • Dynamic Polymorphism in Java
  • String Pool in Java
  • What is constructor chaining in Java
  • Add elements to Array in Java
  • Advantages and disadvantages of Java
  • Advantages of JavaBeans
  • AWS SDK for Java with Apache Maven
  • AWT and Swing in Java
  • AWT Program in Java
  • Boolean values in Java
  • ByteStream Classes in Java
  • CharacterStream Classes in Java
  • Class and Interface in Java
  • ClassCast Exception in Java
  • Cloneable in Java
  • Constructor overloading in Java
  • Control Flow in Java
  • Convert Java Object to Json using GSON
  • Convert XML to JSON in Java
  • How to avoid null pointer exception in Java
  • Java constructor returns a value, but what
  • Singleton Class in Java
  • Doubly Linked List Program in Java
  • Association in Java
  • Big data Java vs Python
  • Branching Statements in Java
  • Collections Sort in Java 8
  • List vs Set in Java
  • How many days required to learn Java
  • Implicitly Typecasting in Java
  • Legacy Class in Java
  • Character Array in Java
  • Equals() and Hashcode() in Java
  • Externalization in Java
  • Identifiers in Java
  • InvocationTargetException
  • Java Pass by Value
  • Mutable and Immutable in Java
  • Power Function in Java
  • Primitive Data Types in Java
  • String Array in Java
  • Virtual Function in Java
  • C vs C++ vs Java
  • Java String Max Size
  • Convert Java object to JSON
  • How to Calculate Date Difference in Java
  • How to Improve Coding Skills in Java
  • Java Email Validation
  • Java Testing Tools
  • Permutation and Combination in Java
  • Unique Number in Java Program
  • Java Code for DES
  • Pig Latin Program in Java
  • Array Rotation in Java
  • Equilibrium Index of an Array in Java
  • Different Ways to Print Exception Message in Java
  • Java Copy Constructor Example
  • Why We Use Static Class in Java
  • What is Core Java
  • Set vs Map in Java
  • How to Create a New Folder in Java
  • Remove an Element from ArrayList in Java
  • How to Create Test Cases for Exceptions in Java
  • How to Convert JSON Array to ArrayList in Java
  • How to Create a Class File in Java
  • Java Spring Pros & Cons
  • Java Stack Trace
  • Array Slicing in Java
  • Flutter vs Java
  • Permutation of Numbers in Java
  • Magic Number in Java
  • Reference Data Types in Java
  • Counter variable in Java
  • How to take Character Input in Java using BufferedReader Class
  • Java employee details program
  • Java is case sensitive explain
  • Ramanujan Number or Taxicab Number in Java
  • Advanced Java Books in 2021
  • Fail Fast and Fail Safe Iterator in Java
  • How to build a Web Application Using Java
  • Is Java Interpreted or Compiled
  • Java Big Data Frameworks
  • Java Get Data From URL
  • No Main Manifest Attribute
  • Java missing return statement
  • Java program to remove duplicate characters from a string
  • JUnit test case example in Java
  • List of logical programs in Java
  • PermGen space Java
  • Unsigned Right Shift Operator in Java
  • Infix to Postfix Java
  • Memory Leak in Java
  • How To Write Test Cases In Java
  • Java 32-Bit Download For Windows 10
  • FizzBuzz Program in Java
  • A Java Runtime Environment JRE Or JDK Must Be Available
  • Java Does Not Open
  • No Java Virtual Machine was Found
  • Java Program Number to Word
  • Types of Garbage Collector in Java
  • No Suitable Driver Found For JDBC
  • AVL Tree program in Java
  • Fail-fast and Fail-safe in Java
  • Find unique elements in array Java
  • Highest precedence in Java
  • Java Closure
  • Java String Encoding
  • Prim's algorithm Java
  • Quartz scheduler java
  • Red Black Tree Java
  • GC Overhead Limit Exceeded
  • Generating QR Code in Java
  • Delegation Event Model in Java
  • Java Profilers
  • Java Flight Recorder
  • Bucket Sort in Java
  • Java Atomic
  • Wait vs Sleep in Java
  • Executor Framework Java
  • Gregorian calendar Java
  • int vs Integer Java
  • What is truncation in Java
  • Java HTTP Proxy Server
  • Java Static Constructor
  • How to prepare for Java Interview
  • Java callback function
  • Java 8 vs Java 11
  • Login Form Java
  • Vaadin Framework Java
  • EJB vs. Spring
  • Types of Applets in Java
  • Visitor Design Pattern Java
  • Advantages of Python over Java
  • Design Principles in Java
  • JSON Validator Java
  • Pseudocode Java
  • Windows Programming Using Java
  • Vert.x Java
  • Complex Java Programs
  • ORE Number Java
  • PalPrime Number Java
  • Twin Prime Numbers
  • Twisted Prime Number Java
  • Ugly number Java
  • Achilles Number in Java
  • Amicable Pair Number in Java
  • Playfair Cipher Program in Java
  • Java.lang.outofmemoryerror: java heap space
  • Banker's Algorithm Java
  • Kruskal Algorithm Java
  • Longest Common Subsequence
  • Travelling Salesman Problem
  • & vs && in Java
  • Jumping Number in Java
  • Lead Number in Java
  • Lucky Number in Java
  • Middle Digit Number in Java
  • Special Number in Java
  • Passing Array to Function In Java
  • Lexicographical Order Java
  • Adam Number in Java
  • Bell Number in Java
  • Reduce Java
  • LRU Cache Implementation
  • Goldbach Number in Java
  • How to Find Number of Objects Created in Java
  • Multiply Two Numbers Without Using Arithmetic Operator in Java
  • Sum of Digits of a Number in Java
  • Sum of Numbers in Java
  • Power of a Number in Java
  • Sum of Prime Numbers in Java
  • Cullen Number in Java
  • Mobile Number Validation in Java
  • Fermat Number in Java
  • Instantiation in Java
  • Exception Vs Error in Java
  • flatMap() Method in Java 8
  • How to Print Table in Java
  • Java Create PDF
  • Mersenne Number in Java
  • Pandigital Number in Java
  • Pell Number in Java
  • Java Get Post
  • Fork Join in Java
  • Java Callable Example
  • Blockchain Java
  • Design of JDBC
  • Java Anon Proxy
  • Knapsack Problem Java
  • Session Tracking in Java
  • What is Object-Oriented Programming
  • Literals in Java
  • Square Free Number in Java
  • What is an anagram in Java
  • What is programming
  • Iterate JSON Array Java
  • Java Date Add Days
  • Javac Command Not Found
  • Factorial Program in Java Using while Loop
  • Frugal Number in Java
  • Java Digital Signature
  • Catalan Number in Java
  • Partition Number in Java
  • Powerful Number in Java
  • Practical Number in Java
  • Chromatic Number in Java
  • Sublime Number in Java
  • Advanced Java Viva Questions
  • Getter and Setter Method in Java Example
  • How to convert String to String array in Java
  • How to Encrypt Password in Java
  • Instance Variable in Java
  • Java File Extension
  • Types of Inheritance in Java
  • Untouchable Number in Java
  • AES 256 Encryption in Java
  • Applications of Array in Java
  • Example of Static Import in Java
  • Hill Cipher Program in Java
  • Lazy Loading in Java
  • Rectangular Number in Java
  • How to Print Table in Java Using Formatter
  • IdentityHashMap Class in Java
  • Undulating Number in Java
  • Java Obfuscator
  • Java Switch String
  • Applet Life Cycle in Java
  • Banking Application in Java
  • Duodecimal in Java
  • Economical Number in Java
  • Figurate Number in Java
  • How to resolve IllegalStateException in Java
  • Java Coding Software
  • Java Create Jar Files
  • Java Framework List
  • Java Initialize array
  • java lang exception no runnable methods
  • Nonagonal Number in Java
  • SexagesimalFormatter in Java
  • Sierpinski Number in Java
  • Vigesimal in Java
  • Java Color Codes
  • JDoodle Java
  • Online Java Compiler
  • Pyramidal Number in Java
  • Relatively Prime in Java
  • Java Modulo
  • Repdigit Numbers in Java
  • Abstract Method in Java
  • Convert Text-to-Speech in Java
  • Java Editors
  • MVC Architecture in Java
  • Narcissistic Number in Java
  • Hashing Algorithm in Java
  • Java Escape Characters
  • Java Operator Precedence
  • Private Constructor in Java
  • Scope of Variables in Java
  • Groovy vs Java
  • Java File Upload to a Folder
  • Java Full Stack
  • Java Developer
  • Thread States in Java
  • Java EE vs Node.js
  • Loose Coupling in Java
  • Java Top 10 Libraries
  • Method Hiding in Java
  • Dijkstra Algorithm Java
  • Extravagant Number in Java
  • Java Unicode
  • New Line in Java
  • Return Statement in Java
  • Order of Execution of Constructors in Java Inheritance
  • Cardinal Number in Java
  • Hyperfactorial in Java
  • Identifier Expected Error in Java
  • Java Generate UUID
  • Labeled Loop in Java
  • Lombok Java
  • Ordinal Number in Java
  • Tetrahedral Number in Java
  • Cosmic Superclass in Java
  • Shallow Copy Java
  • BiFunction Java 8
  • Equidigital Number in Java
  • Fall Through in Java
  • Java Reserved Keywords
  • Parking Lot Design Java
  • Boyer Moore Java
  • Java Security Framework
  • Tetranacci Number in Java
  • BFS Algorithm in Java
  • CountDownLatch in Java
  • Counting sort in Java
  • CRC Program in Java
  • FileNotFoundException in Java
  • InputMismatchException in Java
  • Java ASCII Table
  • Lock in Java
  • Segment Tree in Java
  • Why main() method is always static in Java
  • Bellman-Ford Algorithm Java
  • BigDecimal toString() in Java
  • .NET vs Java
  • Java ZipFile
  • Lazy Propagation in Segment Tree in Java
  • Magnanimous Number in Java
  • Binary Tree Java
  • How to Create Zip File in Java
  • Java Dot Operator
  • Associativity of Operators in Java
  • Fenwick Tree in Java
  • How annotation works in Java
  • How to Find Length of Integer in Java
  • Java 8 filters
  • List All Files in a Directory in Java
  • How to Get Day Name from Date in Java
  • Zigzag Array in Java
  • Class Definition in Java
  • Find Saddle Point of a Matrix in Java
  • Non-primitive data types in Java
  • Pancake Number in Java
  • Pancake Sorting in Java
  • Print Matrix Diagonally in Java
  • Sort Dates in Java
  • Carmichael Numbers in Java
  • Contextual Keywords in Java
  • How to Open Java Control Panel
  • How to Reverse Linked List in Java
  • Interchange Diagonal Elements Java Program
  • Java Set to List
  • Level Order Traversal of a Binary Tree in Java
  • Bully algorithm in Java
  • Convert JSON File to String in Java
  • Convert Milliseconds to Date in Java
  • Copy Content/ Data From One File to Another in Java
  • Constructor vs Method in Java
  • Access Specifiers vs Modifiers
  • Java vs PHP
  • replace() vs replaceAll() in Java
  • this vs super in Java
  • Heap implementation in Java
  • How to Check null in Java
  • Java Arrays Fill
  • Rotate Matrix by 90 Degrees in Java
  • Exception Class in Java
  • Transient variable in Java
  • Web crawler Java
  • Zigzag Traversal of a Binary Tree in Java
  • Java Get File Size
  • Internal Working of ArrayList in Java
  • Java Program to Print Matrix in Z Form
  • Vertical Order Traversal of a Binary Tree in Java
  • Group By in Java 8
  • Hashing Techniques in Java
  • Implement Queue Using Array in Java
  • Java 13 Features
  • Package Program in Java
  • Canonical Name Java
  • Method Chaining in Java
  • Orphaned Case Java
  • Bottom View of a Binary Tree in Java
  • Coercion in Java
  • Dictionary Class in Java
  • Left View of a Binary Tree in Java
  • Pangram Program in Java
  • Top View of a Binary Tree in Java
  • Tribonacci Series in Java
  • Hollow Diamond Pattern in Java
  • Normal and Trace of a Matrix in Java
  • Right View of a Binary Tree in Java
  • Dining Philosophers Problem and Solution in Java
  • Shallow Copy vs Deep Copy in Java
  • Java Password Generator
  • Java Program for Shopping Bill
  • Lock Interface in Java
  • Convert JSON to Map in Java
  • Convert JSON to XML in Java
  • Middle Node of a Linked List in Java
  • Pernicious Number in Java
  • Cohesion in Java
  • How to get UTC time in Java
  • Jacobsthal Number in Java
  • Java Calculate Age
  • Tribonacci Number Java
  • Bernoulli number in Java
  • Cake Number in Java
  • Compare time in Java
  • Compare Two Sets in Java
  • Crown Pattern in Java
  • Convert List to Array in Java
  • Aggregation vs Composition
  • Morris Traversal for Inorder in Java
  • Morris Traversal for Preorder in Java
  • Package Naming Conversion in Java
  • India Map Pattern in Java
  • Ladder Pattern in Java
  • ORM Tools in Java
  • Odious Number in Java
  • Rat in a Maze Problem in Java
  • Sudoku in Java
  • Christmas Tree Pattern in Java
  • Double Hashing in Java
  • Magic Square in Java
  • Possible Paths from Top Left to Bottom Right of a Matrix in Java
  • Palindrome Partitioning Problem in Java
  • Rehashing in Java
  • Round Robin Scheduling Program in Java
  • Types of Statements in Java
  • Compound Assignment Operator in Java
  • Prime Points in Java
  • Butterfly Pattern in Java
  • Fish Pattern in Java
  • Flag Pattern in Java
  • Kite pattern in Java
  • Swastika Pattern in Java
  • Tug of War in Java
  • Clone HashMap in Java
  • Fibodiv Number in Java
  • Heart Pattern in Java
  • How to check data type in Java
  • Java Array Clone
  • Use of final Keyword in Java
  • Factorial of a Large Number in Java
  • Race Condition in Java
  • Static Array in Java
  • Water Jug Problem in Java
  • Electricity Bill Program in Java
  • Facts about null in Java
  • Maximizing Profit in Stock Buy Sell in Java
  • Permutation Coefficient in Java
  • Convert List to String in Java
  • List of Constants in Java
  • MOOD Factors to Assess a Java Program
  • Computing Digit Sum of All Numbers From 1 to n in Java
  • Read PDF File in Java
  • Finding Odd Occurrence of a Number in Java
  • Java Indentation
  • Zig Zag Star and Number Pattern in Java
  • Check Whether a Number is a Power of 4 or not in Java
  • Kth Smallest in an Unsorted Array in Java
  • BlockingQueue in Java
  • Next Greater Element in Java
  • Star Numbers in Java
  • 3N+1 Problem in Java
  • Java Program to Find Local Minima in An Array
  • Processing Speech in Java
  • Java Output Formatting
  • House Numbers in Java
  • Java Program to Generate Binary Numbers
  • Longest Odd-Even Subsequence in Java
  • Java Subtract Days from Current Date
  • Java Future Example
  • Minimum Cost Path Problem in Java
  • Diffie-Hellman Algorithm in Java
  • Ganesha's Pattern in Java
  • Hamming Code in Java
  • Map of Map in Java
  • Print Pencil Shape Pattern in Java
  • Zebra Puzzle in Java
  • Display Unique Rows in a Binary Matrix in Java
  • Rotate A Matrix By 180 Degree in Java
  • Dangling Else Problem in Java
  • Java Application vs Java Applet
  • Dutch National Flag Problem in Java
  • Java Calculate Average of List
  • compareToIgnoreCase Java
  • Trimorphic Numbers in Java
  • Arithmetic Exception in Java
  • Java instanceof operator
  • Java Localization
  • Minimum XOR Value Pair in Java
  • Iccanobif Numbers in Java
  • Java Program to Count the Occurrences of Each Character
  • Java Technologies List
  • Java Program to Find the Minimum Number of Platforms Required for a Railway Station
  • Shift Operators in Java
  • Final Object in Java
  • Object Definition in Java
  • Shadowing in Java
  • Zipping and Unzipping Files in Java
  • Display the Odd Levels Nodes of a Binary Tree in Java
  • Java Variable Declaration
  • Nude Numbers in Java
  • Java Programming Challenges
  • Java URL Encoder
  • anyMatch() in Java 8
  • Sealed Class in Java
  • Camel case in Java
  • Career Options for Java Developers to Aim in 2022
  • Java Progress Bar
  • Maximum Rectangular Area in a Histogram in Java
  • Polygonal Number in Java
  • Two Sorted LinkedList Intersection in Java
  • Set Matrix Zeros in Java
  • Find Number of Island in Java
  • Balanced Prime Number in Java
  • Minecraft Bedrock vs Java Minecraft
  • arr.length vs arr[0].length vs arr[1].length in Java
  • Future in Java 8
  • How to Set Timer in Java
  • Construct the Largest Number from the Given Array in Java
  • Minimum Coins for Making a Given Value in Java
  • Eclipse Shortcuts Java
  • Empty Statement in Java
  • Java Program to Implement Two Stacks in an Array
  • Java Snippet
  • Longest Arithmetic Progression Sequence in Java
  • Types of Sockets in Java
  • Java Program to Add Digits Until the Number Becomes a Single Digit Number
  • Next Greater Number with Same Set of Digits in Java
  • Split the Number String into Primes in Java
  • Java Cron Expression
  • Huffman Coding Java
  • Java Snippet Class
  • Why Java is So Popular
  • Java Project idea
  • Java Web Development
  • Brilliant Numbers in Java
  • Sort Elements by Frequency in Java
  • Beautiful Array in Java
  • Moran Numbers in Java
  • Intersection Point of Two Linked List in Java
  • Sparse Number in Java
  • How to Check JRE Version
  • Java Programming Certification
  • Two Decimal Places Java
  • Eclipse Change Theme
  • Java how to Convert Bytes to Hex
  • Decagonal Numbers in Java
  • Java Binary to Hexadecimal Conversion
  • Java Hexadecimal to Binary Conversion
  • How to Capitalize the First Letter of a String in Java
  • Java &0XFF Example
  • Stream findFirst() Method in Java
  • Balanced Parentheses in Java
  • Caesar Cipher Program in Java
  • next() vs nextLine()
  • Java Split String by Comma
  • Spliterator in java 8
  • Tree Model Nodes in Jackson
  • Types of events in Java
  • Callable and Future in Java
  • How to Check Current JDK Version installed in Your System Using CMD
  • How to Round Double and Float up to Two Decimal Places in Java
  • Java 8 Multimap
  • Parallel Stream in Java
  • Java Convert Bytes to Unsigned Bytes
  • Display List of TimeZone with GMT and UTC in Java
  • Binary Strings Without Consecutive Ones in Java
  • Convert IP to Binary in Java
  • Returning Multiple Values in Java
  • Centered Square Numbers in Java
  • ProcessBuilder in Java
  • How to Clear Java Cache
  • IntSummaryStatistics Class in Java
  • Java ProcessBuilder Example
  • Java Program to Delete a Directory
  • Java Program to Print Even Odd Using Two Threads
  • Java Variant
  • MessageDigest in Java
  • Alphabet Pattern in Java
  • Java Linter
  • Java Mod Example
  • Stone Game in Java
  • TypeErasure in Java
  • How to Remove substring from String in Java
  • Program to print a string in vertical in Java
  • How to Split a String between Numbers and Letters
  • String Handling in Java
  • Isomorphic String in Java
  • Java ImageIO Class
  • Minimum Difference Subarrays in Java
  • Plus One to Array Problem in Java
  • Unequal Adjacent Elements in Java
  • Java Parallel Stream Example
  • SHA Hashing in Java
  • How to make Java projects
  • Java Fibers
  • Java MD5 Hashing Example
  • Hogben Numbers in Java
  • Self-Descriptive Numbers in Java
  • Hybrid Inheritance in Java
  • Java IP Address (IPv4) Regex Examples
  • Converting Long to Date in JAVA
  • Java 17 new features
  • GCD of Different SubSequences in Java
  • Sylvester Sequence in Java
  • Console in Java
  • Asynchronous Call in Java
  • Minimum Window Substring in Java
  • Nth Term of Geometric Progression in Java
  • Coding Guidelines in Java
  • Couple Holding Hands Problem in Java
  • Count Ones in a Sorted binary array in Java
  • Ordered Pair in Java
  • Tetris Game in Java
  • Factorial Trailing Zeroes in Java
  • Java Assert Examples
  • Minimum Insertion To Form A Palindrome in Java
  • Wiggle Sort in Java
  • Java Exit Code 13
  • Java JFileChooser
  • What is LINQ
  • NZEC in Java
  • Box Stacking Problem
  • K Most Frequent Elements in Java
  • Parallel Programming in Java
  • How to Generate JVM Heap Memory Dump
  • Java Program to use Finally Block for Catching Exceptions
  • Count Login Attempts Java
  • Largest Independent Set in Java
  • Longest Subarray With All Even or Odd Elements in Java
  • Open and Closed Hashing in Java
  • DAO Class in Java
  • Kynea Numbers in Java
  • UTF in Java
  • Zygodromes in Java
  • ElasticSearch Java API
  • Form Feed in Java
  • Java Clone Examples
  • Payment Gateway Integration in Java
  • What is PMD
  • RegionMatches() Method in Java
  • Repaint() Method in Java
  • Serial Communication in Java
  • Count Double Increasing Series in A Range in Java
  • Longest Consecutive Subsequence in Java
  • Smallest Subarray With K Distinct Numbers in Java
  • String Sort Custom in Java
  • Count Number of Distinct Substrings in a String in Java
  • Display All Subsets of An Integer Array in Java
  • Digit Count in a Factorial Of a Number in Java
  • Valid Parentheses Problem in Java
  • Median Of Stream Of Running Integers in Java
  • Arrow Operator in Java
  • Java Learning app
  • Create Preorder Using Postorder and Leaf Nodes Array
  • Display Leaf nodes from Preorder of a BST in Java
  • Unicodes for Operators in Java
  • XOR and XNOR operators in Java
  • AWS Lambda in Java
  • AWS Polly in Java
  • SAML in Java
  • SonarQube in Java
  • UniRest in Java
  • Override equals method in Java
  • Undo and Redo Operations in Java
  • Size of longest Divisible Subset in an Array in Java
  • Sort An Array According To The Set Bits Count in Java
  • Two constructors in one class in Java
  • Union in Java
  • What is New in Java 15
  • ART in Java
  • Definite Assignment in Java
  • Cast Operator in Java
  • Diamond operator in Java
  • Java Singleton Enum
  • Three-way operator | Ternary operator in Java
  • GoF Design Pattern Java
  • Shorthand Operator in Java
  • What is new in Java 17
  • How to Find the Java Version in Linux
  • What is New in Java 12
  • Exception in Thread Main java.util.NoSuchElementException no line Found
  • How to reverse a string using recursion in Java
  • Java Program to Reverse a String Using Stack
  • Java Program to Reverse a String Using the Stack Data Structure
  • Reverse Middle Words of a String in Java
  • Sastry Numbers in Java
  • Sum of LCM in Java
  • Tilde Operator in Java
  • 8 Puzzle problems in Java
  • Maximum Sum Such That No Two Elements Are Adjacent in Java
  • Reverse a String in Place in Java
  • Reverse a string Using a Byte array in Java
  • Reverse a String Using Java Collections
  • Reverse String with Special Characters in Java
  • get timestamp in java
  • How to convert file to hex in java
  • AbstractSet in java
  • List vs Set vs Map in Java
  • Birthday Problem in Java
  • How to Calculate the Time Difference Between Two Dates in Java
  • Number of Mismatching Bits in Java
  • Palindrome Permutation of a String in Java
  • Grepcode java.util.Date
  • How to add 24 hrs to date in Java
  • How to Change the Day in The Date Using Java
  • Java ByteBuffer Size
  • java.lang.NoSuchMethodError
  • Maximum XOR Value in Java
  • How to Add Hours to The Date Object in Java
  • How to Increment and Decrement Date Using Java
  • Multithreading Scenarios in Java
  • Switch case with enum in Java
  • Longest Harmonious Subsequence in Java
  • Count OR Pairs in Java
  • Merge Two Sorted Arrays Without Extra Space in Java
  • How to call a concrete method of abstract class in Java
  • How to create an instance of abstract class in Java
  • Java Console Error
  • 503 error handling retry code snippets Java
  • Implementation Of Abstraction In Java
  • How to avoid thread deadlock in Java
  • Number of Squareful Arrays in Java
  • One-Time Password Generator Code In Java
  • Real-Time Face Recognition In Java
  • Converting Integer Data Type to Byte Data Type Using Typecasting in Java
  • How to Generate File checksum Value
  • Index Mapping (or Trivial Hashing) With Negatives allowed in Java
  • Shortest Path in a Binary Maze in Java
  • customized exception in Java
  • Difference between error and exception in Java
  • How to solve deprecated error in Java
  • Jagged Array in Java
  • CloneNotSupportedException in Java with Examples
  • Difference Between Function and Method in Java
  • Immutable List in Java
  • Nesting Of Methods in Java
  • How to Convert Date into Character Month and Year Java
  • How to Mock Lambda Expression in Java
  • How to Return Value from Lambda Expression Java
  • if Condition in Lambda Expression Java
  • Chained Exceptions in Java
  • Final static variable in Java
  • Java File Watcher
  • Various Operations on HashSet in Java
  • Word Ladder Problem in Java
  • Various Operations on Queue in Java
  • Various Operations on Queue Using Linked List in Java
  • Various Operations on Queue Using Stack in Java
  • Get Yesterday's Date from Localdate Java
  • Get Yesterday's Date by No of Days in Java
  • Advantages of Lambda Expression in Java 8
  • Cast Generic Type to Specific type Java
  • ConcurrentSkipListSet in Java
  • Fail Fast Vs. Fail-Safe in Java
  • Get Yesterday's Date in Milliseconds Java
  • Get Yesterday's Date Using Date Class Java
  • Getting First Date of Month in Java
  • Gregorian Calendar Java Current Date
  • How to Calculate Time Difference Between Two Dates in Java
  • How to Calculate Week Number from Current Date in Java
  • Keystore vs Truststore
  • Leap Year Program in Java
  • Online Java Compiler GDB
  • Operators in Java MCQ
  • Separators In Java
  • StringIndexOutOfBoundsException in Java
  • Anonymous Function in Java
  • Default Parameter in Java
  • Group by Date Code in Java
  • How to add 6 months to Current Date in Java
  • How to Reverse A String in Java Letter by Letter
  • Java 8 Object Null Check
  • Java Synchronized
  • Types of Arithmetic Operators in Java
  • Types of JDBC Drivers in Java
  • Unmarshalling in Java
  • Write a Program to Print Reverse of a Vowels String in Java
  • ClassNotFound Exception in Java
  • Null Pointer Exception in Java
  • Why Does BufferedReader Throw IOException in Java
  • Java Program to Add two Complex Numbers
  • Read and Print All Files From a Zip File in Java
  • Reverse an Array in Java
  • Right Shift Zero Fill Operator in Java
  • Static Block in Java
  • Accessor and Mutator in Java
  • Array of Class Objects in Java
  • Benefits of Generics in Java
  • Can Abstract Classes Have Static Methods in Java
  • ClassNotFoundException Java
  • Creating a Custom Generic Class in Java
  • Generic Queue Java
  • Getting Total Hours From 2 Dates in Java
  • How to add 2 dates in Java
  • How to Break a Date and Time in Java
  • How to Call Generic Method in Java
  • How to Increment and Decrement Date using Java
  • Java Class Methods List
  • Java Full Stack Developer
  • Java.lang.NullPointerException
  • Least Operator to Express Number in Java
  • Shunting Yard Algorithm in Java
  • Switch Case Java
  • Treeset Java Operations
  • Types of Logical Operators in Java
  • What is Cast Operator in Java
  • What is Jersey in Java
  • Alternative to Java Serialization
  • API Development in Java
  • Disadvantage of Multithreading in Java
  • Find the row with the maximum number of 1s
  • Generic Comparator in Java
  • Generic LinkedList in Java
  • Generic Programming in Java Example
  • How Can I Give the Default Date in The Array Java
  • How to Accept Date in Java
  • How to add 4 years to Date in Java
  • How to Check Date Equality in Java
  • How to Modify HTML File Using Java
  • Java 8 Multithreading Features
  • Java Abstract Class and Methods
  • Java Thread Dump Analyser
  • Process vs. Thread in Java
  • Reverse String Using Array in Java
  • Types of Assignment Operators in Java
  • Types of Bitwise Operators in Java
  • Union and Intersection Of Two Sorted Arrays In Java
  • Vector Operations Java
  • Java Books Multithreading
  • Advantages of Generics in Java
  • Arrow Operator Java
  • Generic Code in Java
  • Generic Method in Java Example
  • Getting a Range of Dates in Java
  • Getting the Day from a Date in Java
  • How Counter Work with Date Using Java
  • How to Add Date in Arraylist Java
  • How to Create a Generic List in Java
  • Java Extend Multiple Classes
  • Java Function
  • Java Generics Design Patterns
  • Why Are Generics Used in Java
  • XOR Binary Operator in Java
  • Check if the given string contains all the digits in Java
  • Constructor in Abstract Class in Java
  • Count number of a class objects created in Java
  • Difference Between Byte Code and Machine Code in Java
  • Java Program to Append a String in an Existing File
  • Main thread in Java
  • Store Two Numbers in One Byte Using Bit Manipulation in Java
  • The Knight's Tour Problem in Java
  • Business Board Problem in Java
  • Business Consumer Problem in Java
  • Buy as Much Candles as Possible Java Problem
  • Get Year from Date in Java
  • How to Assign Static Value to Date in Java
  • Java List Node
  • Java List Sort Lambda
  • Java Program to Get the Size of a Directory
  • Misc Operators in Java
  • Reverse A String and Reverse Every Alternative String in Java
  • Reverse a String in Java Using StringBuilder
  • Reverse Alternate Words in A String Java
  • Size of Empty Class in Java
  • Titniry Operation in Java
  • Triple Shift Operator in Java
  • Types of Conditional Operators in Java
  • View Operation in Java
  • What is Linked list Operation in Java
  • What is Short Circuit && And or Operator in Java
  • What is the & Operator in Java
  • Why to use enum in Java
  • XOR Bitwise Operator in Java
  • XOR Logical Operator Java
  • Compile-Time Polymorphism in Java
  • Convert JSON to Java Object Online
  • Difference between comparing String using == and .equals() method in Java
  • Difference Between Singleton Pattern and Static Class in Java
  • Difference Between Static and Non-Static Nested Class in Java
  • Getting Date from Calendar in Java
  • How to Swap or Exchange Objects in Java
  • Java Get Class of Generic Parameter
  • Java Interface Generic Parameter
  • Java Map Generic
  • Java Program for Maximum Product Subarray
  • Java Program To Print Even Length Words in a String
  • Logger Class in Java
  • Manacher's Algorithm in Java
  • Mutable Class in Java
  • Online Java IDE
  • Package getImplementationVersion() method in Java with Examples
  • Set Default Close Operation in Java
  • Sorting a Java Vector in Descending Order Using Comparator
  • Types of Interfaces in Java
  • Understanding String Comparison Operator in Java
  • User-Defined Packages in Java
  • Valid variants of main() in Java
  • What is a Reference Variable in Java
  • What is an Instance in Java
  • What is Retrieval Operation in ArrayList Java
  • When to Use the Static Method in Java
  • XOR Operations in Java
  • 7th Sep - Array Declaration in Java
  • 7th Sep - Bad Operand Types Error in Java
  • 7th Sep - Data Structures in Java
  • 7th Sep - Generic Type Casting In Java
  • 7th Sep - Multiple Inheritance in Java
  • 7th Sep - Nested Initialization for Singleton Class in Java
  • 7th Sep - Object in Java
  • 7th Sep - Recursive Constructor Invocation in Java
  • 7th Sep - Java Language / What is Java
  • 7th Sep - Why is Java Platform Independent
  • 7th Sep - Card Flipping Game in Java
  • 7th Sep - Create Generic Method in Java
  • 7th Sep - Difference between super and super() in Java with Examples
  • 7th Sep - for loop enum Java
  • 7th Sep - How to Convert a String to Enum in Java
  • 7th Sep - Illustrate Class Loading and Static Blocks in Java Inheritance
  • 7th Sep - Introduction To Java
  • 7th Sep - Java Lambda foreach
  • 7th Sep - Java Latest Version
  • 7th Sep - Java Method Signature
  • 7th Sep - Java Practice Programs
  • 7th Sep - Java SwingWorker Class
  • 7th Sep - java.util.concurrent.RecursiveAction class in Java With Examples
  • 7th Sep - Largest Palindrome by Changing at Most K-digits in Java
  • 7th Sep - Parameter Passing Techniques in Java with Examples
  • 7th Sep - Reverse a String in Java Using a While Loop
  • 7th Sep - Reverse a String Using a For Loop in Java
  • 7th Sep - Short Circuit Operator in Java
  • 7th Sep - Java 8 Stream API
  • 7th Sep - XOR Operation on Integers in Java
  • 7th Sep - XOR Operation on Long in Java
  • Array Programs in Java
  • Concrete Class in Java
  • Difference between Character Stream and Byte Stream in Java
  • Difference Between Static and non-static in Java
  • Different Ways to Convert java.util.Date to java.time.LocalDate in Java
  • Find the Good Matrix Problem in Java
  • How Streams Work in Java
  • How to Accept Different Formats of Date in Java
  • How to Add Date in MySQL from Java
  • How to Find the Size of int in Java
  • How to Make a Field Serializable in Java
  • How to Pass an Array to Function in Java
  • How to Pass an ArrayList to a Method in Java
  • Implementing the Java Queue Interface
  • Initialization of local variable in a conditional block in Java
  • isnull() Method in Java
  • Java Array Generic
  • Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe
  • Java Program to Demonstrate the Non-Lazy Initialization Thread-Safe
  • Java Static Field Initialization
  • Machine Learning Using Java
  • Mars Rover Problem in Java
  • Model Class in Java
  • Nested Exception Handling in Java
  • Program to Convert List to Stream in Java
  • Static Polymorphism in Java
  • Static Reference Variables in Java
  • Sum of Two Arrays in Java
  • What is Is-A-Relationship in Java
  • When to Use Vector in Java
  • Which Class cannot be subclassed in Java
  • Word Search Problem in Java
  • XOR Operation Between Sets in Java
  • Burger Problem in Java Game
  • Convert Set to List in Java
  • Floyd Triangle in Java
  • How to Call Static Blocks in Java
  • Interface Attributes in Java
  • Java Applications in the Real World
  • Java Concurrent Array
  • Java Detect Date Format
  • Java Interface Without Methods
  • Java Iterator Performance
  • Java Packet
  • Java Static Instance of Class
  • Java TreeMap Sort by Value
  • Length of List in Java
  • List of Checked Exceptions in Java
  • Message Passing in Java
  • Product Maximization Problem in Java
  • Terminal Operations in Java 8
  • Understanding Base Class in Java
  • Difference between Early Binding and Late Binding in Java
  • Collectors toCollection() in Java
  • Difference between ExecutorService execute() and submit() method in Java
  • Difference between Java and Core Java
  • Different Types of Recursions in Java
  • Initialize a static map in Java with Examples
  • Merge Sort Using Multithreading in Java
  • Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version
  • Circular Primes in Java
  • Difference Between poll() and remove() Method of a Queue
  • EvalEx Java: Expression Evaluation in Java
  • Exeter Caption Contest Java Program
  • FileInputStream finalize() Method in Java
  • Find the Losers of the Circular Game problem in Java
  • Finding the Differences Between Two Lists in Java
  • Finding the Maximum Points on a Line in Java
  • Get Local IP Address in Java
  • Handling "Handler dispatch failed" Nested Exception: java.lang.StackOverflowError in Java
  • Harmonic Number in Java
  • How to Find the Percentage of Uppercase Letters, Lowercase Letters, Digits, and Special Characters in a String Using Java
  • Interface Variables in Java
  • Java 8 Interface Features
  • Java Class Notation
  • Java Exception Messages Examples and Explanations
  • Java Package Annotation
  • Java Program to Find First Non-Repeating Character in String
  • Java Static Type Vs. Dynamic Type
  • Kaprekar Number in Java
  • Multitasking in Java
  • Niven Number in Java
  • Rhombus Pattern in Java
  • Shuffle an Array in Java
  • Static Object in Java
  • The Scope of Variables in Java
  • Toggle String in Java
  • Use of Singleton Class in Java
  • What is the Difference Between Future and Callable Interfaces in Java
  • Aggregate Operation in Java 8
  • Bounded Types in Java
  • Calculating Batting Average in Java
  • Compare Two LinkedList in Java
  • Comparison of Autoboxed Integer objects in Java
  • Count Tokens in Java
  • Cyclomatic Complexity in Java
  • Deprecated Meaning in Java
  • Double Brace Initialization in Java
  • Functional Interface in Java
  • How to prevent objects of a class from Garbage Collection in Java
  • Java Cast Object to Class
  • Java isAlive() Method
  • Java Line Feed Character
  • java.net.MulticastSocket class in Java
  • Keytool Error java.io.FileNotFoundException
  • Matrix Diagonal Sum in Java
  • Number of Boomerangs Problem in Java
  • Sieve of Eratosthenes Algorithm in Java
  • Similarities Between Bastar and Java
  • Spring vs. Struts in Java
  • Switch Case in Java 12
  • The Pig Game in Java
  • Unreachable Code Error in Java
  • Who Were the Kalangs of Java
  • 2048 Game in Java
  • Abundant Number in Java
  • Advantages of Applet in Java
  • Alpha-Beta Pruning Java
  • ArgoUML Reverse Engineering Java
  • Can Constructor be Static in Java
  • Can we create object of interface in Java
  • Chatbot Application in Java
  • Difference Between Component and Container in Java
  • Difference Between Java.sql and Javax.sql
  • Find A Pair with Maximum Product in Array of Integers
  • Goal Stack Planning Program in Java
  • Half Diamond Pattern in Java
  • How to find trigonometric values of an angle in Java
  • How to Override tostring() method in Java
  • Inserting a Node in a Doubly Linked List in Java
  • Java 9 Immutable Collections
  • Java 9 Interface Private Methods
  • Java Convert Array to Collection
  • Java Transaction API
  • Methods to Take Input in Java
  • Parallelogram Pattern in Java
  • Reminder Program in Java
  • Sliding Window Protocol in Java
  • Static Method in Java
  • String Reverse in Java 8 Using Lambdas
  • Types of Threads in Java
  • What is thread safety in Java? How do you achieve it?
  • xxwxx.dll Virus Java 9
  • Java 8 Merge Two Maps with Same Keys
  • Java 8 StringJoiner, String.join(), and Collectors.joining()
  • Java 9 @SafeVarargs Annotation Changes
  • Java 9 Stream API Improvements
  • Java 11 var in Lambda Expressions
  • Sequential Search Java
  • Thread Group in Java
  • User Thread Vs. Daemon Thread in Java
  • Collections Vs. Streams in Java
  • Import statement in Java
  • init() Method in Java
  • Java Generics Jenkov
  • Ambiguity in Java
  • Benefits of Learning Java
  • Designing a Vending Machine in Java
  • Monolithic Applications in Java
  • Name Two Types of Java Program
  • Random Access Interface in Java
  • Rust Vs. Java
  • Types of Constants in Java
  • Execute the Main Method Multiple Times in Java
  • Find the element at specified index in a Spiral Matrix in Java
  • Find The Index of An Array Element in Java
  • Mark-and-Sweep Garbage Collection Algorithm in Java
  • Shadowing of Static Functions in Java
  • Straight Line Numbers in Java
  • Zumkeller Numbers in Java
  • Types of Layout Manager in Java
  • Virtual Threads in Java 21
  • Add Two Numbers Without Using Operator in Java
  • Automatic Type Promotion in Java
  • ContentPane Java
  • Difference Between findElement() and findElements() in Java
  • Difference Between Inheritance and Interfaces in Java
  • Difference Between Jdeps and Jdeprscan tools in Java
  • Find Length of String in Java Without Using Function
  • InvocationTargetException in Java
  • Java Maps to JSON
  • Key Encapsulation Mechanism API in Java 21
  • Placeholder Java
  • String Templates in Java 21
  • Why Java is Robust Language
  • Collecting in Java 8
  • containsIgnoreCase() Method in Java
  • Convert String to Biginteger In Java
  • Convert String to Map in Java
  • Define Macro in Java
  • Difference Between Lock and Monitor in Java Concurrency
  • Difference Between the start() and run() Methods in Java
  • Generalization and Specialization in Java
  • getChannel() Method in Java
  • How to Check Whether an Integer Exists in a Range with Java
  • HttpEntity in Java
  • Lock Framework Vs. Thread Synchronization in Java
  • Niven Number Program in Java
  • Passing Object to Method in Java
  • Pattern Matching for Switch in Java 21
  • Swap First and Last Digit of a Number in Java
  • Adapter Design Pattern in Java
  • Best Automation Frameworks for Java
  • Building a Search Engine in Java
  • Bytecode Verifier in Java
  • Caching Mechanism in Java
  • Comparing Two HashMap in Java
  • Cryptosystem Project in Java
  • Farthest from Zero Program in Java
  • How to Clear Linked List in Java
  • Primitive Data Type Vs. Object Data Type in Java
  • setBounds() Method in Java
  • Unreachable Code or Statement in Java
  • What is Architecture Neutral in Java
  • Difference between wait and notify in Java
  • Dyck Path in Java
  • Find the last two digits of the Factorial of a given Number in Java
  • How to Get an Environment Variable in Java
  • Java Program to open the command prompt and insert commands
  • JVM Shutdown Hook in Java
  • Semiprimes Numbers in Java
  • 12 Tips to Improve Java Code Performance
  • Ad-hoc Polymorphism in Java
  • Array to String Conversion in Java
  • CloudWatch API in Java
  • Essentials of Java Programming Language
  • Extends Vs. Implements in Java
  • 2d Array Sorting in Java
  • Aliquot Sequence in Java
  • Authentication and Authorization in Java
  • Cannot Find Symbol Error in Java
  • Compare Two Excel Files in Java
  • Consecutive Prime Sum Program in Java
  • Count distinct XOR values among pairs using numbers in range 1 to N
  • Difference Between Two Tier and Three Tier Architecture in Java
  • Different Ways of Reading a Text File in Java
  • Empty Array in Java
  • FCFS Program in Java with Arrival Time
  • Immutable Map in Java
  • K-4 City Program in Java
  • Kahn's algorithm for Topological Sorting in Java
  • Most Popular Java Backend Tools
  • Recursive Binary Search in Java
  • Set Intersection in Java
  • String Reverse Preserving White Spaces in Java
  • The Deprecated Annotation in Java
  • What is JNDI in Java
  • Backtracking in Java
  • Comparing Doubles in Java
  • Consecutive Prime Sum in Java
  • Finding Missing Numbers in an Array Using Java
  • Good Number Program in Java
  • How to Compress Image in Java Source Code
  • How to Download a File from a URL in Java
  • Passing an Object to The Method in Java
  • Permutation program in Java
  • Profile Annotation in Java
  • Scenario Based Questions in Java
  • Understanding Static Synchronization in Java
  • Types of Errors in Java
  • Abstract Factory Design Pattern in Java
  • Advantages of Kotlin Over Java
  • Advantages of Methods in Java
  • Applet Program in Java to Draw House with Output
  • Atomic Boolean in Java
  • Bitset Class in Java
  • Bouncy Castle Java
  • Chained Exception in Java
  • Colossal Numbers in Java
  • Compact Profiles Java 8
  • Convert Byte to Image in Java
  • Convert Set to Array in Java
  • Copy ArrayList to another ArrayList Java
  • Copy Data from One File to Another in Java
  • Dead Code in Java
  • Driver Class Java
  • EnumMap in Java
  • Farthest Distance of a 0 From the Centre of a 2-D Matrix in Java
  • How to Terminate a Program in Java
  • Instance Block in Java
  • Iterative Constructs in Java
  • Java 10 var Keyword
  • Nested ArrayList in Java
  • Square Pattern in Java
  • String Interpolation in Java
  • Unnamed Classes and Instance Main Method in Java 21
  • What is difference between cacerts and Keystore in Java
  • Agile Principles Patterns and Practices in Java
  • Color Method in Java
  • Concurrent Collections in Java
  • Create JSON Node in Java
  • Difference Between Checkbox and Radio Button in Java
  • Difference Between Jdeps and Jdeprscan Tools in Java
  • Difference Between Static and Dynamic Dispatch in Java
  • Difference Between Static and Non-Static Members in Java
  • Error Java Invalid Target Release 9
  • Filedialog Java
  • String Permutation in Java
  • Structured Concurrency in Java
  • Uncaught Exception in Java
  • ValueOf() Method in Java
  • Virtual Thread in Java
  • Difference Between Constructor Overloading and Method Overloading in Java
  • Difference Between for loop and for-each Loop in Java
  • Difference Between Fork/Join Framework and ExecutorService in Java
  • Difference Between Local, Instance, and Static Variables in Java
  • Difference Between Multithreading and Multiprocessing in Java
  • Difference Between Serialization and Deserialization in Java
  • Difference Between Socket and Server Socket in Java
  • Advantages of Immutable Classes in Java
  • BMI Calculator Java
  • Code Coverage Tools in Java
  • How to Declare an Empty Array in Java
  • How To Resolve Java.lang.ExceptionInInitializerError in Java
  • Java 18 Snippet Tag with Example
  • Object Life Cycle in Java
  • print() Vs. println() in Java
  • @SuppressWarnings Annotation in Java
  • Types of Cloning in Java
  • What is portable in Java
  • What is the use of an interpreter in Java
  • Abstract Syntax Tree (AST) in Java
  • Aliasing in Java
  • CRUD Operations in Java
  • Euclid-Mullin Sequence in Java
  • Frame Class in Java
  • Initializing a List in Java
  • Number Guessing Game in Java
  • Number of digits in N factorial to the power N in Java
  • Rencontres Number in Java
  • Skewed Binary Tree in Java
  • Vertical zig-zag traversal of a tree in Java
  • Wap to Reverse a String in Java using Lambda Expression
  • Concept of Stream in Java
  • Constraints in Java
  • Context Switching in Java
  • Dart Vs. Java
  • Dependency Inversion Principle in Java
  • Difference Between Containers and Components in Java
  • Difference Between CyclicBarrier and CountDownLatch in Java
  • Difference Between Shallow and Deep Cloning in Java
  • Dots and Boxes Game Java Source code
  • DRY Principle Java
  • How to get File type in Java
  • IllegalArgumentException in Java example
  • Is the main() method compulsory in Java
  • Java Paradigm
  • Lower Bound in Java
  • Method Binding in Java
  • Overflow and Underflow in Java
  • Padding in Java
  • Passing and Returning Objects in Java
  • Single Responsibility Principle in Java
  • ClosedChannelException in Java with Examples
  • How to Fix java.net.ConnectException Connection refused connect in Java
  • java.io.UnsupportedEncodingException in java with Examples
  • Selection Statement in Java
  • Difference Between Java 8 and Java 9
  • Difference Between Nested Class and Inner Class in Java
  • Difference Between OOP and POP in Java
  • Difference Between Static and Dynamic in Java
  • Difference Between Static Binding and Dynamic Binding in Java
  • Difference Between Variable and Constant in Java
  • Alternate Pattern Program in Java
  • Architecture Neutral in Java
  • AutoCloseable Interface in Java
  • BitSet Class in Java
  • Border Layout Manager in Java
  • Digit Extraction in Java
  • Dynamic Method Dispatch Java
  • Dynamic Variable in Java
  • How to Convert Double to string in Java
  • How to Convert Meter to Kilometre in Java
  • How to Install SSL Certificate in Java
  • How to Protect Java Source Code
  • How to Use Random Object in Java
  • Java Backward Compatibility
  • Java New String Class Methods from Java 8 to Java 17
  • Mono in Java
  • Object to int in Java
  • Predefined Streams in Java
  • Prime Factor Program in Java
  • Transfer Statements in Java
  • What is Interceptor in Java
  • Java Array Methods
  • java.lang.Class class in Java
  • Reverse Level Order Traversal in Java
  • Working with JAR and Manifest files In Java
  • Alphabet Board Path Problem in Java
  • Composite Design Pattern Java
  • Default and Static Methods in Interface Java 8
  • Difference Between Constraints and Annotations in Java
  • Difference Between fromJson() and toJson() Methods of GSON in Java
  • Difference Between Java 8 and Java 11
  • Difference Between map() and flatmap() Method in Java 8
  • Difference Between next() and nextLine() Methods in Java
  • Difference Between orTimeout() and completeOnTimeOut() Methods in Java 9
  • Disadvantages of Array in Java
  • How Synchronized works in Java
  • How to Create a Table in Java
  • ID Card Generator Using Java
  • Introspection in JavaBeans
  • Java 15 Features
  • Java Object Model
  • Java Tools and Command-List
  • Next Permutation Java
  • Object as Parameter in Java
  • Optimizing Java Code Performance
  • Pervasive Shallowness in Java
  • Sequenced Collections in Java 21
  • Stdin and Stdout in Java
  • Stream count() Function in Java
  • String.strip() Method in Java
  • Vertical Flip Matrix Problem in Java
  • Calling Object in Java
  • Characteristics of Constructor in Java
  • Counting Problem in Multithreading in Java
  • Creating Multiple Pools of Objects of Variable Size in Java
  • Default Exception in Java
  • How to Install Multiple JDK's in Windows
  • Differences Between Vectors and Arrays in Java
  • Duplicate Class Errors in Java
  • Example of Data Hiding in Java
  • Foreign Function and Memory APIs in Java 21
  • Generic Tree Implementation in Java
  • getSource() Method in Java
  • Giuga numbers in Java
  • Hessian Java
  • How to Connect Login Page to Database in Java
  • Difference between BlueJ and JDK 1.3
  • How to Solve Incompatible Types Error in Java
  • Java 8 Method References
  • Java 9 Try with Resources Improvements
  • Menu-Driven Program in Java
  • Mono Class in Java
  • Multithreading Vs. Asynchronous in Java
  • Nested HashMap in Java
  • Number Series Program in Java
  • Object Slicing in Java
  • Oracle Java
  • Print 1 to 100 Without Loop in Java
  • Remove elements from a List that satisfy given predicate in Java
  • Replace Element in Arraylist Java
  • Sliding Puzzle Game in Java
  • Strobogrammatic Number in Java
  • Web Methods in Java
  • Web Scraping Java
  • Window Event in Java
  • @Builder Annotation in Java
  • Advantages of Abstraction in Java
  • Advantages of Packages in Java
  • Bounce Tales Java Game Download
  • Breaking Singleton Class Pattern in Java
  • Building a Brick Breaker Game in Java
  • Building a Scientific Calculator in Java
  • Circle Program in Java
  • Class Memory in Java
  • Convert Byte to an Image in Java
  • Count Paths in Given Matrix in Java
  • Difference Between Iterator and ListIterator in Java with Example
  • Distinct Character Count Java Stream
  • EOFException in Java
  • ExecutionException Java 8
  • Generic Object in Java
  • How to Create an Unmodifiable List in Java
  • How to Create Dynamic SQL Query in Java
  • How to Return a 2D Array in Java
  • Java 8 Stream.distinct() Method
  • Java setPriority() Method
  • Mutator Methods in Java
  • Predicate Consumer Supplier Java 8
  • Program to Generate CAPTCHA and Verify User Using Java
  • Random Flip Matrix in Java
  • System Class in Java
  • Vigenere Cipher Program in Java
  • Behavior-Driven Development (BDD) in Java
  • CI/ CD Tools for Java
  • cint in Java
  • Command Pattern in Java
  • CSV to List Java
  • Difference Between Java Servlets and CGI
  • Difference Between Multithreading Multitasking, and Multiprocessing in Java
  • Encoding Three Strings in Java
  • How to Import Jar File in Eclipse
  • Meta Class Vs. Class in Java
  • Meta Class Vs. Super Class in Java
  • Print Odd and Even Numbers by Two Threads in Java
  • Scoped value in Java
  • Upper-Bounded Wildcards in Java
  • Wildcards in Java
  • Zero Matrix Problem in Java
  • All Possible Combinations of a String in Java
  • Atomic Reference in Java
  • Final Method Overloading in Java| Can We Overload Final Methods
  • Constructor in Inheritance in Java
  • Design Your Custom Connection Pool in Java
  • How Microservices Communicate with Each Other in Java
  • How to Convert String to Timestamp in Java
  • Java 10 Collectors Methods
  • Java and Apache OpenNLP
  • Java Deep Learning
  • Java Iterator Vs. Listiterator Vs. Spliterator
  • Pure Functions in Java
  • Use of Constructor in Java | Purpose of Constructor in Java
  • Implement Quintet Class with Quartet Class in Java using JavaTuples
  • Java Best Practices
  • Efficiently Reading Input For Competitive Programming using Java 8
  • Length of the longest substring without repeating characters in Java
  • Advantages of Inner Class in Java
  • AES GCM Encryption Java
  • Array Default Values in Java
  • Copy File in Java from one Location to Another
  • Creating Templates in Java
  • Different Packages in Java
  • How to Add Elements to an Arraylist in Java Dynamically
  • How to Add Splash Screen in Java
  • How to Calculate Average Star Rating in Java
  • Immutable Class with Mutable Object in Java
  • Java instanceOf() Generics
  • Set Precision in Java
  • Snake Game in Java
  • Tower of Hanoi Program in Java
  • Two Types of Streams Offered by Java
  • Uses of Collections in Java
  • Additive Numbers in Java
  • Association Vs. Aggregation Vs. Composition in Java
  • Covariant and Contravariant Java
  • Creating Immutable Custom Classes in Java
  • mapToInt() in Java
  • Methods of Gson in Java
  • Server Socket in Java
  • Check String Are Permutation of Each Other in Java
  • Containerization in Java
  • Difference Between Multithreading and Multiprogramming in Java
  • Flyweight Design Pattern
  • HMAC Encryption in Java
  • How to Clear Error in Java Program
  • 5 Types of Java
  • Design a Job Scheduler in Java
  • Elements of Java Programming
  • Generational ZCG in Java 21
  • How to Print Arraylist Without Brackets Java
  • Interface Vs. Abstract Class After Java 8
  • Java 9 Optional Class Improvements
  • Number of GP sequence Problem in Java
  • Pattern Matching for Switch
  • Range Addition Problem in Java
  • Swap Corner Words and Reverse Middle Characters in Java
  • Kadane's Algorithm in Java
  • Capture the Pawns Problem in Java
  • Find Pair With Smallest Difference in Java
  • How to pad a String in Java
  • When to use Serialization and Externalizable Interface
  • Which Component is responsible to run Java Program
  • Difference Between Java and Bastar
  • Difference Between Static and Instance Methods in Java
  • Difference Between While and Do While loop in Java
  • Future Interface in Java
  • Invert a Binary tree in Java
  • Java Template Engine
  • KeyValue Class in JavaTuples
  • Quantifiers in Java
  • Swapping Pairs of Characters in a String in Java
  • Version Enhancements in Exception Handling introduced in Java SE 7
  • Find all Palindromic Sub-Strings of a given String in Java
  • Find if String is K-Palindrome or not in Java
  • Count Pairs from an Array with Even Product of Count of Distinct Prime Factor in Java
  • Find if an Array of Strings can be Chained to form a Circle in Java
  • Find largest factor of N such that NF is less than K in Java
  • Lexicographically First Palindromic String in Java
  • LinkedTransferQueue removeAll() method in Java with Examples
  • Next Smallest Palindrome problem in Java

In , assignment is used to assign values to a variable. In this section, we will discuss the .

The is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results in shorter syntax forms. In short, the compound assignment operator can be used in place of an assignment operator.

For example:

Let's write the above statements using the compound assignment operator.

Using both assignment operators generates the same result.

Java supports the following assignment operators:

CatagoriesOperatorDescriptionExampleEquivalent Expression
It assigns the result of the addition.count += 1count = count + 1
It assigns the result of the subtraction.count -= 2count = count - 2
It assigns the result of the multiplication.price *= quantityprice = price * quantity
It assigns the result of the division.average /= number_of_termsaverage = number_of_terms
It assigns the result of the remainder of the division.s %= 1000s = s % 1000
It assigns the result of the signed left bit shift.res <<= numres = res << num
It assigns the result of the signed right bit shift.y >>= 1y = y >> 1
It assigns the result of the logical AND.x &= 2x = x & 2
It assigns the result of the logical XOR.a ^= ba = a ^ b
It assigns the result of the logical OR.flag |= trueflag = flag | true
It assigns the result of the unsigned right bit shift.p >>>= 4p = p >>> 4

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

Latest Courses

Python

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks

Contact info

G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India

[email protected] .

Facebook

Interview Questions

Online compiler.

Switch Case vs. If-Else in JavaScript Explained

Switch case and if-else offer two different approaches to writing conditional statements in JavaScript. Here’s how to determine which one to use.

Michelle Wong

In JavaScript , the switch case and if-else statement provide two different ways to write a conditional statement .  The switch case is used to test the value of the given variable against a list of case values to determine which code block to run. The if-else statement nests conditions under if and else statements that determine which code to execute. It can be difficult to determine which one to use.

Switch Case vs. If-Else Statements in JavaScript Explained

  • Switch case: Switch case allows conditions to be separated into different case blocks. The expression inside the switch statement decides what to execute. 
  •   If-else statements: If-else statements nest conditions under if and else statements. The condition in the if statement determines whether to execute code under the if block or the else block.  

However, a switch statement is usually more efficient than a set of nested ifs. When you have to choose which one to use, it’s best to decide based on readability and the expression that the statement is testing.

Differences Between Switch Case vs. If-Else 

  • The expression inside of an if statement decides whether to execute the statements inside the if block or the else block. For switch, the expression inside the switch statement decides which case to execute.
  • The if-else statement checks for equality as well as for logical expression. On the other hand, switch checks only for equality.
  • The if statement evaluates integer, character, pointer or floating-point type or boolean type. The switch statement evaluates only character or an integer datatype.
  • In if-else statements, the if statement determines whether the statement under the if block will execute or the statement under else block statement will execute. However, the expression in the switch statement decides which case to execute, however, if you don’t apply a break statement after each case , it will execute until the end of switch statement.
  • For an if-else statement, if the expression inside of the if turns out to be false, the statement inside of the else block will be executed. For the switch statement, if the expression inside of the switch statement turns out to be false, then the default statements are executed.
  • It can be difficult to edit if-else statements since it’s tedious to trace where the correction is required. Many people agree that it’s much simpler to edit switch statements since they’re easy to trace.

More on Software Engineering JavaScript Check If a Checkbox Is Checked

Switch Case vs. If-Else Syntax

This is the general syntax of an if-else statement:

And this is the general syntax for switch:

The if-else ladder is of type strict condition check, while switch is of type jump value catching.

More on Software Engineering Guide to the JavaScript Array Filter() Method

Advantages of Switch Case vs. If-Else 

  • A switch statement works much faster than the equivalent if-else ladder because the compiler generates a jump table for a switch during compilation. During execution, instead of checking which case is satisfied, it only decides which case has to be executed.
  • A switch case statement is more readable compared to if-else statements.

In the end, the choice is yours and I hope this blog helps lead you in the right path to making the most informed decision when to use an if-else statement verses a switch case!

Frequently Asked Questions

Is switch better than if-else in javascript .

Switch case is considered faster and more readable than nested if-else statements. If-else statements require the compiler to check each statement to determine if a condition is met. Switch case is more efficient because it allows the compiler to determine only which case has to be executed. 

What is the key difference between switch case vs. if-else statements in JavaScript?

  • If-else statements involving branching conditions under if and else statements. The code executes the if statement if a given condition is met, otherwise it executes the else statement. Here’s how the syntax looks:
  • In switch case , the expression in the switch statement decides which case to execute along with a break statement after each case. This allows the compiler to execute only the code in which the case condition is met, making it a more streamlined version of if-else. The syntax looks like this:

Recent Software Engineering Perspectives Articles

Why Separating Knowledge, Compute and Storage is the Next Big Leap in Data Platforms

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

assign and execute if/else conditions in single line

How can I do that for example, if block checks if the condition is true or false and then execute action depends on that condition?

Something like that do it all in the same line without blocks , it that possible ?

Sorry for my bad English

  • if-statement
  • ternary-operator

Sufiyan Ghori's user avatar

  • 1 Why wihout blocks? It's mere syntax. Any reason? –  m0skit0 Commented Jan 30, 2015 at 12:36
  • 1 People downvoting new users without even bothering to comment makes me sad. –  André Laszlo Commented Jan 30, 2015 at 12:55

7 Answers 7

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 .

here is another example using String ,

this examples would clear it more. It prints the salutation properly for a person's gender:

Question: you cannot call a method inside ternary operator.

No, this is incorrect.

You can call a method inside a ternary operator as long as it returns a value which is of the same type as the left-side of a ternary operator,

consider this example,

let's create a method that returns a String value,

Now see this code,

this will execute just fine because return type of message() and variable type of answer are the same, i.e String .

  • Thx, for the examples now i get it! So if(true) ? trueaction; : falseaction; would work no ? –  peti446 Commented Jan 30, 2015 at 12:55
  • (true or false) ? (execute this if true) : (execute this if false) –  Sufiyan Ghori Commented Jan 30, 2015 at 13:52
  • i mean if i can call a method there like for example (true)?System.out.println("true") : System.out.println("false") but i see that @neeraj-jain say that ternary operation cannot execute methods, but thx for all! –  peti446 Commented Jan 30, 2015 at 13:57
  • in your given condition, i.e (true)?System.out.println("true") : System.out.println("false") what would be the left side of your statement ?, you can do this instead, System.out.print(false ? "true" : "false"); –  Sufiyan Ghori Commented Jan 30, 2015 at 14:14
  • Ok, thanks for all! the left side would be a check for ecample 'if(myNumber == 1) ? callTrueMethod; : callFalseMethod;' The method can be for example a void. –  peti446 Commented Jan 30, 2015 at 14:22

Is logically identical to

Dave's user avatar

For putting a conditional statement on one line, you could use the ternary operator. Note, however, that this can only be used in assignments , i.e. if the functions actually return something and you want to assign that value to a variable.

If you want to execute methods, that do not return anything, but have some other side-effects, the ternary operator is not the right way to go. In fact, it does not even compile!

Instead, you should just use a plain-old if-then-else . It's also easier to read.

tobias_k's user avatar

You can not use Ternary Operator as you can not invoke any void method (i.e. the method which do not return anything ) from Ternary Operator

As it is not the intended use of the ternary operator .

If you really want it to be achieved in 1 line, you can write:

Neeraj Jain's user avatar

Maybe the ternary operator does what you want:

André Laszlo's user avatar

You can use a trenary operator:

which I guess pretty much does what you want.

Eypros's user avatar

If you really, really need a one-liner you could use this syntax (Known as ternary operator) :

1>0 ? "do action" : " Do other action";

An example would be this:

String result = x>y ? "x>y" : "y>x";

But this is not recommended, most people hate this syntax because it can become very unreadable if you cascade several conditions inside it, or even worst cascade ternary operators.

But it has it's uses.

Cristiano Fontes's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged java if-statement ternary-operator or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • C++ std::function-like queue
  • Fast leap year check
  • O(nloglogn) Sorting Algorithm?
  • What is the oldest open math problem outside of number theory?
  • Custom PCB with Esp32-S3 isn't recognised by Device Manager for every board ordered
  • Why do I often see bunches of medical helicopters hovering in clusters in various locations
  • Should I change advisors because mine doesn't object to publishing at MDPI?
  • How should I email HR after an unpleasant / annoying interview?
  • Whom did Jesus' followers accompany -- a soldier or a layman?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Proving commutator of velocity differentiation and total time differentiation is position differentiation
  • mmrm R package : No optimizer led to a successful model fit
  • Input impedance of an op amp when sharing bias resistor across multiple op amps
  • Are there something like standard documents for 8.3 filename which explicitly mention about the folder names?
  • Concerns with newly installed floor tile
  • Stuck as a solo dev
  • Subject verb agreement - I as well as he is/am the culprit
  • Is it safe to use the dnd 3.5 skill system in pathfinder 1e?
  • Why was Esther included in the canon?
  • Rocky Mountains Elevation Cutout
  • What factors cause differences between dried herb/spice brands?
  • Negating a multiply quantified statement
  • If Act A repeals another Act B, and Act A is repealed, what happens to the Act B?
  • What are the pros and cons of the classic portfolio by Wealthfront?

use of assignment statement in java

IMAGES

  1. Java 1

    use of assignment statement in java

  2. The Assignment Operator in Java

    use of assignment statement in java

  3. 1.4. Expressions and Assignment Statements

    use of assignment statement in java

  4. PPT

    use of assignment statement in java

  5. LESSON 5

    use of assignment statement in java

  6. Java Assignment operators

    use of assignment statement in java

VIDEO

  1. #20. Assignment Operators in Java

  2. Core

  3. JAVA TUTORIAL

  4. Java Programming Tutorials

  5. Java Tutorial # 7

  6. java101

COMMENTS

  1. Java Assignment Operators with Examples

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

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

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

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

  5. All Java Assignment Operators (Explained With Examples)

    Java Conditional Statements: if, if-else, nested if, ladder, switch; Nested Loop in Java (Nested for, while, do-while loops) for-each Loop in Java (Syntax, Examples, Flowchart) Java Continue Statement: Use, Examples, Jump Statements; All Java Assignment Operators (Explained With Examples) Java Break Statement: Uses, Syntax, Examples, Label Break

  6. Java

    Example. =. Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A.

  7. Types of Assignment Operators in Java

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

  8. Assignment Operator in Java with Example

    The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example : a = 20; // variable a is reassigned with value 20. The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be ...

  9. Assignment Operators in Java with Examples

    Assignment Operator in Java. The following assignment operators are supported in Java. ... As you can see, In the above example, we are using assignment operator in if statement. We did a comparison of value 10 to an assignment operator which resulted in a 'true' output because the return of assignment operator is the value of left operand.

  10. Java Assignment Operators

    Java Assignment Operators. The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =. In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to ...

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

  12. 1. How to execute the assignment statement

    Questions 2 and 3 ask about the if-statement and if-else statement. These are the same as in just about any programming language, except for the syntax, of course. So use your knowledge of these statements in whatever programming language you know. 1. Write the algorithm for executing the Java assignment statement <variable>= <expression>; 2.

  13. Expressions, Statements, and Blocks (The Java™ Tutorials

    The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int.As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.

  14. What Is an Assignment Statement in Java?

    The assignment statement in Java involves using the assignment operator to set the value of a variable. The exact syntax depends on the type of variable receiving a value. Advertisement Variables Video of the Day In Java, variables are strongly typed. This means that when you declare a variable in a Java program, you must declare its type ...

  15. What does an assignment expression evaluate to in Java?

    The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c). So here, readLine() will be executed, and its return value stored in line. That stored value is then checked against null, and if it's null then the loop will terminate. edited Jun 3, 2021 at 14:55. Michael.

  16. Compound assignment operators in Java

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

  17. Java Operators

    Java Comparison Operators. Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If ...

  18. Java Operators: Arithmetic, Relational, Logical and more

    2. Java Assignment Operators. Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age. Let's see some more assignment operators available in Java.

  19. Compound Assignment Operator in Java

    Compound Assignment Operator. The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand.

  20. Assigning in Java?

    In Java, your variables can be split into two categories: Objects, and everything else (int, long, byte, etc). A primitive type (int, long, etc), holds whatever value you assign it. An object variable, by contrast, holds a reference to an object somewhere. So if you assign one object variable to another, you have copied the reference, both A ...

  21. Switch Case vs. If-Else in JavaScript Explained

    Switch case: Switch case allows conditions to be separated into different case blocks. The expression inside the switch statement decides what to execute. If-else statements: If-else statements nest conditions under if and else statements. The condition in the if statement determines whether to execute code under the if block or the else block.

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