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

The try-with-resources Statement

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable , can be used as a resource.

The following example reads the first line from a file. It uses an instance of FileReader and BufferedReader to read data from the file. FileReader and BufferedReader are resources that must be closed after the program is finished with it:

In this example, the resources declared in the try -with-resources statement are a FileReader and a BufferedReader . The declaration statements of these resources appear within parentheses immediately after the try keyword. The classes FileReader and BufferedReader , in Java SE 7 and later, implement the interface java.lang.AutoCloseable . Because the FileReader and BufferedReader instances are declared in a try -with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException ).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try -with-resources statement:

However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource's memory when it's finished with it. The program must also release the resoure back to the operating system, typically by calling the resource's close method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.

In this example, if the readLine method throws an exception, and the statement br.close() in the finally block throws an exception, then the FileReader has leaked. Therefore, use a try -with-resources statement instead of a finally block to close your program's resources.

If the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile , if exceptions are thrown from both the try block and the try -with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try -with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

In this example, the try -with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter . When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try -with-resources statement to automatically close a java.sql.Statement object:

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note : A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try -with-resources statement. In the example writeToFileZipFileContents , an exception can be thrown from the try block, and up to two exceptions can be thrown from the try -with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try -with-resources statement, then those exceptions thrown from the try -with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException , or no exception at all.

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

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

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Modernizing APIs : Share your thoughts on GraphQL, AI, microservices, automation , and more for our April report (+ enter a raffle for $250!).

DZone Research Report : A look at our developer audience, their tech stacks, and topics and tools they're exploring.

Getting Started With Large Language Models : A guide for both novices and seasoned practitioners to unlock the power of language models.

Managing API integrations : Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

  • Five Java Developer Must-Haves for Ultra-Fast Startup Solutions
  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • A Maven Story
  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • The Power of Generative AI: How It Is Revolutionizing Business Process Automation
  • Python Function Pipelines: Streamlining Data Processing
  • NIST AI Risk Management Framework: Developer’s Handbook
  • Implementation Best Practices: Microservice API With Spring Boot

How to Specify Multiple Resources in a Single Try-With-Resources Statement

The ability to specify multiple resources in a single try-with-resources statement is a feature introduced in java 7. but, it can be fraught with peril if not used carefully. read on to ensure you do this right every time..

Dustin Marx user avatar

Join the DZone community and get the full member experience.

One of the more useful features of Java 7 was the introduction of the try-with-resources statement , also known as the  Automatic Resource Management ( ARM ). The attractiveness of the try-with-resources statement lies in its promise to "ensure that each resource is closed at the end of the statement." A "resource" in this context is any class that implements AutoCloseable and its close() method and is instantiated inside the "try" clause of the try-with-resources statement .

The Java Language Specification (JLS) describes the try-with-resources statement in detail in Section 14.20.3  of Java SE 10 JLS in this case. The JLS states that the " try -with-resources statement is parameterized with local variables (known as resources ) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block."

The JLS clearly specifies that multiple resources can be defined in relation to a single try -with-resources statement, and it specifies how multiple resources are specified. Specifically, it indicates that try can be followed by a " ResourceSpecification " that is composed of a " ResourceList " that is composed of one or more " Resource 's." When there is more than a single declared resource, the multiple resources are delimited by a semicolon ( ; ). This specification of multiple resources in a semicolon-delimited list is important because any candidate resources not declared in this manner will not be supported (will not be closed automatically) by the try -with-resources statement.

The most likely source of errors when specifying multiple resources in a try -with-resources statement is "nesting" instantiations of "resources," instead of explicitly instantiating local variables of each of them separately with semicolons between each instantiation. The examples below will illustrate the difference.

Two ridiculous but illustrative classes are shown next. Each class implements an  AutoCloseable and can be used in conjunction with try -with-resources and will have its close() method called automatically when used correctly with the try -with-resources statement. They are named to reflect that the OuterResource can be instantiated with an instance of the InnerResource .

