A variable that is specified outside the function or block of the code is known as Global Variable.
Global Variables(전역변수)는 함수, 코드 블록 외부에 지정되는 변수이다.
So many variables are declared global, then they stay in memory until the execution of the program is completed. This can trigger the issue of Out of Memory.
메모리 성능 저하 우려 → 전역변수는 프로그램 실행이 완료될 때 까지 메모리에 유지된다. 메모리 성능 저하를 유발할 수도 있다.
I thought global variables were more convenient, but now I understand their disadvantages.
단순히 전역변수가 더 편리하다고 생각했는데, 메모리 성능 저하라는 치명적 단점이 존재한다.
We need to modify all the modules where they are named if global variables are discontinued due to code refactoring.
코드 리팩토링으로 전역변수가 중단되면, 모든 모듈을 수정해줘야 한다는 점.
The worst fear of a developer is to have a program where a change in a single function causes a totally different part of the program to fail. Each global variable increases this risk.
개발자의 가장 큰 공포…...(?) 단 한 가지 기능 수정으로 인해 전체 프로그램이 중단되는 것. Global variable은 이런 위험을 증가시킴.
DiceRoller Class
public class DiceRoller {
//Global variables -> declared outside a method, but within a class visible to all parts of a class
Random random;
int number;
DiceRoller(){
random = new Random();
roll();
}
void roll() {
number = random.nextInt(6)+1;
System.out.println(number);
}
}
Main Class
public class Main {
public static void main(String[] args) {
DiceRoller diceRoller = new DiceRoller();
}
}
Random randomint numberDiceRoller()random= new Random(); 로 자체적으로 랜덤 난수를 생성할 수 있다.roll() method, which generates a random number and assigns it to the number variable.roll() 메소드를 호출하면, 랜덤한 숫자가 생성 → number 변수에 값을 저장한다.The Local Variable is specified in the programming block or subroutines as a form of variable declared. The local variable persists before the function's block is executed. It will be lost automatically after that.
코드블록이나 서브쿼리 내에 선언된 변수이다. local 변수는 함수가 실행되기 전 지속되고, 함수 종료되면 소멸된다.
❓ IFFY
Then, I started to wonder, in which situations is it most appropriate to use global variables and local variables?
그럼, 전역변수와 로컬 변수를 어떤 상황에 사용하는 것이 가장 적절한지가 궁금해졌다.
”If u are not sharing data with other function then you will use local variables to store the data.
If u are sharing data with other functions then you should go with global variables.”
When I need to share data with other then Global would be great, If not, use local. It’s a simple answer, but it clarifies their uses.
데이터 공유가 필요한 경우Global, 아닐 경우Local. 심플한 답변이지만, 용도를 알겠다.
Main
public class Test {
public void pupAge() {
// age = local variable. This is defined inside pupAge() method and its scope is limited to only this method.
int age = 0;
age = age + 7;
System.out.println("Puppy age is: " + age);
}
public static void main(String[] args) {
Test test = new Test();
test.pupAge();
}
}
Main
public class Main {
public static void main(String[] args) {
Pizza pizza = new Pizza(); // Instance of Pizze class -> Create pizza
System.out.println("Here are the ingredients of your pizza: ");
System.out.println(pizza.bread);
System.out.println(pizza.sauce);
System.out.println(pizza.cheese);
System.out.println(pizza.topping);
}
}
Summary of the Lecture Code.
강의 코드 정리
Main
public class Main {
public static void main(String[] args) {
Pizza pizza = new Pizza(); // Instance of Pizze class -> Create pizza
System.out.println("Here are the ingredients of your pizza: ");
System.out.println(pizza.bread);
System.out.println(pizza.sauce);
System.out.println(pizza.cheese);
System.out.println(pizza.topping);
}
}
Pizza
public class Pizza {
//Some of the value we receive
String bread;
String sauce;
String cheese;
String topping;
//Pizza Constructor
Pizza(String bread, String sauce, String cheese, String topping){ // 4 Parameters
this.bread = bread;
this.sauce = sauce;
this.cheese = cheese;
this.topping = topping;
}
Pizza(String bread, String sauce, String cheese){ // 3 Parameters
this.bread = bread;
this.sauce = sauce;
this.cheese = cheese;
}
Pizza(String bread, String sauce){ // 2 Parameters
this.bread = bread;
this.sauce = sauce;
}
Pizza(String bread){ // 1 Parameters
this.bread = bread;
}
Pizza(){ // 0 Parameters
}
}
Aren’t there better solutions?
더 좋은 방법이 없을까? → Getters & Setters를 사용한다.
public class Pizza2 {
private String bread = "Plain";
public String getBread() {
return bread;
}
public void setBread(String bread) {
this.bread = bread;
}
}
public class Main {
public static void main(String[] args) {
//getters & setters
Pizza2 pizza2 = new Pizza2();
System.out.println(pizza2.getBread());
}
}