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 Math sqrt()

Java Math acos()

Java Math atan()

Java Math tan()

A method is a block of code that performs a specific task.

Suppose you need to create a program to create a circle and color it. You can create two methods to solve this problem:

  • a method to draw the circle
  • a method to color the circle

Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.

In Java, there are two types of methods:

  • User-defined Methods : We can create our own method based on our requirements.
  • Standard Library Methods : These are built-in methods in Java that are available to use.

Let's first learn about user-defined methods.

  • Declaring a Java Method

The syntax to declare a method is:

  • 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 in a program.
  • method body - It includes the programming statements that are used to perform some tasks. The method body is enclosed inside the curly braces { } .

For example,

In the above example, the name of the method is adddNumbers() . And, the return type is int . We will learn more about return types later in this tutorial.

This is the simple syntax of declaring a method. However, the complete syntax of declaring a method is

  • modifier - It defines access types whether the method is public, private, and so on. To learn more, visit Java Access Specifier .
  • static - If we use the static keyword, it can be accessed without creating objects. For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.
  • parameter1/parameter2 - These are values passed to a method. We can pass any number of arguments to a method.

Calling a Method in Java

In the above example, we have declared a method named addNumbers() . Now, to use the method, we need to call it.

Here's is how we can call the addNumbers() method.

Call a method in Java using the name the method followed by a parenthesis

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

Methods in Java – Explained with Code Examples

Methods are essential for organizing Java projects, encouraging code reuse, and improving overall code structure.

In this article, we will look at what Java methods are and how they work, including their syntax, types, and examples.

Here's what we'll cover:

What are java methods.

  • Types of Access Specifiers in Java – Public ( public ) – Private ( private ) – Protected ( protected ) – Default ( Package-Private )
  • Types of Methods – Pre-defined vs. User-defined – Based on functionality

In Java, a method is a set of statements that perform a certain action and are declared within a class.

Here's the fundamental syntax for a Java method:

Let's break down the components:

  • accessSpecifier : defines the visibility or accessibility of classes, methods, and fields within a program.
  • returnType : the data type of the value that the method returns. If the method does not return any value, the void keyword is used.
  • methodName : the name of the method, following Java naming conventions.
  • parameter : input value that the method accepts. These are optional, and a method can have zero or more parameters. Each parameter is declared with its data type and a name.
  • method body : the set of statements enclosed in curly braces {} that define the task the method performs.
  • return statement : if the method has a return type other than void , it must include a return statement followed by the value to be returned.

Here's an example of a simple Java method:

In this example, the addNumbers method takes two integers as parameters ( a and b ), calculates their sum, and returns the result. The main method then calls this method and prints the result.

Compile the Java code using the terminal, using the javac command:

Screenshot-from-2024-02-28-09-27-12

Methods facilitate code reusability by encapsulating functionality in a single block. You can call that block from different parts of your program, avoiding code duplication and promoting maintainability.

Types of Access Specifiers in Java

Access specifiers control the visibility and accessibility of class members (fields, methods, and nested classes).

There are typically four main types of access specifiers: public, private, protected, and default. They dictate where and how these members can be accessed, promoting encapsulation and modularity.

Public ( public )

This grants access to the member from anywhere in your program, regardless of package or class. It's suitable for widely used components like utility functions or constants.

In this example:

  • The MyClass class is declared with the public modifier, making it accessible from any other class.
  • The publicField is a public field that can be accessed from outside the class.
  • The publicMethod() is a public method that can be called from outside the class.
  • The main method is the entry point of the program, where an object of MyClass is created, and the public field and method are accessed.

Private ( private )

This confines access to the member within the class where it's declared. It protects sensitive data and enforces encapsulation.

  • The MyClass class has a privateField and a privateMethod , both marked with the private modifier.
  • The accessPrivateMembers() method is a public method that can be called from outside the class. It provides access to the private field and calls the private method.

Protected ( protected )

The protected access specifier is used to make members (fields and methods) accessible within the same package or by subclasses, regardless of the package. They are not accessible from unrelated classes. It facilitates inheritance while controlling access to specific members in subclasses.

  • The Animal class has a protected field ( species ) and a protected method ( makeSound ).
  • The Dog class is a subclass of Animal , and it can access the protected members from the superclass.
  • The displayInfo() method in the Dog class accesses the protected field and calls the protected method.

Screenshot-from-2024-02-28-10-05-27

With the protected access specifier, members are accessible within the same package and by subclasses, promoting a certain level of visibility and inheritance while still maintaining encapsulation.

Default ( Package-Private )

If no access specifier is used, the default access level is package-private . Members with default access are accessible within the same package, but not outside it. It's often used for utility classes or helper methods within a specific module.

  • The Animal class does not have any access modifier specified, making it default (package-private). It has a package-private field species and a package-private method makeSound .
  • The Dog class is in the same package as Animal , so it can access the default (package-private) members of the Animal class.
  • The Main class runs the program by creating an object of Dog and calling its displayInfo method.

When you run this program, it should output the species and the sound of the animal.

How to Choose the Right Access Specifier

  • Public: Use for widely used components, interfaces, and base classes.
  • Private: Use for internal implementation details and sensitive data protection.
  • Default: Use for helper methods or components specific to a package.
  • Protected: Use for shared functionality among subclasses, while restricting access from outside the inheritance hierarchy.