InnerResource.java

OuterResource.java

The two classes defined can now be used to demonstrate the difference between correctly declaring instances of each in the same try -with-resources statement in a semicolon-delimited list and incorrectly nesting instantiation of the inner resource within the constructor of the outer resource. The latter approach doesn't work as well as hoped, because the inner resource  —without a locally defined variable — is not treated as a "resource" in terms of invoking its AutoCloseable.close() method.

The next code listing demonstrates the incorrect approach for instantiating "resources" in the try -with-resources statement.

Incorrect Approach for Instantiating Resources in try -with-resources Statement

When the code above is executed, the output "  InnerResource created " is seen, but no output is ever presented related to the resource's closure. This is because the instance of InnerResource was instantiated within the call to the constructor of the OuterResource class and was never assigned to its own separate variable in the resource list of the try -with-resource statement. With a real resource, the implication of this is that the resource is not closed properly.

The next code listing demonstrates the correct approach for instantiating "resources" in the try -with-resources statement.

Correct Approach for Instantiating Resources in try -with-resources Statement

When the code above is executed, the output includes both  InnerResource created   and  InnerResource closed  , because the InnerResource instance was properly assigned to a variable within the try -with-resources statement. Therefore, its close() method is properly called, even when an exception occurs during its instantiation.

The try-with-resources statement section of the Java Tutorials includes examples of correctly specifying the resources in the try -with-resources as semicolon-delimited individual variable definitions. One example shows this correct approach with java.util.zip.ZipFile and java.io.BufferedWriter . Another example shows this correct approach with instances of java.sql.Statement and java.sql.ResultSet .

The introduction of try -with-resources in JDK 7 was a welcome addition to the language that it made it easier for Java developers to write resource-safe applications that were not as likely to leak or waste resources. However, when multiple resources are declared within a single try -with-resources statement, it's important to ensure that each resource is individually instantiated and assigned to its own variable declared within the try 's resource specifier list to ensure that each and every resource is properly closed. A quick way to check this is to ensure that for n,  AutoCloseable  is implementing resources specified in the try. There should be  n-1 semicolons, separating those instantiated resources.

Published at DZone with permission of Dustin Marx , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

Welcome to Java

Using try/catch blocks assignment.

Java Tutorial

Java methods, java classes, java file handling, java how to, 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.

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:

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:

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:

Java Bitwise Operators

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

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

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to 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.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types

Java Operators

  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

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

Java instanceof Operator

Java OOP (II)

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

Java OOP (III)

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

Java Reader/Writer

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

Additional Topics

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

Java Tutorials

Java Operator Precedence

Java Ternary Operator

Java Bitwise and Shift Operators

  • Java if...else Statement
  • Java while and do...while Loop

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.

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.

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 .

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.

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:

  • 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:

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

Sorry about that.

Related Tutorials

Java Tutorial

  • 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

Related Articles

  • Solve Coding Problems
  • Java Tutorial

Overview of Java

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

Basics of Java

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

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

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

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples

Java Assignment Operators with Examples

  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

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

Access Modifiers in Java

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

Inheritance in Java

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

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

Constructors in Java

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

Methods in Java

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

Keywords in Java

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

Memory Allocation in Java

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

Classes of Java

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

Packages in Java

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

Exception Handling in Java

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

File Handling in Java

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

JDBC - Java Database Connectivity

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

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

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 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

  • Java-Operators
  • nishkarshgandhi
  • chakka_saikiran

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Browse Course Material

Course info, instructors.

  • Adam Marcus

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Introduction to programming in java, assignments.

MIT Open Learning

Javatpoint Logo

Java Tutorial

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

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

