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

Overview of Java

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

Basics of Java

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

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

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

Flow Control in Java

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

Java Assignment Operators with Examples

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

OOPS in Java

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

Access Modifiers in Java

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

Inheritance in Java

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

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

Constructors in Java

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

Methods in Java

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

Keywords in Java

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

Memory Allocation in Java

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

Classes of Java

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

Packages in Java

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

Exception Handling in Java

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

File Handling in Java

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

JDBC - Java Database Connectivity

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

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

Similar reads.

  • Java-Operators
  • 10 Ways to Use Slack for Effective Communication
  • 10 Ways to Use Google Docs for Collaborative Writing
  • NEET MDS 2024 Result: Toppers List, Category-wise Cutoff, and Important Dates
  • NDA Admit Card 2024 Live Updates: Download Your Hall Ticket Soon on upsc.gov.in!
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JB Header

Explore All Categories

  • Function interface has been defined with the generic types T & R , where T is the type of the input and R is the output type.
  • Method apply() is the primary abstract functional method of Function interface. It takes as input a parameter t of type T and gives an output object of type R .
  • Function<T, R> has two default methods. First default method compose() combines the function on which it is applied(lets call it the current function ) with another function, named before , in such a way that when the combined function is applied then first the before function is applied which converts the input type V to type T . And then the current function converts this object of type T to its output type R . Thus, the combined function obtained as a result of compose() applies both the functions, in the process converting type V to R .
  • The second default method is andThen() which combines the function on which it is applied( current function ) with another function, named after , in such a way that when the combined function is called then first the current function is applied which converts the input type T to type R . And then the after function is applied which converts from type R to V . Thus, the combined function obtained by using andThen() default method applies both functions internally, in the process converting type T to type V .
  • Function<T, R> also contains a static method identity() which is very simple as it returns as-is whatever is given to it as input. In the code above it takes as input a parameter t of Type T and returns back this t .
  • The lambda defining funcEmpToString is - (Employee e)-> {return e.getName();} . It takes as input an Employee object and returns his\her name, which is a String value, as output.
  • The list of employees is passed to method convertEmpListToNamesList() along with the Function object funcEmpToString ;
  • The method convertEmpListToNamesList() iterates over all the employees in the employee list, applies the function funcEmpToString to each of the Employee objects, getting back the employee names in String format, which it puts in a employee name list and sends it back to the main() method.
  • On printing the employee name list we get the names of all the employees as required.
  • Function instance funcEmpToString maps\converts an Employee object to a String of his\her name.
  • Function instance initialFunction maps\converts a String to its initial or first letter.
  • Default method andThen() is used to combine initialFunction with funcEmpToString . What the combined method does is that it first maps an Employee to his\her name and then takes out the first letter from the name as a String value. This combined function is passed as Function parameter to convertEmpListToNamesList() method along with the employee list.
  • When the convertEmpListToNamesList() applies the combined function to each of the Employee objects, then the result is a String list first letters of names of each employee.
  • This is the required output i.e. T H E N D
  • Function instance funcEmpToString maps\converts an Employee object to a String value of his\her name.
  • Function instance funcEmpFirstName maps\converts the name inside an Employee object to the first name using the substring method of String .
  • Default method compose() is used to combine funcEmpFirstName with funcEmpToStringString . What the combined method does is that it first converts the name of an Employee into just his\her first name returning the same Employee object back with the changed value of name . It then converts\maps the Employee object to just its name as a String .This combined function is passed as Function<Employee, String> parameter to convertEmpListToNamesList() method along with the employee list.
  • When the convertEmpListToNamesList() applies the combined function to each of the Employee objects, then the result is the list of first names of each employee.
  • This is the required output i.e. Tom Harry Ethan Nancy Deborah
  • Employee list is passed to the method applyIdentityToEmpList() along with an instance of Function.identity() . The parameter of applyIdentityToEmpList() which takes Function.identity() value is nothing but Function<Employee, Employee> i.e. an equivalent of a Function which takes Employee as input and gives back (the same) Employee as output.
  • Method applyIdentityToEmpList() takes the input employee list, iterates through it, applies the identity() function to each employee in the list and returns back the list of employees obtained as a result of applying the identity() function.
  • As we now know, the identity function does nothing , it just returns back the object it receives as input. So, what we get back is the same employee list which we passed to the applyIdentityToEmpList() method! And the same i.e. original employee list is printed as output!!
  • This is how the static method Function.identity() works.

