> Java > java지도 시간 > 본문

Java의 할당 연산자

WBOY
풀어 주다: 2024-08-30 15:19:57
원래의
801명이 탐색했습니다.

Java 할당 연산자는 단순 할당 연산자와 복합 할당 연산자의 두 가지 범주로 분류됩니다. 이름에서 알 수 있듯이 할당 연산자는 작업과 관련된 변수에 값을 할당하는 데 사용됩니다. 단순 할당 연산자는 덧셈, 뺄셈, 곱셈, 나눗셈과 같은 단순하고 복잡하지 않은 연산을 처리합니다. 복합 할당 연산자는 ^, &, %, <>, >>, << 등과 같이 코드에 더 많은 논리 연산이 필요할 때 사용됩니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

할당 연산자는 일반적으로 두 가지 유형이 있습니다. 그들은:

  • 단순 할당 연산자
  • 복합 할당 연산자

단순 할당 연산자는 "=" 기호와 함께 사용되며 왼쪽은 피연산자로 구성되고 오른쪽은 값으로 구성됩니다. 오른쪽 값은 왼쪽에 정의된 데이터 유형과 동일해야 합니다.

복합 연산자는 = 연산자와 함께 +,-,*, /가 사용되는 곳에 사용됩니다.

할당 연산자 유형

다양한 작업 연산자가 있습니다. 할당은 할당 후 목표/목표 변수의 값을 가져옵니다.

단순 할당 연산자

먼저 Java 프로그램의 도움으로 Simple Assignment 연산자의 작동을 확인하고 살펴보겠습니다. 이 프로그램에는 숫자 1과 숫자 2에 두 개의 값을 할당한 다음 출력에 인쇄하여 해당 값이 숫자에 할당되었음을 표시하는 작업이 포함됩니다.

코드:

class AssignmentOperator
{
public static void main(String[] args)
{
int n1, n2;
// Assigning 5 to number1
n1 = 5;
System.out.println(n1);
// Assigning value of variable number2 to number1
n2 = n1;
System.out.println(n2);
}
}
로그인 후 복사

print 문을 실행하면 다음과 같은 결과가 출력됩니다. 앞서 초기화된 두 개의 숫자가 출력된 것을 확인할 수 있습니다. 두 숫자 모두 값 5로 초기화되었습니다.

출력:

Java의 할당 연산자

복합 할당 연산자

여기에서는 복합 할당 연산자의 작동 방식을 확인해 보겠습니다. 복합 할당 연산자 목록은 다음과 같습니다.

  • += 복합 추가 할당 연산자
  • -= 복합 뺄셈 대입 연산자
  • *= 복합 곱셈 대입 연산자
  • /= 복합 나눗셈 할당 연산자.

위에 언급된 네 가지 기본 복합 할당 연산자는 존재합니다. 다음과 같은 다른 복합 할당 연산자가 있습니다.

  • %= 복합 모듈로 할당 연산자.
  • &= 복합 비트 할당 연산자.
  • ^= 복합 비트 ^ 할당 연산자.
  • >>= 복합 오른쪽 시프트 할당 연산자.

  • >>>= 복합 오른쪽 시프트가 0 대입 연산자로 채워집니다.
  • <<= 복합 왼쪽 시프트 할당 연산자.

이 글에서는 처음 4개의 복합 할당 연산자를 다른 연산자와 함께 자세히 살펴보겠습니다. 복합 할당 연산자의 기본 장점은 Java 언어 프로그램 내에서 많은 코드를 절약한다는 것입니다.

1. 복합 추가 할당 연산자

이 연산자는 전체 루프에서 지속적으로 변수에 숫자를 추가하는 데 사용됩니다. 우리는 루프의 도움으로 첫 번째 i번째 자연수의 합을 구하는 프로그램을 볼 것입니다. for 루프에서는 복합 추가 연산자를 사용하겠습니다.

코드:

//Program to print the sum uptil ith natural number
import java.io.*;
public class Main
{
public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number upto which you want to find the sum");//Print statement
int i=Integer.parseInt(br.readLine());//Taking input from user
int sum=0;//Initializing sum=0
//Beginning of for loop
for (int j=1; j<i; j++)
{
sum+= j;//Compound assignment operator being used here
}//end of for loop
System.out.println("Sum of first " +i+ " natural numbers = " +sum);
}// end of main
}// end of class
로그인 후 복사