Types of Methods

In Java, methods can be categorized in two main ways:

1. Predefined vs. User-defined:

Predefined methods: These methods are already defined in the Java Class Library and can be used directly without any declaration.

Examples include System.out.println() for printing to the console and Math.max() for finding the maximum of two numbers.

User-defined methods: These are methods that you write yourself to perform specific tasks within your program. They are defined within classes and are typically used to encapsulate functionality and improve code reusability.

  • add is a user-defined method because it's created by the user (programmer).
  • The method takes two parameters ( num1 and num2 ) and returns their sum.
  • The main method calls the add method with specific values, demonstrating the customized functionality provided by the user.

2. Based on functionality:

Within user-defined methods, there are several other classifications based on their characteristics:

Instance Methods:

Associated with an instance of a class. They can access instance variables and are called on an object of the class.

Here are some key characteristics of instance methods:

Access to Instance Variables:

  • Instance methods have access to instance variables (also known as fields or properties) of the class.
  • They can manipulate the state of the object they belong to.

Use of this Keyword:

  • Inside an instance method, the this keyword refers to the current instance of the class. It's often used to differentiate between instance variables and parameters with the same name.

Non-static Context:

  • Instance methods are called in the context of an object. They can't be called without creating an instance of the class.

Declaration and Invocation:

  • Instance methods are declared without the static keyword.
  • They are invoked on an instance of the class using the dot ( . ) notation.

Here's a simple example in Java to illustrate instance methods:

  • bark and ageOneYear are instance methods of the Dog class.
  • They are invoked on instances of the Dog class ( myDog and anotherDog ).
  • These methods can access and manipulate the instance variables ( name and age ) of the respective objects.

Instance methods are powerful because they allow you to encapsulate behavior related to an object's state and provide a way to interact with and modify that state.

Static Methods:

A static method belongs to the class rather than an instance of the class. This means you can call a static method without creating an instance (object) of the class. It's declared using the static keyword.

Static methods are commonly used for utility functions that don't depend on the state of an object. For example, methods for mathematical calculations, string manipulations, and so on.

Abstract Methods:

These methods are declared but not implemented in a class. They are meant to be overridden by subclasses, providing a blueprint for specific functionality that must be implemented in each subclass.

Abstract methods are useful when you want to define a template in a base class or interface, leaving the specific implementation to the subclasses. Abstract methods define a contract that the subclasses must follow.

Other method types: Additionally, there are less common types like constructors used for object initialization, accessor methods (getters) for retrieving object data, and mutator methods (setters) for modifying object data.

In this article, we will look at Java methods, including their syntax, types, and recommended practices.

Happy Coding!

A curious full-stack web developer. I love solving problems using software development and representing Data in a meaningful way. I like pushing myself and taking up new challenges.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

  • Java-Operators
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 10 Best Skillshare Alternatives in 2024
  • 10 Best Task Management Apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

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

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.

  • Skip to content
  • Accessibility Policy
  • Oracle blogs
  • Lorem ipsum dolor

Written by the Java community for Java and JVM developers

Quiz yourself: Interface methods and assignment compatibility in Java

method assignment java

What does it mean when a method has no modifiers—and a semicolon instead of a body?

More quiz questions available here

Given these four Java types

What is the result? Choose one.

Answer. This question investigates the accessibility of interface methods, interface implementation, and assignment compatibility. For this quiz question, look at each of the types that are declared and observe the key characteristics of the sample code.

Starting with the Command interface, notice that the type declaration has no modifier. This gives the interface package-level access, which means that it is accessible only within the bot package.

Next, the execute method is declared with no modifiers and has a semicolon in place of a body. This is valid, and if a method is declared this way in an interface, it will be implicitly public and abstract. From this you can determine that the interface is accessible and valid; therefore, option B is incorrect.

The Engine class is public, so it is accessible anywhere in the same module (or in the same JVM if the code is running without modules). The class declares a single method called run. This method is public, so it’s also accessible anywhere. The method is also static, so no instances of Engine need to be created to use the method. The method takes a single argument of type Command. The Engine class is in the same package as the Command interface, so it is accessible. The body of the run method simply calls the execute method of the Command argument. Command declares that the method, and the usage (the argument type sequence, which is empty), is valid. Because there is no reason for this code to fail, you can determine that option C is incorrect.

Notice that the AboutCommand class is in a different package from the Command interface. In addition, although it has the word Command in its name, this class does not contain the code implements Command . There are two immediate conclusions that can be drawn from this.

  • Because AboutCommand doesn’t reference Command, it’s not a problem that it’s in a different package.
  • While AboutCommand is not assignment-compatible with Command, this does not cause a problem here. (It does have consequences in other code, however.)

Also notice that the execute method in AboutCommand has package access and would not be a valid override of the execute method in Command. This isn’t a problem, however, since this method does not attempt such an override.

From these observations, you can see the AboutCommand class compiles successfully and option E is incorrect.

Finally, look at the Main class. It’s in the package bot, so it has access to the Command type. It imports the public type bot.command.AboutCommand , so it has access to that too. The main method has a valid signature line, and that signature is consistent with a program entry point. However, the body of the method has a problem. The argument type for the Engine.run method must be assignment-compatible with Command. However, as noted earlier, AboutCommand does not implement Command; therefore, it is not assignment-compatible with that type. That means the code Engine.run(ac); will fail to compile and option D is correct.