Click on a category to view all articles

  • Algorithms & DS in Java  (7)
  • Core Java  (24)
  • Design Patterns  (17)
  • Error Handling  (6)
  • General Java Programs  (9)
  • JPA  (6)
  • Java 8  (60)
  • Java 9 & beyond...  (4)
  • JavaScript and HTML  (2)
  • Node.js  (1)
  • Programming & Design Principles  (9)
  • Quick Coding Tips  (19)
  • Reviews  (1)

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

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

One of the most common operators that you'll encounter is the simple assignment operator " = ". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

This operator can also be used on objects to assign object references , as discussed in Creating Objects .

The Arithmetic Operators

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments . For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

The following program, UnaryDemo , tests the unary operators:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version ( ++result ) evaluates to the incremented value, whereas the postfix version ( result++ ) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo , illustrates the prefix/postfix unary increment operator:

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

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

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.

  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable 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. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

Java assignment operators are classified into two types: simple and compound .

The Simple assignment operator is the equals ( = ) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left.

Compound operators are comprised of both an arithmetic, bitwise, or shift operator in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * 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. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com

Example 1: Java Methods

In the above example, we have created a method named addNumbers() . The method takes two parameters a and b . Notice the line,

Here, we have called the method by passing two arguments num1 and num2 . Since the method is returning some value, we have stored the value in the result variable.

Note : The method is not static. Hence, we are calling the method using the object of the class.

  • Java Method Return Type

A Java method may or may not return a value to the function call. We use the return statement to return any value. For example,

Here, we are returning the variable sum . Since the return type of the function is int . The sum variable should be of int type. Otherwise, it will generate an error.

Example 2: Method Return Type

In the above program, we have created a method named square() . The method takes a number as its parameter and returns the square of the number.

Here, we have mentioned the return type of the method as int . Hence, the method should always return an integer value.

Java method returns a value to the method call

Note : If the method does not return any value, we use the void keyword as the return type of the method. For example,

Method Parameters in Java

A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters. For example,

If a method is created with parameters, we need to pass the corresponding values while calling the method. For example,

Example 3: Method Parameters

Here, the parameter of the method is int . Hence, if we pass any other data type instead of int , the compiler will throw an error. It is because Java is a strongly typed language.

Note : The argument 24 passed to the display2() method during the method call is called the actual argument.

The parameter num accepted by the method definition is known as a formal argument. We need to specify the type of formal arguments. And, the type of actual arguments and formal arguments should always match.

  • Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

  • print() is a method of java.io.PrintSteam . The print("...") method prints the string inside quotation marks.
  • sqrt() is a method of Math class. It returns the square root of a number.

Here's a working example:

Example 4: Java Standard Library Method

To learn more about standard library methods, visit Java Library Methods .

What are the advantages of using methods?

1. The main advantage is code reusability . We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".

Example 5: Java Method for Code Reusability

In the above program, we have created the method named getSquare() to calculate the square of a number. Here, the method is used to calculate the square of numbers less than 6 .

Hence, the same method is used again and again.

2. Methods make code more readable and easier to debug. Here, the getSquare() method keeps the code to compute the square in a block. Hence, makes it more readable.

Table of Contents

  • Calling a Java Method
  • Method Parameters
  • Advantages of Java Methods

Sorry about that.

Related Tutorials

Java Library

Java Tutorial

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

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions .

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses () . Java provides some pre-defined methods, such as System.out.println() , but you can also create your own methods to perform certain actions:

Create a method inside Main:

Example Explained

  • myMethod() is the name of the method
  • static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
  • void means that this method does not have a return value. You will learn more about return values later in this chapter

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon ;

In the following example, myMethod() is used to print a text (the action), when it is called:

Inside main , call the myMethod() method:

Try it Yourself »

A method can also be called multiple times:

In the next chapter, Method Parameters , you will learn how to pass data (parameters) into a method.

Test Yourself With Exercises

