search
HomeJavajavaTutorial[Java Getting Started Notes] Java Language Basics (3): Operators

Introduction

An operator is a special symbol. An operator is a specific symbol that operates one or more operands through certain operation rules and generates a result. The effective combination of an operator and operands is called an expression.

Operators in Java are mainly divided into the following categories:

Assignment operators

Arithmetic operators

Relational operators

Logical operators

Conditional operators (ternary operators)

Bitwise operators

Assignment operator

The assignment operator is used to assign a value to a variable or constant. The symbol of the assignment operator is "=".

Example

int a = 1;  //定义时直接赋值int b;int c;
b = 
c = 2;  //可以在一个语句内为多个变量赋值
int d = b + 3;   //变量运算后再赋值,先执行右边,再执行左边

Arithmetic operators

Java supports basic mathematical operations such as addition, subtraction, multiplication, division and remainder. They are the following:

[Java Getting Started Notes] Java Language Basics (3): Operators

Addition operator: +

double a = 1.1;double b = 1.2;double sum = a + b;
System.out.PRintln(sum); //Output 2.3

Subtraction operator: -

double a = 2.2;double b = 1.1;double sub = a - b;
System.out.println(sub); //Output 1.1

Multiplication operator: *

int a = 11;double b = 1.2;double multiply = a * b;
System.out.println(multiply); //Output 1.32

Division operator: /

The division operator is a bit special: if the operation Both values ​​​​are int, and the result obtained is also of type int. The decimal point will be removed directly and will not be rounded.

int a = 10; int b = 4; double c = a/b; System.out.println(c); //The original result of 10chu 4 is 2.5, but the result of dividing two int type numbers is an int type number. Although the result value is assigned to double,
          //But the output result becomes 2.0, which is equivalent to removing the decimal point when the operation is completed, and then converting it to 2.0double a2 = 5.2;double b2 = 3.1;double c2 = a2/b2; System.out.println(c2); //Operation on two double values, output result: 1.6774193548387097System.out.println(5 / 0.0); //The divisor is double type 0.0, and the output is negative infinity System.out.println(5 / 0); //If the divisor is 0, an error will be reported during runtime

Remainder operator: %

int a = 5;int b = 3;double c = 3.2;
System.out.println(a%b) ; //Output 2System.out.println(a%c); //1.7999999999999998System.out.println(0%5); //Output 0System.out.println(5%0); //An error will occur during operation

Find the negative: -

int i = -1;int i2 = -i;
System.out.println(i2); //Output 1

Self-increment: ++

int i = 1;
i++ ; //Equivalent to adding 1 to the value of i; System.out.println(i); //Output 2

The self-increasing symbol can be placed in front of the variable or behind the variable. Put it in front first Add 1 to the operand, and then perform the operation of the expression. Putting it after it will do the opposite.

int i1 = 1;int i2 = 1;int i3 = i1++; //At this time, the value of i3 is 1 and the value of i1 is 2; it first assigns the value of i1 to i3, and then adds 1 to i1 ;int i4 = ++i2; //At this time, the value of i4 is 2, and the value of i2 is also 2; it first adds 1 to the value of i2, and then assigns the value to i4;

Decrement: --

The function is similar to self-adding

int i1 = 1;int i2 = 1;int i3 = i1++; //At this time, the value of i3 is 1 and the value of i1 is 0; it first assigns the value of i1 to i3, then decrement i1 by 1; int i4 = ++i2; //At this time, the value of i4 is 0, and the value of i2 is also 0; it first decrements the value of i2 by 1, and then assigns the value to i4;

Relational operators (comparison operators)

Relational operators can test the relationship between two operands (but will not change the value of the operand). The result of the relational expression is boolean true/false:

[Java Getting Started Notes] Java Language Basics (3): Operators

System.out.println(4 == 4); //The result is trueSystem.out.println(4 != 3); //The result is trueSystem.out.println(true == false); //The result is false

Logical operators

Logical operators are used to operate boolean type variables or constants

[Java Getting Started Notes] Java Language Basics (3): Operators

See examples

System.out.println(!true); //The result is falseSystem.out.println (2 > 1 && 1 > 1); //The result is falseSystem.out.println(2 > 1 || 1 > 1); //The result is trueSystem.out.println(true ^ false); / /The result is true, XOR, which is equivalent to inverting the first previous value true, and then performing an "OR" operation

Let's take a look at the difference between | and ||

int a = 1; int b = 1;if(a == 1 | b++ > 1){
System.out.println(b); //The output value of b is 2, bitwise OR, although the result on the left side of the | symbol is true, it still Will execute the code to the right of the | symbol}

and change | to ||

int a = 1;int b = 1;if(a == 1 || b++ > 1){
System.out.println(b); //The output value of b is 1, and the result on the left side of the || symbol is true, the code to the right of the || symbol will no longer be executed}

Conditional operator (ternary operator)

Its general form is:

Expression 1 ? Expression 2 : Expression 3

Determine whether to execute expression 2 or expression 3 based on the result of expression 1. If the result of expression 1 is true, execute expression 2, otherwise execute expression 3;

Conditional operators can be substituted in some cases Small if...else statement.

String s = 1 > 2 ? "1 is greater than 2" : "1 is not greater than 2";
System.out.println(s); //Output 1 is not greater than 2

bit operator

bit operation Symbols are two data that participate in operations, and operations are performed based on binary bits. There are seven bitwise operators in Java: bitwise AND (&), bitwise OR (|), bitwise NOT (~), bitwise XOR (^), left shift operator (>), unsigned right shift operator (>>>).

For detailed introduction, please refer to the following article:

http://www.cnblogs.com/yezhenhan/archive/2012/06/20/2555849.html

Priority of operators

In many cases , an expression consists of multiple operators, and the priority determines the calculation order of the operators:

[Java Getting Started Notes] Java Language Basics (3): Operators

Although operators have priorities, an expression will be evaluated sequentially according to the priority of the expression operators, but In actual programming, if an expression is very long, it is not recommended to write it like this. Instead, it is written in several steps, because the readability is too poor when written together.

The above is [Java Introduction Notes] Java Language Basics (3): The content of operators. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)