Because the Main class does not compile, option A must be incorrect.

Conclusion. The correct answer is option D.

Related quizzes

  • Quiz yourself: Using core functional interfaces: Predicate
  • Quiz yourself: Default methods
  • Quiz yourself: Abstract classes and default methods in Java
  • Quiz yourself: Java abstract classes and access modifiers for abstract methods

Simon Roberts

Simon Roberts joined Sun Microsystems in time to teach Sun’s first Java classes in the UK. He created the Sun Certified Java Programmer and Sun Certified Java Developer exams. He wrote several Java certification guides and is currently a freelance educator who publishes recorded and live video training through Pearson InformIT (available direct and through the O’Reilly Safari Books Online service). He remains involved with Oracle’s Java certification projects.

Mikalai Zaikin

Mikalai Zaikin is a lead Java developer at IBA Lithuania (part of worldwide IBA Group) and currently located in Vilnius. During his career, Zaikin has helped Oracle with development of Java certification exams, and he has been a technical reviewer of several Java certification books, including three editions of the famous Sun Certified Programmer for Java study guides by Kathy Sierra and Bert Bates.

Previous Post

Quiz yourself: Using the Java stream methods dropWhile and takeWhile

The performance implications of java reflection.

  • Analyst Reports
  • Cloud Economics
  • Corporate Responsibility
  • Diversity and Inclusion
  • Security Practices
  • What is Customer Service?
  • What is ERP?
  • What is Marketing Automation?
  • What is Procurement?
  • What is Talent Management?
  • What is VM?
  • Try Oracle Cloud Free Tier
  • Oracle Sustainability
  • Oracle COVID-19 Response
  • Oracle and SailGP
  • Oracle and Premier League
  • Oracle and Red Bull Racing Honda
  • US Sales 1.800.633.0738
  • How can we help?
  • Subscribe to Oracle Content
  • © 2024 Oracle
  • Privacy / Do Not Sell My Info

Javatpoint Logo

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

  • Blogs by Topic

The IntelliJ IDEA Blog

IntelliJ IDEA – the Leading Java and Kotlin IDE, by JetBrains

  • Twitter Twitter
  • Facebook Facebook
  • Youtube Youtube

Java 22 and IntelliJ IDEA

Mala Gupta

Java 22 is here, fully supported by IntelliJ IDEA 2024.1 , allowing you to use these features now!

Java 22 has something for all – from new developers to Java experts, features related to performance and security for big organizations to those who like working with bleeding edge technology, from additions to the Java language to improvements in the JVM platform, and more.

It is also great to see how all these Java features, release after release, work together to create more possibilities and have a bigger impact on how developers create their applications that address existing pain points, perform better and are more secure.

This blog post doesn’t include a comprehensive coverage of all the Java 22 features. If you are interested in that, I’d recommend you to check out this link to know everything about what’s new and changing in Java 22, including the bugs.

In this blog post, I’ll cover how IntelliJ IDEA helps you get started, up and running with some of the Java 22 features, such as, String Templates , Implicitly Declared Classes and Instance Main Methods , Statements before super() , and Unnamed variables and patterns .

Over the past month, I published separate blog posts to cover each of these topics in detail. If you are new to these topics, I’d highly recommend you check out those detailed blog posts (I’ve included their links in the relevant subsections in this blog post). In this blog post, I’ll cover some sections from those blog posts, especially how IntelliJ IDEA supports them. Let’s start by configuring IntelliJ IDEA to work with the Java 22 features.

IntelliJ IDEA Configuration

Java 22 support is available in IntelliJ IDEA 2024.1 Beta . The final version will release soon in March 2024.

In your Project Settings, set the SDK to Java 22. For the language level, select ‘22 (Preview) – Statements before super(), string templates (2nd preview etc.)’ on both the Project and Modules tab, as shown in the below settings screenshot:

method assignment java

If you do not have Java 22 downloaded to your system yet, don’t worry; IntelliJ IDEA has your back! You could use the same Project settings window, select ‘Download JDK’, after you click on the drop down next to SDK. You’ll see the below popup that would enable you to choose from a list of vendors (such as Oracle OpenJDK, GraalVM, Azul Zulu and others):

method assignment java

With the configuration under our belt, let’s get started with covering one of my favorite new features, that is, String Templates.

String Templates (Preview Language feature) The existing String concatenation options are difficult to work with and could be error prone; String templates offer a better alternative, that is, String interpolation with additional benefits such as validation, security and transformations via template processors.

Please check out my detailed blog post on this topic: String Templates in Java – why should you care? if you are new to this topic. It covers all the basics, including why you need String Templates, with multiple hands-on examples on built-in and user defined String processors.

IntelliJ IDEA can highlight code that could be replaced with String Templates Let’s assume you defined the following code to log a message that combines string literals and variable values using the concatenation operator:

The output from the preceding code could be an issue if you miss adding spaces in the String literals. The code isn’t quite easy to read or understand due to multiple opening and closing double quotes, that is, " and the + operator, and it would get worse if you add more literals, or variable values to it.

You could replace the preceding code with either StringBuilder.append() , String.format() or String.formatted() method or by using the class MessageFormat (as shown in my detailed blog post on this topic), but each of these methods have their own issues.

