분류 전체보기70 두 변수의 값 바꾸기 (swap) 자바에서는 두 변수의 값을 바꿀 때 임시 저장 변수인 temp변수를 이용하여 값을 바꾼다. 아래 코드를 2,3,1로 바꿔보자 public class Temporary { public static void main(String[] args){ int a = 1; int b = 2; int c = 3; int temp = 0; //temp 라는 빈공간에 a의 값인 1의 값을 넣는다. //이제 a 로 아무거나 할 수 있음 (a = 1상태임 아직, 근데 temp도 1임) temp = a; a = b; //이때도 b의 값은 b = 2 b = c; c = temp; //복사해둔 a값을 쓴다. System.out.println(a); System.out.println(b); System.out.println(c); .. 2022. 1. 7. Try-catch 예외처리 Error와 Exception의 차이 error는 error가 발생하면 프로그램이 종료되지만, excpetion은 error가 발생하여도 , excpetion handling(예외처리)을 통해 프로그램이 계속 작동할 수 있게 해준다. 자바에서 예외처리는 try-exception을 통해 해준다. exception에서 printStackTrace() 메소드를 쓰면 어디서 에러가 발생했는지 알려준다. public class TryCatch{ public static void main(String[] args){ int num1,num2 try{ num1=0; num2=62/num1; System.out.println(num2); // 0으로 나누어져서 에러발생 System.out.println("숫자는 0으로.. 2022. 1. 7. Super() 메소드 this()메소드는 같은 클라스의 다른 생성자를 호출할 때 사용된다면, super()메소드는 부모 클라스의 생성자를 호출할 떄 사용된다. public class PracticeSuper { public static void main(String[] args){ Child ch = new Child(); ch.display(); } } class Parent{ int a ; Parent(){ a = 10; } Parent(int n){ a = n; } } class Child extends Parent{ int b; Child(){ super(); this.b = 20; } public void display(){ System.out.println(a); System.out.println(b); } } 여.. 2022. 1. 7. super 키워드 super키워드는 부모클라스의 메소드나 필드를 상속 받을 때 쓰는 참조변수이다. 인스턴스 변수와 지역변수의 이름이 같을 경우 this 키워드를 통해 가져왔는데, super도 이와 같은 맥락으로 부모클라스와 자식 클라스의 맴버가 같을 경우 super를 써서 데려올 수 있다. 코드를 통해 자세히 살펴보자.. 1.변수가 부모클라스에서만 선언되는 경우 모든 변수가 같은 값을 출력한다. public class PracticeSuper { public static void main(String[] args){ Child ch = new Child(); ch.display(); } } class Parent{ int a = 10; } class Child extends Parent{ public void displa.. 2022. 1. 7. 이전 1 ··· 13 14 15 16 17 18 다음