Insert the missing part to call myMethod from main .

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.

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

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Java Basics
  • Java Tutorial
  • Java HelloWorld Program
  • Java Program Structure
  • Java Datatypes
  • Java Variable Types
  • Java Access Modifiers
  • Java Operators
  • Java Decision Making
  • Print array
  • Initialize array
  • Array of integers
  • Array of strings
  • Array of objects
  • Array of arrays
  • Iterate over array
  • Array For loop
  • Array while loop
  • Append element to array
  • Check if array is empty
  • Array average
  • Check if array contains
  • Array ForEach
  • Array - Find Index of Item
  • Concatenate arrays
  • Find smallest number in array
  • Find largest number in array
  • Array reverse
  • Classes and Objects
  • Inheritance
  • Polymorphism
  • Method Overloading
  • Method Overriding/
  • Abstraction
  • Abstract methods and classes
  • Encapsulation
  • Print string
  • Read string from console
  • Create string from Char array
  • Create string from Byte array
  • Concatenate two strings
  • Get index of the first Occurrence of substring
  • Get index of nth occurrence of substring
  • Check if two strings are equal
  • Check if string ends with specific suffix
  • Check if string starts with specific prefix
  • Check if string is blank
  • Check if string is empty
  • Check if string contains search substring
  • Validate if string is a Phone Number
  • Character Level
  • Get character at specific index in string
  • Get first character in string
  • Get last character from string
  • Transformations
  • Replace first occurrence of string
  • Replace all occurrences of a string
  • Join strings
  • Join strings in string array
  • Join strings in ArrayList
  • Reverse a string
  • Trim string
  • Split string
  • Remove whitespaces in string
  • Replace multiple spaces with single space
  • Comparisons
  • Compare strings lexicographically
  • Compare String and CharSequence
  • Compare String and StringBuffer
  • Java Exception Handling StringIndexOutOfBoundsException
  • Convert string to int
  • Convert string to float
  • Convert string to double
  • Convert string to long
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Convert int to double
  • Convert int to long
  • Convert int to char
  • Convert float to string
  • Convert float to int
  • Convert float to double
  • Convert float to long
  • Convert long to string
  • Convert long to float
  • Convert long to double
  • Convert long to int
  • Convert double to string
  • Convert double to float
  • Convert double to int
  • Convert double to long
  • Convert char to int
  • Convert boolean to string
  • Create a file
  • Read file as string
  • Write string to file
  • Delete File
  • Rename File
  • Download File from URL
  • Replace a String in File
  • Filter list of files or directories
  • Check if file is readable
  • Check if file is writable
  • Check if file is executable
  • Read contents of a file line by line using BufferedReader
  • Read contents of a File line by line using Stream
  • Check if n is positive or negative
  • Read integer from console
  • Add two integers
  • Count digits in number
  • Largest of three numbers
  • Smallest of three numbers
  • Even numbers
  • Odd numbers
  • Reverse a number
  • Prime Number
  • Print All Prime Numbers
  • Factors of a Number
  • Check Palindrome number
  • Check Palindrome string
  • Swap two numbers
  • Even or Odd number
  • Java Classes
  • ArrayList add()
  • ArrayList addAll()
  • ArrayList clear()
  • ArrayList clone()
  • ArrayList contains()
  • ArrayList ensureCapacity()
  • ArrayList forEach()
  • ArrayList get()
  • ArrayList indexOf()
  • ArrayList isEmpty()
  • ArrayList iterator()
  • ArrayList lastIndexOf()
  • ArrayList listIterator()
  • ArrayList remove()
  • ArrayList removeAll()
  • ArrayList removeIf()
  • ArrayList removeRange()
  • ArrayList retainAll()
  • ArrayList set()
  • ArrayList size()
  • ArrayList spliterator()
  • ArrayList subList()
  • ArrayList toArray()
  • ArrayList trimToSize()
  • HashMap clear()
  • HashMap clone()
  • HashMap compute()
  • HashMap computeIfAbsent()
  • HashMap computeIfPresent()
  • HashMap containsKey()
  • HashMap containsValue()
  • HashMap entrySet()
  • HashMap get()
  • HashMap isEmpty()
  • HashMap keySet()
  • HashMap merge()
  • HashMap put()
  • HashMap putAll()
  • HashMap remove()
  • HashMap size()
  • HashMap values()
  • HashSet add()
  • HashSet clear()
  • HashSet clone()
  • HashSet contains()
  • HashSet isEmpty()
  • HashSet iterator()
  • HashSet remove()
  • HashSet size()
  • HashSet spliterator()
  • Integer bitCount()
  • Integer byteValue()
  • Integer compare()
  • Integer compareTo()
  • Integer compareUnsigned()
  • Integer decode()
  • Integer divideUnsigned()
  • Integer doubleValue()
  • Integer equals()
  • Integer floatValue()
  • Integer getInteger()
  • Integer hashCode()
  • Integer highestOneBit()
  • Integer intValue()
  • Integer longValue()
  • Integer lowestOneBit()
  • Integer max()
  • Integer min()
  • Integer numberOfLeadingZeros()
  • Integer numberOfTrailingZeros()
  • Integer parseInt()
  • Integer parseUnsignedInt()
  • Integer remainderUnsigned()
  • Integer reverse()
  • Integer reverseBytes()
  • Integer rotateLeft()
  • Integer rotateRight()
  • Integer shortValue()
  • Integer signum()
  • Integer sum()
  • Integer toBinaryString()
  • Integer toHexString()
  • Integer toOctalString()
  • Integer toString()
  • Integer toUnsignedLong()
  • Integer toUnsignedString()
  • Integer valueOf()
  • StringBuilder append()
  • StringBuilder appendCodePoint()
  • StringBuilder capacity()
  • StringBuilder charAt()
  • StringBuilder chars()
  • StringBuilder codePointAt()
  • StringBuilder codePointBefore()
  • StringBuilder codePointCount()
  • StringBuilder codePoints()
  • StringBuilder delete()
  • StringBuilder deleteCharAt()
  • StringBuilder ensureCapacity()
  • StringBuilder getChars()
  • StringBuilder indexOf()
  • StringBuilder insert()
  • StringBuilder lastIndexOf()
  • StringBuilder length()
  • StringBuilder offsetByCodePoints()
  • StringBuilder replace()
  • StringBuilder reverse()
  • StringBuilder setCharAt()
  • StringBuilder setLength()
  • StringBuilder subSequence()
  • StringBuilder substring()
  • StringBuilder toString()
  • StringBuilder trimToSize()
  • Arrays.asList()
  • Arrays.binarySearch()
  • Arrays.copyOf()
  • Arrays.copyOfRange()
  • Arrays.deepEquals()
  • Arrays.deepToString()
  • Arrays.equals()
  • Arrays.fill()
  • Arrays.hashCode()
  • Arrays.sort()
  • Arrays.toString()
  • Random doubles()
  • Random ints()
  • Random longs()
  • Random next()
  • Random nextBoolean()
  • Random nextBytes()
  • Random nextDouble()
  • Random nextFloat()
  • Random nextGaussian()
  • Random nextInt()
  • Random nextLong()
  • Random setSeed()
  • Math random
  • Math signum
  • Math toDegrees
  • Math toRadians
  • Java Date & Time
  • ❯ Java Tutorial