Don’t worry; IntelliJ IDEA could detect such code, suggest that you could replace it with String template, and do that for you, as shown below. It doesn’t matter if you are not even aware of the syntax of the String templates, IntelliJ IDEA has your back 🙂

Embedded expressions in String Templates and IntelliJ IDEA The syntax to embed a remplate expression (variable, expressible or a method call) is still new to what Java developers are used to and could be challenging to use without help. Don’t worry, IntelliJ IDEA has your back!

Each embedded expression must be enclosed within \{}. When you type \{, IntelliJ IDEA adds the closing ‘}’ for you. It also offers code completion to help you select a variable in scope, or any methods on it. If the code that you insert doesn’t compile, IntelliJ IDEA will highlight that too (as a compilation error), as shown in the following gif:

Using String Templates with Text Blocks Text blocks are quite helpful when working with string values that span multiple lines, such as, JSON, XML, HTML, SQL or other values that are usually processed by external environments. It is common for us Java developers to create such string values using a combination of string literals and variable values (variables, expressions or method calls).

The example below shows how IntelliJ IDEA could detect and create a text block using String templates for multiline string values that concatenates string literals with variable values. It also shows how IntelliJ IDEA provides code completion for variable names within such blocks. When you type in \{ , IntelliJ IDEA adds } . As you start typing the variable name countryName , it shows the available variables in that context:

Language injection and String Templates You could also inject a language or a reference in string values that spans single line or multiple lines, such as, a text block. By doing so, you get comprehensive coding assistance to edit the literal value. You could avail of this feature temporarily or permanently by using the @Language annotation, as shown below:

You can check out this link for detailed information on the benefits and usage of injecting language or reference in IntelliJ IDEA.

Predefined Template Processors With the String templates, you get access to predefined processors like the STR , FMT and RAW . I’d highly recommend you to check out my detailed blog post on String templates for multiple hands-on examples on it.

Custom Template Processor

Let’s work with a custom String template that isn’t covered in my previous blog post.

Imagine you’d like to create an instance of a record, say, WeatherData , that stores the details of the JSON we used in the previous section. Assume you define the following records to store this weather data represented by the JSON in the previous section:

You could create a method to return a custom String template that would process interpolated string, accept a class name ( WeatherData for this example) and return its instance:

Depending on the logic of your application, you might want to escape, delete or throw errors for the special characters that you encounter in the the JSON values interpolated via template expressions, as follows (the following method chooses to escape the special characters and include them as part of the JSON value):

You could initialize and use this custom JSON template processor as below. Note how elegant and concise the solution is with a combination of textblocks and String templates. The JSON is easy to read, write and understand (thanks to text blocks). The template expressions make it clear and obvious about the sections that are not constants and would be injected by the variables. At the end, the custom template processor WEATHER_JSON would ensure the resultant JSON is validated according to the logic you defined and returns an instance of WeatherData (doesn’t it sound magical?) :

