>  기사  >  Java  >  자바의 변수

자바의 변수

WBOY
WBOY원래의
2024-08-30 15:10:381109검색

변수는 Java에서 정보를 저장하는 데 사용되는 기본 단위입니다. 변수 이름은 이러한 단위에 할당된 이름입니다. Java 코드에는 숫자 또는 문자열 값 형식의 정보가 필요할 수 있습니다. 코드의 여러 단계에서 동일한 값 세트가 필요할 수 있습니다. 여기서 변수가 등장합니다.

이러한 모든 필수 값은 해당 메모리 위치에 저장될 다양한 변수에 할당될 수 있습니다. 따라서 변수는 메모리 위치의 이름일 뿐입니다. 변수에 값을 저장하는 것이 코드의 모든 위치에서 값을 반복하는 것보다 더 효율적입니다. 또한 여러 위치에서 변경하는 것보다 변수 선언의 한 위치에서만 변경하면 충분하므로 필요한 값이 변경될 때 도움이 됩니다.

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

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

변수 선언

변수는 선언되기 전까지는 사용할 수 없으며, 선언 중에 할당하는 데이터 유형은 변수가 보유할 수 있는 값의 유형을 정의합니다. int, float, string, char, Boolean, long, double 등 다양한 데이터 유형을 변수에 할당할 수 있습니다.

Java에서 변수를 선언하는 일반적인 구문은 다음과 같습니다.

Ex: int a = 1;

어디,

  • int – 데이터 유형
  • a – 변수 이름
  • 1 – 변수 값

다음 다이어그램은 동일한 내용을 그림으로 표현한 것입니다.

자바의 변수

변수 초기화

변수에 기본값을 할당하는 것을 해당 변수의 초기화라고 합니다. 선언하는 동안과 필요에 따라 프로그램의 후반 단계에서 변수를 초기화할 수 있습니다. 예: 다음은 특정 데이터 유형과 관련하여 변수에 할당할 수 있는 값 중 일부입니다.

  •  int i; 나는=10;
  •  문자열 도시; city=”방갈로르”;
  •  문자 a; a='H';
  •  12월 부동; 12월=3.5;
  •  부울 값; 값=true;

변수의 종류

Java에는 세 가지 유형의 변수가 있습니다.

  • 지역변수
  • 인스턴스 변수
  • 정적변수

1. 지역변수

  • 특정 메서드나 블록, 생성자 내부에 선언된 변수입니다.
  • 선언 중에 저장되는 변수 값은 해당 메소드 범위 내에서만 유효하며 메소드가 종료되면 손실됩니다.
  • 동일한 변수 이름을 가진 로컬 변수는 충돌 없이 여러 메소드나 블록에서 선언될 수 있습니다.

예: 다음 예에서는 "num"과 "name"을 지역 변수로 간주합니다. 코드:

public class PatientDetails{
public void Patient()
{
// local variable num
//local variable name
int num = 1200;
string name = "Harish";
id = id + 1;
System.out.println("Patient Name is: " + name + " Patient Number is: " + num);
name = "Sudha";
System.out.println("Patient Name is: " + name + " Patient Number is: " + num);
}
public void DoctorDetails()
{
int num = 12000;
string name = "Vijay";
num = num +1;
System.out.println("Doctor Name is: " + name + " Doctor ID is: " + num);
name = "Suma";
System.out.println("Doctor Name is: " + name + " Doctor ID is: " + num);
}
public static void main(String args[])
{
PatientDetails pat = new PatientDetails();
pat. Patient();
pat.DoctorDetails();
}
}

출력:

환자 이름: Harish
환자 번호: 1200
환자 이름은: Sudha
환자 번호: 1201
의사 이름은: Vijay
의사 ID: 12000
의사 이름은: 수마
의사 ID: 12001

이는 두 가지 다른 메소드(예: Patient 및 DoctorDetails)에서 선언된 동일한 지역 변수 이름 "num" 및 "name"을 사용하여 여러 다른 값을 할당할 수 있음을 보여줍니다.

예:

동일한 지역 변수 “num”과 “name”은 메서드 외부에서 값을 표시하려고 하면 유효하지 않습니다.

코드:

public class PatientDetails{
public void Patient()
{
// local variable num
//local variable name
int id = 1200;
}
public static void main(String args[])
{
System.out.println("Patient Number is: " + num);
//printing local variable outside it's method
}
}

출력:

Java 코드의 컴파일 오류:-
prog.java:12: 오류: 기호를 찾을 수 없습니다
System.out.println(“환자 번호: ” + num);
^
기호: 변수 번호
위치: 환자 세부정보 클래스
오류 1개

2. 인스턴스 변수

  • 인스턴스 변수는 메소드가 아닌 클래스 내부에 선언되는 변수입니다.
  • 객체가 생성될 때 생성되며, 객체가 소멸되면 그 가치는 상실됩니다.
  • 이러한 변수의 초기화는 필수는 아니며 기본적으로 값은 0으로 처리됩니다.
  • 비정적 변수입니다. 즉, 새 객체가 생성될 때마다 변수의 메모리가 할당됩니다.

예:

여기서 a, b, c는 서로 다른 두 객체에 의해 서로 다른 두 인스턴스에 선언된 인스턴스 변수입니다.

코드:

import java.io.*;
class Marks {
// a, b, c are instance variables
// a, b, c variables are being declared inside a class and not function
int a;
int b;
int c;
}
class MarksDemo {
public static void main(String args[])
{
// first object declaration
Alpha alp1 = new Alpha();
alp1 .a= 44;
alp1 .b= 77;
alp1 .c= 88;
// second object declaration
Alpha alp2 = new Alpha();
alp2 .a= 77;
alp2 .b= 55;
alp2 .c= 74;
// displaying variable values for first object
System.out.println("Values for first object:");
System.out.println(alp1.a);
System.out.println(alp1.b);
System.out.println(alp1.c);
// displaying variable values for second object
System.out.println("Values for second object:");
System.out.println(alp2.a);
System.out.println(alp2.b);
System.out.println(alp2.c);
}
}

출력:

첫 번째 개체의 값:
44
77
88
두 번째 개체의 값:
77
55
74

3. Static Variables

  • Static variables are declared at the beginning of the program, preceded by the static keyword.
  • Like instance variables, the initialization of static variables is not mandatory, and their default value is 0.
  • Only one static variable name will be created when the program is started and lost when execution has ended.
  • The memory for these variables is allocated only once at the time of loading the class and can be shared by multiple objects.
  • When the objects are different, the changes made in the value of the static variable in one of the objects will be reflected in all unlike instance variables where the values declared in one object will not be reflected in others.

Example:

Code:

import java.io.*;
class Students {
//static variable rollno
public static double rollno;
public static String name = "Lilly";
public static classnum;
}
public class StudentDetails {
public static void main(String args[])
}
{
// no need of object to access static variables
Students .rollno= 101;
Students.classnum=3;
System.out.println(Students .name + "'s rollno is:" + Students .rollno + "and class number is:" + Students.classnum);
}
}

Output:

Lilly’s rollno is 101, and the class number is: 3

Conclusion – Variables in Java

Variables form the elemental part of a Java program. They point to a particular memory location when they are created, and the same is released when the object is not referenced anymore. This memory which is released, will be swept away when garbage collection takes place. This process can also be considered as the life cycle of a variable.

위 내용은 자바의 변수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java의 기본 패키지다음 기사:Java의 기본 패키지