Java Subtraction Assignment (-=) Operator

Java subtraction assignment.

In Java, Subtraction Assignment Operator is used to find the difference of the value (right operand) from this variable (left operand) and assign the result back to this variable (left operand). In this tutorial, we will learn how to use Subtraction Assignment operator in Java, with examples.

The syntax to subtract a value of 2 from variable x and assign the result to x using Subtraction Assignment Operator is

In the following example, we take a variable x with an initial value of 5 , subtract a value of 2 from x and assign the result to x , using Subtraction Assignment Operator.

In this Java Tutorial , we learned about Subtraction Assignment Operator in Java, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

IMAGES

  1. The Assignment Operator in Java

    java function assignment

  2. Java's main function explained with examples

    java function assignment

  3. Functional Programming in Java with Examples

    java function assignment

  4. Java Augmented Assignment Operators

    java function assignment

  5. Java Assignment Operators

    java function assignment

  6. How to call a function in Java

    java function assignment

VIDEO

  1. Assignment operators in java

  2. #20. Assignment Operators in Java

  3. Java Program to Find the Largest Among Three Numbers using In-built Function #java #interview

  4. Speaking For Transactional Function Assignment / Campus Sales

  5. Core

  6. Call By Value || JAVA || #java #video #viral

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. Function (Java Platform SE 8 )

    Java™ Platform Standard Ed. 8. Prev Class; Next Class; Frames; ... Interface Function<T,R> Type Parameters: T - the type of the input to the function R - the type of the result of the function All Known Subinterfaces: UnaryOperator<T> Functional Interface: This is a functional interface and can therefore be used as the assignment target for a ...

  3. Java 8 java.util.function.Function Tutorial with Examples

    What is java.util.function.Function Function<T, R> is an in-built functional interface introduced in Java 8 in the java.util.function package. The primary purpose for which Function<T, R> has been created is for mapping scenarios i.e when an object of a type is taken as input and it is converted (or mapped) to another type.

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

    This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators. The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics.

  5. Lambda Expressions and Functional Interfaces: Tips and Best ...

    2. Prefer Standard Functional Interfaces. Functional interfaces, which are gathered in the java.util.function package, satisfy most developers' needs in providing target types for lambda expressions and method references. Each of these interfaces is general and abstract, making them easy to adapt to almost any lambda expression.

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

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

  8. Java Assignment Operators

    Java assignment operators are classified into two types: simple and compound. The Simple assignment operator is the equals ( =) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...

  9. Java Methods (With Examples)

    Declaring a Java Method. The syntax to declare a method is: returnType methodName() { // method body } Here, returnType - It specifies what type of value a method returns For example if a method has an int return type then it returns an integer value. If the method does not return a value, its return type is void.; methodName - It is an identifier that is used to refer to the particular method ...

  10. Types of Assignment Operators in Java

    Types of Assignment Operators in Java. Java is a popular programming language that software developers use to construct a wide range of applications. It is a simple, robust, and platform-independent object-oriented language. There are various types of assignment operators in Java, each with its own function.

  11. Java Methods

    Example Explained. myMethod() is the name of the method static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial. void means that this method does not have a return value. You will learn more about return values later in this chapter

  12. java

    Your assignment is the last thing that happens in that line of code. The execution order is, first execute the function call to setContentView () and this method returns a ViewDataBinding. Then the second step is using the returned ViewDataBinding to assign to your binding variable. @Zorgan binding = DataBindingUtil.setContentView(this, R ...

  13. Java Method exercises and solution

    Write a Java method to display the factors of 3 in a given integer. Expected Output: Input an integer (positive/negative): 81 Factors of 3 of the said integer: 81 = 3 * 3 * 3 * 3 * 1. Click me to see the solution. 22. Write a Java method to check whether every digit of a given integer is even.

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

  15. confused with return value of assignment operation in java

    4. You've got it right. The operator precedence rules make sure that first the == operator is evaluated. That's b1==false, yielding true. After that, the assigned is executed, setting b2 to true. Finally, the assignment operator returns the value as b2, which is evaluated by the if statement. Java usually evaluates the terms from the left to ...

  16. What is += Addition Assignment Operator in Java?

    It's the Addition assignment operator. Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

  17. Definite Assignment in Java

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

  18. Java programming Exercises, Practice, Solution

    Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking the solution. Hope, these exercises help you to improve your Java ...

  19. language agnostic

    The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next(). It's already been mentioned that you can assign multiple variables in one step. x = y = z = 3; This sort of thing is the most common use, but creative programmers will always come up ...

  20. assign

    Java does not allow returning multiple values. Python allows this: def foo(): return 1, 2, 3. a, b, c = foo() The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable: Wrapper wrapper = WrapperGenrator.generateWrapper(); You can not assign to a tuple on the LHS as you can in Python.

  21. Java Subtraction Assignment (-=) Operator

    The syntax to subtract a value of 2 from variable x and assign the result to x using Subtraction Assignment Operator is. x -= 2 Example. In the following example, we take a variable x with an initial value of 5, subtract a value of 2 from x and assign the result to x, using Subtraction Assignment Operator. Main.java