Do not miss to check out my detailed blog post on this topic: String Templates in Java – why should you care? to discover how you could use the predefined String templates like FMT , to generate properly formatted receipts for, say, your neighborhood stationery store, or, say encode and decode combinations like :) or :( to emojis like 🙂 or ☹️. Does that sound fun to you?

Implicitly Declared Classes and Instance Main Methods (Preview language feature)

Introduced as a preview language feature in Java 21, this feature is in its second preview in Java 22.

It would revolutionize how new Java developers would get started learning Java. It simplifies the initial steps for students when they start learning basics, such as variable assignment, sequence, conditions and iteration. Students no longer need to declare an explicit class to develop their code, or write their main() method using this signature – public static void main(String []) . With this feature, classes could be declared implicitly and the main() method can be created with a shorter list of keywords.

If you are new to this feature, I’d highly recommend you to check out my detailed blog post: ‘HelloWorld’ and ‘main()’ meet minimalistic on this feature. In this blog post, I’ll include a few of the sections from it.

Class ‘HelloWorld’ before and after Java 21

Before Java 21, you would need to define a class, say, HelloWorld , that defined a main() method with a specific list of keywords, to print any text, say, ‘Hello World’ to the console, as follows:

With Java 21, this initial step has been shortened. You can define a source code file, say, HelloWorld.java, with the following code, to print a message to the console (it doesn’t need to define a class; it has a shorter signature for method main() ):

The preceding code is simpler than what was required earlier. Let’s see how this change could help you focus on what you need, rather than what you don’t.

Compiling and executing your code

Once you are done writing your code, the next step is to execute it.

On the command prompt, you could use the javac and java commands to compile and execute your code. Assuming you have defined your code in a source code file HelloWorld.java, you could use the following commands to run and execute it:

Since Java 11, it is possible to skip the compilation process for code defined in a single source code file, so you could use just the second command (by specifying the name of the source code file, as follows):

However, since instance main methods and implicit classes is a preview language feature, you should add the flag --enable-preview with --source 22 with these commands, as follows:

Sooner or later, you might switch to using an IDE to write your code. If you wish to use IntelliJ IDEA for creating instance main methods, here’s a quick list of steps to follow. Create a new Java project, select the build system as IntelliJ (so you could use Java compiler and runtime tools), create a new file, say, HelloWorld.java with your instance main method and set the properties to use Java 22, before you run your code, as shown in the following gif (It could save you from typing out the compilation/ execution commands on the command prompt each time you want to execute your code):

Are you wondering if it would be better to create a ‘Java class’ instead of a ‘File’ in the ‘src’ folder? The option of selecting a Java class would generate the body of a bare minimum class, say, public class HelloWorld { } . Since we are trying to avoid unnecessary keywords in the beginning, I recommended creating a new ‘File’ which wouldn’t include any code.

What else can main() do apart from printing messages to the console?

As included in my detailed post on this topic , I included multiple hand-on examples to show what you could achieve via just the main() method:

  • Example 1. Variable declarations, assignments and simple calculations
  • Example 2. Print patterns, such as, big letters using a specified character
  • Example 3. Animating multiline text – one word at a time
  • Example 4. Data structure problems
  • Example 5. Text based Hangman game

The idea to include multiple examples as listed above is to demonstrate the power of sequence, condition and iteration all of which can be included in the main() method, to build good programming foundations with problem solving skills. By using the run command or the icon to run and execute their code in IntelliJ IDEA, new programmers reduce another step when getting started.

Changing an implicit class to a regular class

When you are ready to level up and work with other concepts like user defined classes, you could also covert the implicit classes and code that we used in the previous examples, to regular classes, as shown below:

What happens when you create a source code file with method main(), but no class declaration?

Behind the scenes, the Java compiler creates an implicit top level class, with a no-argument constructor, so that these classes don’t need to be treated in a way that is different to the regular classes.

Here’s a gif that shows a decompiled class for you for the source code file AnimateText.java:

Variations of the main method in the implicit class

As we are aware, a method can be overloaded. Does that imply an implicit class can define multiple main methods? If yes, which one of them qualifies as the ‘main’ method? This is an interesting question. First of all, know that you can’t define a static and non-static main method with the same signature, that is, with the same method parameters. The following method are considered valid main() methods in an implicit class:

If there is no valid main method detected, IntelliJ IDEA could add one for you, as shown in the following gif:

Educators could use this feature to introduce other concepts to the students in an incremental way

If you are an educator, you could introduce your students to other commonly used programming practices, such as creating methods- that is delegating part of your code to another method and calling it from the main method. You could also talk about passing values vs. variables to these methods.

The following gif shows how to do it:

Statements before super() – a preview language feature

Typically, we create alternative solutions for tasks that are necessary, but not officially permitted. For instance, executing statements before super() in a derived class constructor was not officially allowed, even though it was important for, say, validating values being passed to the base class constructor. A popular workaround involved creating static methods to validate values and then calling these methods on the arguments of super() . Though this approach worked well, it could make the code look complicated. This is changing with Statements before super() , a preview language feature in Java 22.

By using this feature, you can opt for a more direct approach, that is, drop the workaround of creating static methods, and execute code that validates arguments, just before calling super() . Terms and conditions still apply, such as, not accessing instance members of a derived class before execution of super() completes.

An example – Validating values passed to super() in a derived class constructor Imagine you need to create a class, say, IndustryElement , that extends class Element , which is defined as follows:

The constructor of the class Element misses checking if the atomicNumber is in the range of 1-118 (all known elements have atomic numbers between 1 to 118). Often the source code of a base class is not accessible or open for modification. How would you validate the values passed to atomicNumber in the constructor of class IndustryElement ?

Until Java 21, no statements were allowed to execute before super() . Here’s one of the ways we developers found a workaround by defining and calling static methods (static methods belong to a class and not to instances and can be executed before any instance of a class exists):

Starting Java 22, you could inline the contents of your static method in the constructor for your derived class, as shown in the following gif:

Here’s the resultant code for your reference:

Where else would you use this feature? If you are new to this feature, I’d recommend that you check out my detailed blog post, Constructor Makeover in Java 22 , in which I’ve covered this feature in detail using the following examples:

  • Example 2 – base class constructor parameters that use annotations for validations
  • Example 3 – Transforming variable values received in a derived class constructor, before calling a base class constructor.
  • Example 4 – Executing statements before this() in constructor of Records
  • Example 5 – Executing statements before this() in Enum constructors
  • Example 6 – Executing statements before this() in classes

How does it work behind the scenes? The language syntax has been relaxed but it doesn’t change or impact the internal JVM instructions. There are no changes to the JVM instructions for this new feature because the order of execution of the constructors still remains unchanged – from base class to a derived class. Also, this feature still doesn’t allow you to use members of a derived class instance, until super() executes.

Let’s access and compare the instruction set of the constructor of class IndustryElement , before and after its modification – one that can execute statements before super() and the one that doesn’t. To do so, use the following command:

Here’s the instruction set for the constructor that doesn’t explicitly execute statements before super() and calls static methods to validate range of atomic number:

method assignment java

Here’s instruction set for the constructor that explicitly executes statements before super() to validate range of atomic number:

method assignment java

The most important point to note here is that in both the cases, the constructor of the base class, that is, Element is called, after the execution of all other statements. Essentially, it means, you are still doing the same thing, it is just packaged in a way that makes things easier for you.

I understand it is difficult to remember what each of these instruction codes means. Access the following link and search for the instruction code and following the above instructions set would be a breeze:

https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-6.html#jvms-6.5.aload_n

Can you execute ‘any’ statements before calling super()?

No. If the statements before super() try to access instance variables or execute methods of your derived class, your code won’t compile. For example, if you change the static checkRange() method to an instance method, your code won’t compile, as shown below:

Unnamed Variables and Patterns

Starting Java 22, using Unnamed Variables & Patterns you can mark unused local variables, patterns and pattern variables to be ignored, by replacing their names (or their types and names) with an underscore, that is, _ . Since such variables and patterns no longer have a name, they are referred to as Unnamed variables and patterns. Ignoring unused variables would reduce the time and energy anyone would need to understand a code snippet. In the future, this could prevent errors :-). This language feature doesn’t apply to instance or class variables.