값을 10으로 입력하면, 즉 45와 같은 처음 10개의 자연수의 합을 구하는 것을 알 수 있습니다.

출력:

Java의 할당 연산자

2. 복합 빼기 할당 연산자

이 프로그램은 기존의 더 큰 숫자에서 숫자를 삭제하는 데 사용할 수 있습니다. 다음 프로그램에서는 더 큰 숫자 100에서 숫자를 삭제하는 방법을 살펴보겠습니다.

코드:

//Program to print the sum when certain numbers are subtracted
import java.io.*;
public class Subtract
{
public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number upto which you want to subtract from the sum");//Print statement
int i=Integer.parseInt(br.readLine());//Taking input from user
int sum = 100;//Initializing sum=0
//Beginning of for loop
for (int j=1; j<=i; j++)
{
sum-= j;//Compound assignment operator being used here
}//end of for loop
System.out.println("Result " +sum);
}// end of main
}// end of class
로그인 후 복사

샘플 코드를 보면 숫자 5가 입력되어 있고, 숫자 100에서 5까지의 합을 빼면 85라는 답이 나옵니다.

출력:

Java의 할당 연산자

3. 복합 곱셈 할당 연산자

이 프로그램은 사용자가 입력하는 특정 숫자까지 숫자를 곱하는 데 사용할 수 있습니다. for 루프 내에서 특정 숫자와 숫자의 곱셈을 인쇄하는 데 사용되는 프로그램을 볼 수 있습니다.

코드:

//Program to print the multiplication uptil ith natural number
import java.io.*;
public class Multiply
{
public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number upto which you want to print the multiplication");//Print statement
int i=Integer.parseInt(br.readLine());//Taking input from user
int prod=1;//Initializing prod=1
//Beginning of for loop
for (int j=1; j<=i; j++)
{
prod*= j;//Compound assignment operator being used here
}//end of for loop
System.out.println("Result " +prod);
}// end of main
}// end of class
로그인 후 복사

We enter the number as 5, and then we see that the result is the multiplication of the number with numbers below. In other words, this program shows the factorial of a number in simple terms. We see the output of the program in the below screen.

Output:

Java의 할당 연산자

4. Compound Division Assignment Operator

In this case, we are going to see the division of a number using the division operator. We won’t be using any kind of loop in this case, but we are going to see the numerator and the denominator. We will input the value of the numerator and divide it by 10 and produce the output to the user.

Code:

//Program to print the division of a number
import java.io.*;
public class Divide
{
public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the numerator");//Print statement
int i=Integer.parseInt(br.readLine());//Taking input from user
i/=10;// Compound Division assignment operator
System.out.println("Result " +i);
}// end of main
}// end of class
로그인 후 복사

In the program, we input 100 as a number, and we divide it by 10 using the Compound Division Assignment operator. We get the output finally as 10, as shown in the below screenshot.

Output:

Java의 할당 연산자

5. Compound Operators (Remaining Operators)

In the below program, we will see the working of the remaining operators present. The remaining operators are %, ^, &, >>, << and >>>The following is the code and output.

Code:

class CompoundAssignment
{
public static void main(String args[])
{
byte b2 = 127;
b2 %= 7;
byte b3 = 120;
b3 &= 40;
short s1 = 300;
s1 ^= 100;
byte b4 = 127;
b4 >>= 3;
short s2 = 100;
s2 <<= 3;
short s3 = 200;
s3 >>>= 4;
System.out.println("Value of b2= "+b2);
System.out.println("Value of b3= "+b3);
System.out.println("Value of b4= "+b4);
System.out.println("Value of s1= "+s1);
System.out.println("Value of s2= "+s2);
System.out.println("Value of s3= "+s3);
}
}
로그인 후 복사

In the output, we see the result of the compound assignment operations that were left. The output has been printed correspondingly.

Output:

Java의 할당 연산자

Conclusion – Assignment Operators in Java

This article sees two kinds of Assignment operators- Simple Assignment operators and Compound Assignment operators. We see the working with the help of coding examples. There are advantages as well as disadvantages of using Compound Assignment operators. Assignment operators are used in all other programming languages like C, C++, Python, and wherever value has to be assigned to a variable. The only constraint is that the value has to be of the same data type as the variable which is declared.

위 내용은 Java의 할당 연산자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!