IMAGES

  1. Java Try Catch Block with Example

    java try assignment

  2. Java 7 Try-With-Resources or Try With Resources Example Tutorial

    java try assignment

  3. How to Use try-catch Block in Java? [Try-Catch-Finally Explained]

    java try assignment

  4. The Assignment Operator in Java

    java try assignment

  5. Nested Try in Java

    java try assignment

  6. Java try-catch

    java try assignment

VIDEO

  1. Finally In Java21 main method got better 🥳

  2. Exception and Exception Handling in Java

  3. Java Assignment questions Continuation

  4. Assignment Operators in Java #java #coding #assignment #operators

  5. Demo Assignment Java 5

  6. 15 Comments

COMMENTS

  1. Java

    Support for try-with-resources — introduced in Java 7 — allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block. ... Although the writer variable is not explicitly final, it doesn't change after the first assignment.

  2. java

    Solutions. You have several options for fixing this. You must make sure that there can not be a branch that accesses choice unassigned. Therefore, you could assign it with a default value before entering the loop: int choice = -1; // Default value. Of course you would need to handle this special case then.

  3. Java try...catch (With Examples)

    The try-with-resources statement is a try statement that has one or more resource declarations. Its syntax is: try (resource declaration) { // use of the resource } catch (ExceptionType e1) { // catch block } The resource is an object to be closed at the end of the program. It must be declared and initialized in the try statement.

  4. The try-with-resources Statement (The Java™ Tutorials > Essential Java

    The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used ...

  5. Java Try Catch Block

    2. catch in Java. The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. catch. {. // statement (s) that handle an exception. // examples, closing a connection, closing. // file, exiting the process after writing.

  6. How to Specify Multiple Resources in a Single Try-With ...

    The try-with-resources statement section of the Java Tutorials includes examples of correctly specifying the resources in the try-with-resources as semicolon-delimited individual variable definitions.

  7. Java Exception Handling (With Examples)

    3. Java throw and throws keyword. The Java throw keyword is used to explicitly throw a single exception.. When we throw an exception, the flow of the program moves from the try block to the catch block.. Example: Exception handling using Java throw class Main { public static void divideByZero() { // throw an exception throw new ArithmeticException("Trying to divide by 0"); } public static void ...

  8. Java Exceptions

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  9. W3Schools Tryit Editor

    The W3Schools online code editor allows you to edit code and view the result in your browser

  10. Java Exception Handling: 20 Best Practices for Error-Free Code

    This post is another addition to the best practices series available in this blog. In this post, we cover some well-known and little-known practices that we must consider while handling exceptions in our next java programming assignment. 1. Inbuilt Exceptions in Java. Before we dive into deep concepts of exception-handling best practices, let ...

  11. Java try-catch

    Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception. The catch block must be used after the try block only.

  12. Java: Using try/catch blocks assignment

    Using try/catch blocks assignment; Using try/catch blocks assignment. Put the following code (as shown previously) into a file called FileOut.java, compile and run. Note what happens. Now modify the code to remove the code to remove the line with the try

  13. Java programming Exercises, Practice, Solution

    Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and ...

  14. Java Operators

    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: Example int x = 10; ... Try it && Logical and: Returns true if both statements are true:

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

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

  17. Assignments

    This section provides the assignments for the course, supporting files, and a special set of assignment files that can be annotated. Browse Course Material ... GravityCalculator.java 2 FooCorporation 3 Marathon Marathon.java 4 Library Book.java . Library.java . 5 Graphics! initial.png . SimpleDraw.java ...

  18. How to use try catch in lambda expression (JAVA)?

    In this case the try block have create a JSON Object with the input strings. But I must implement that, if the creation doesn't work, it should return an Optional.Empty() ... Most classes which descend from RuntimeException in Java SE are meant to indicate programmer errors. Examples would be: NullPointerException; IndexOutOfBoundsException;

  19. Types of Assignment Operators in Java

    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: In the above example, the variable x is assigned the value 10. Addition Assignment Operator (+=) To add a value to a variable and subsequently assign the new value to the same variable, use ...