Are you wondering if replacing unused variables with _ is always a good idea, or do they imply code smells and should you consider refactoring your codebase to remove them? Those are good questions to ask. If you are new to this topic, I’d recommend you to check out my detailed blog post: Drop the Baggage: Use ‘_’ for Unnamed Local Variables and Patterns in Java 22 to find out answer to this question.

Since this is not a preview language feature, set Language Level in your Project Settings to ‘22 – Unnamed variables and patterns’ on both the Project and Modules tab, as shown in the below settings screenshot:

method assignment java

A quick example

The following gif gives a sneak peek into how an unused local variable, connection, is detected by IntelliJ IDEA, and could be replaced with an underscore, that is, _ .

The modified code shown in the preceding gif makes it clear that the local variable defined in the try-with-resources statement is unused, making it concise and easier to understand.

Unused Patterns and Pattern variables in switch constructs

Imagine you defined a sealed interface, say, GeometricShape , and records to represent shapes, such as, Point , Line , Triangle , Square , as shown in the following code:

Now assume you need a method that accepts an instance of GeometricShape and returns its area. Since Point and a Line are considered one-dimensional shapes, they wouldn’t have an area. Following is one of the ways to define such method that calculates and returns area:

In the previous example, the patterns int x , int y , Point a and Point B (for case label Line) remain unused as detected by IntelliJ IDEA. These could be replaced by an _ . Also, since all the record components of the case Point remain unused, it could be replaced as Point _ . This could also allow us to merge the first and second case labels. All of these steps are shown in the following gif:

Here’s the modified code for your reference:

In the preceding example, you can’t delete the pattern variables even if they are unused. The code must include the cases when the instance passed to the method calcArea() is of type Point and Line , so that it could return 0 for them.

Unused Patterns or variables with nested records

This feature also comes in quite handy for nested records with multiple unused patterns or pattern variables, as demonstrated using the following example code:

In the preceding code, since the if condition in the method checkFirstNameAndCountryCodeAgain uses only two pattern variables, others could be replaced using _ ; it reduced the noise in the code too.

Where else can you use this feature? Checkout my detailed detailed blog post: Drop the Baggage: Use ‘_’ for Unnamed Local Variables and Patterns in Java 22 to learn more about other use cases where this feature can be used:

  • Requirements change, but you need side effects of constructs like an enhanced for-loop
  • Unused parameters in exception handlers; whose signature can’t be modified
  • Unused auto-closeable resources in try-with-resources statements

It isn’t advisable to use this feature without realising if an unused variable or pattern is a code smell or not. I used these examples to show that at times it might be better to refactor your code to get rid of the unused variable instead of just replacing it with an underscore, that is, _ .

  • Unused lambda parameter
  • Methods with multiple responsibilities

Preview Features

‘String Templates’, ‘Implicitly Declared Classes and Instance Main Methods’ and ‘Statements before super()’ are preview language features in Java 22. With Java’s new release cadence of six months, new language features are released as preview features. They may be reintroduced in later Java versions in the second or more preview, with or without changes. Once they are stable enough, they may be added to Java as a standard language feature.

Preview language features are complete but not permanent, which essentially means that these features are ready to be used by developers, although their finer details could change in future Java releases depending on developer feedback. Unlike an API, language features can’t be deprecated in the future. So, if you have feedback about any of the preview language features, feel free to share it on the JDK mailing list (free registration required).

Because of how these features work, IntelliJ IDEA is committed to only supporting preview features for the current JDK. Preview language features can change across Java versions, until they are dropped or added as a standard language feature. Code that uses a preview language feature from an older release of the Java SE Platform might not compile or run on a newer release.

In this blog post, I covered four Java 22 features – String Templates , Implicitly Declared Classes and Instance Main Methods , Statements before super() , and Unnamed variable and patterns .

String Templates is a great addition to Java. Apart from helping developers to work with strings that combine string constants and variables, they provide a layer of security. Custom String templates can be created with ease to accomplish multiple tasks, such as, to decipher letter combinations, either ignoring them or replacing them for added security.

Java language designers are reducing the ceremony that is required to write the first HelloWorld code for Java students, by introducing implicitly declared classes and instance main methods. New students can start with bare minimum main() method, such as, void main() and build strong programming foundation by polishing their skills with basics like sequence, selection and iteration.

In Java 22, the feature Statements before super() lets you execute code before calling super() in your derived class constructors, this() in your records or enums, so that you could validate the method parameters, or transform values, as required. This avoids creating workarounds like creating static methods and makes your code easier to read and understand. This feature doesn’t change how constructors would operate now vs. how they operated earlier – the JVM instructions remain the same.

Unnamed variables are local to a code construct, they don’t have a name, and they are represented by using an underscore, that is, _ . They can’t be passed to methods, or used in expressions. By replacing unused local variables in a code base with _ their intention is conveyed very clearly. It clearly communicates to anyone reading a code snippet that the variable is not used elsewhere. Until now, this intention could only be communicated via comments, which, unfortunately, all developers don’t write.

Happy Coding!

method assignment java

Subscribe to IntelliJ IDEA Blog updates

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

method assignment java

Getting Started with Databases in IntelliJ IDEA 

Have you ever wondered how IntelliJ IDEA handles databases? Well, today is the perfect opportunity to find out in our database tutorial on initial setups and first steps.   All of the features you’ll need when working with databases are available out of the box in IntelliJ IDEA Ultimate…

Irina Mariasova

Easy Hacks: How to Throw Java Exceptions

Exceptions in Java are used to indicate that an event occurred during the execution of a program and disrupted the normal flow of instructions. When an exception occurs, the Java runtime automatically stops the execution of the current method. It passes an exception object with information about the…

Maarten Balliauw

Drop the Baggage: Use ‘_’ for Unnamed Local Variables and Patterns in Java 22

How would you feel if you tried to understand a code snippet, only to realize that some of the variables you were trying to make sense of, were never used? This could be due to the programming syntax constraints, or an oversight as a result of changes to a codebase over time. Would you like it if th…

Mala Gupta

Build a Spring Boot App with AI Assistant

In this article, we’ll be building a small Java Spring Boot web application in IntelliJ IDEA with the help of JetBrains AI Assistant. If you’d like to follow along with this tutorial, you’ll need IntelliJ IDEA Ultimate, as well as an active subscription to AI Assistant or the free seven-day trial…

Marit van Dijk

  • United States
  • United Kingdom

Getting cozy with Java's new, softer side

New features like var, auto-compile, text blocks, record classes, and more are shifting java in subtle but powerful ways—toward a more flexible, dynamic future..

Matthew Tyson

Contributor, InfoWorld |

Getting cozy with Java's new, softer side

Hidden compilation

Auto-compile multiple source files, a better build toolchain, simple web server, nested text blocks, record classes, structured concurrency.

Java has made some big shifts over the past few years, as seemingly disparate forces converged to make the platform easier to use. New features like auto-compile and the var keyword lower the bar for using Java, for beginners and veterans alike. Let's take a look at what's cooking in this new, friendlier Java.

Perhaps the most astounding thing about modern Java, at least for long-timers, is the presence of var support. One of Java’s defining characteristics is that it is strongly typed, but var loosens that a bit. Within a method, you can now define a reference using var where the compiler will keep track of the type for you.

After much hand-wringing about the wisdom of introducing this feature, Java developers everywhere have simply adopted it like it is the most obvious thing ever. Didn’t Java always let us do this?

No, it didn’t!

This new feature almost feels like running a source file without compiling it, but what's happening under the hood is a little more complicated. The .java file is still compiled, but JEP 330 makes it so it’s all hidden from you. So you can now do:

The runner compiles the source in memory and executes the first main class it discovers.

JEP 330 is limited to a single source file but hang on, because here comes JEP 458.

JEP 458 joins up with JEP 330 to let developers run multiple source files with hidden compilation. When a Java source refers to another, the Java launcher will compile the dependency in memory, load it, and provide it. In short, you can run entire programs of interrelated source files, so long as they exist on disk together, without an explicit compile step.

Is it me, or is Java evolving into something more dynamic? This is very cool.

The introduction to JEP 458 says it aims to:

Enhance the java application launcher to be able to run a program supplied as multiple files of Java source code. This will make the transition from small programs to larger ones more gradual, enabling developers to choose whether and when to go to the trouble of configuring a build tool.

This says in plain language that Java is working toward simplifying the lives of developers through better builds. The JEP even goes so far as to say that it is "not a goal to ease the use of external library dependencies in source-code programs," although " that may be the subject of a future JEP " (italics mine).

I understand here that Java's developers are working on making the tooling easier to use, even down to the dependency level— finally!  Maven is still my go-to build tool for complex projects, as it has been for 15 years, but the tool shows serious signs of age. (A new archetype project in Maven picks Java 1.7 as its default!) Compared to NPM, Maven is downright clunky; a real impediment to getting projects off the ground quickly—especially for beginners who have to learn the build tool while also learning Java.

A platform-ordained dependency manager could be just the thing. When I look at JEP 330 and JEP 458 together, I see not piecemeal band-aids to tooling usability, but the thoughtful rolling out of an integrated, in-platform toolchain. What is emerging is a Java toolchain designed to make it easy to start a project and incrementally adopt more sophisticated tooling as needed.

I know, JShell has been around for a long time now, but let’s acknowledge how nice it is to have a REPL-style runner for Java. Remember to use JShell to try out new ideas on the fly.

One day we woke up and Java had a command-line web server . You can learn all about Java's Simple Web Server here .

The key takeaway is: if you are using Java 18 or higher, your JDK install now includes a dead simple and easy way to serve files. As a result, the Java platform is a bit more one-stop, integrated, and complete. I have previously used Python or Node for basic file-serving needs; now, I can just do it all in Java.

Another feature Java developers have long envied in other platforms was an easy way to handle big chunks of text in code. JEP 378 brings the text blocks we've been looking for:

I don't know about you, but that block gives me a sigh of relief.

Text blocks can also nest quote characters freely:

The product of JEP 395, the record keyword, lets you create a POJO (plain old Java object) without manually adding getters, setters, toString , equals , and hashcode methods as you normally would. When you use record , the platform adds all those niceties for you:

The new record classes also allow for a great deal of customization, so you can have as much or as little added as you want.

New and improved switch

With JEP 361, Java’s switch syntax became more powerful and easier to use. This happened in two ways: a cleaner syntax and the ability to use  switch as an expression and not just a statement.

The switch now makes it possible to take clunky old syntax like this:

And turn it into something like this:

Equally awesome, you can use it as an expression to variable assignment (which is often all we are after, anyway):

Now, concurrency is never going to be a happy-go-lucky area of coding. There is something inherently mind-bending about working with multiple threads. Nevertheless, structured concurrency gives you possibly the easiest way to handle concurrency in the known coding universe:

When combined with Java’s new virtual threads , structured concurrency is a superpower among languages. Now, you can easily use concurrency in Java, without spawning operating system threads, and without leaving normal programming constructs.

Platform developers are working on multiple fronts to lower the bar for developers working in Java. They are improving the day-to-day lives of working coders and making it easier to get started with Java and experiment with it.

These efforts are especially impactful in that peculiar pocket of the developer world that I’m going to call “prototyping,” otherwise known as “playing around.” The more we can do to reduce the distance between thinking about trying something and actually trying it, the better. 

It’s great to see Java in such good shape. I like the direction it's moving toward and the people leading those efforts.

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023
  • Software Development
  • Programming Languages

Matthew Tyson is a founder of Dark Horse Group, Inc. He believes in people-first technology. When not playing guitar, Matt explores the backcountry and the philosophical hinterlands. He has written for JavaWorld and InfoWorld since 2007.

Copyright © 2024 IDG Communications, Inc.

method assignment java

IMAGES

  1. Top 5 Java Main method Interview Questions with Answers

    method assignment java

  2. Java Method

    method assignment java

  3. An Introduction to Methods in Java with Examples

    method assignment java

  4. Different Ways to Call a Method in Java

    method assignment java

  5. How to Call a Method in Java (with Pictures)

    method assignment java

  6. How to Create a Method in Java

    method assignment java

VIDEO

  1. Assignment operators in java

  2. Demo qua Assignment Java 3

  3. 3. (Java Programming)

  4. 5) Method in java

  5. Java Methods

  6. BCSl 043 Solved Assignment Java Programming Lab 2023-24 Ignou

COMMENTS

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

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

  3. Java Methods

    The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. A Java method can perform some specific task without returning anything. Java Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python.

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

  5. Methods in Java

    Simple Java method. In this example, the addNumbers method takes two integers as parameters ( a and b ), calculates their sum, and returns the result. The main method then calls this method and prints the result. Compile the Java code using the terminal, using the javac command: Output.

  6. Java Object Assignment

    With the following line of code: you create a new Test object, and in the same time you create a Test reference named t1 to refer to it. You are actually creating another Test reference, and you assign it to refer to the same object that t1 refers to. So t1.i = 1; will affect t2.i for it is the same object after all.

  7. Java Methods

    Java Methods. Java methods are where you put the operations on data (variables) in your Java code. In other words, you group Java operations (code) inside Java methods. Java methods must be located inside a Java class . Java methods are similar to what is called functions or procedures in other programming languages (e.g. Pascal or JavaScript).

  8. Java Class Methods

    5) In order to use the Main class and its methods, we need to create an object of the Main Class. 6) Then, go to the main () method, which you know by now is a built-in Java method that runs your program (any code inside main is executed). 7) By using the new keyword we created an object with the name myCar. 8) Then, we call the fullThrottle ...

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

    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.

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

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

  12. Java Operators

    Java Methods Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion Java Classes ... 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:

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

  14. Method in Java

    Method in Java. In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. We can also easily modify code using methods.In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a method in Java.

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

  16. Quiz yourself: Interface methods and assignment compatibility in Java

    The AboutCommand class fails to compile. Answer. This question investigates the accessibility of interface methods, interface implementation, and assignment compatibility. For this quiz question, look at each of the types that are declared and observe the key characteristics of the sample code. Starting with the Command interface, notice that ...

  17. Types of Assignment Operators in Java

    There are various types of assignment operators in Java, each with its own function. In this section, we will look at Java's many types of assignment operators, how they function, and how they are utilized. Simple Assignment Operator (=) To assign a value to a variable, use the basic assignment operator (=).

  18. arrays

    Okay here's a Java assignment I've been having trouble with. I asked earlier about this and got some good comments and advice, but have since understood the assignment more clearly and the issue has changed a bit. So here's the assignment: *** Your task is to complete the program below by writing three methods (askInfo, copyInfo and setArray).

  19. Method Overriding in Java

    Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages. //Java Program to demonstrate the real scenario of Java Method Overriding. //where three classes are overriding the method of a parent class. //Creating a parent class. class Bank {.

  20. Java 22 and IntelliJ IDEA

    Java 22 is here, fully supported by IntelliJ IDEA 2024.1, allowing you to use these features now!. Java 22 has something for all - from new developers to Java experts, features related to performance and security for big organizations to those who like working with bleeding edge technology, from additions to the Java language to improvements in the JVM platform, and more.

  21. Getting cozy with Java's new, softer side

    The product of JEP 395, the record keyword, lets you create a POJO (plain old Java object) without manually adding getters, setters, toString, equals, and hashcode methods as you normally would.