▶ JAVA 형변환 정리


[Int 형을 String 형으로]

int int_val;

String myStr = Integer.toString(int_val);

String str=""+i;



[Double 형을 String 형으로]

double double;

String str = Double.toString(double);



[long 형을 String 형으로]

long l;

String str = Long.toString(l);



[float 형을 String 형으로]

float f;

String str = Float.toString(f);



[String 형을 Int 형으로]

String str;

int i = Integer.parseInt(str);

int i = Integer.valueOf(str).intValue();



[char 형을 String 형으로]

char c;

Character.toString(c);



[String 형을 double 형으로]

String str;

double d = Double.valueOf(str).doubleValue();

double d = Double.valueOf(str);



[String 형을 long 형으로]

String str;

long l = Long.valueOf(str).longValue();

long l = Long.parseLong(str);



[String 형을 float 형으로]

String str;

float f = Float.valueOf(str).floatValue();

float f = Float.parseFloat(str);



[2진수 문자열 s를 10진수로]

int i = Integer.parseInt(s, 2);

[String 문자열을 char 문자 배열로] String a = "안냐세요"; char[] as = a.toCharArray(); //char[] as = {"안", "냐", "세", "요"} for(char i:as){System.out.println(i);} >>>안\n냐\n세\n요 char은 하나의 문자만 가지기 때문에, String line = "나는 배가 고프다"; 와 같은 문장을 띄어쓰기 단위로 저장하고 싶을 때는 split 함수를 사용하면 된다.

[char 문자열을 int 형으로] int cnt = 1; char[] charray = ["1","2","3","4","5"]; for (char A: charray){cnt = cnt + Character.getNumericValue(A);} >>> 15

▶ 자바의 Math 클래스

자바에서 Math클래스는 숫자와 관련된 처리를 위한 메소드를 포함하고 있다심화로 들어가면 삼각함수 등 수학적인 내용도 많지만 가장 기본적인 메소드를 알아보자.이전에 프로젝트를 진행하며 간단한 게임을 제작했는데 그때 몬스터의 등장 부분에 Math.random() 값을 많이 사용했던 경험이 있다.Math class is in the java.lang package, which is imported by default. (It's the only package imported by default, I believe.) 또한 클래스명으로 메서드를 부를 수 있기때문에 abs, ceil, floor 등은 math 클래스의 정적메소드(static method)이다.


Math 클래스 정리

import ​java.lang.Math → 디폴트 임폴트 내용

※Math.(함수) 의 형식으로 Math 클래스의 메서드들이 사용되는 것으로 보아, 이것들은 정적메서드(static)메서드들이다.

Math.abs(double a) : 절대값

Math.ceil(double a) : 값올림

Math.floor( double a): 값내림

Math.round (double a): 반올림

Math.max(double a, double a): 큰 쪽 반환

Math.min(double a, double b) : 작은 값 반환

Math.pow(double a, double b) : 제곱

Math.random() : 0~1사이 값을 랜덤으로 반환


random함수는 0~1까지의 수만 반환하기 때문에, 1에서 10사이의 정수를 랜덤으로 뽑아내기 위해서는 아래와 같은 과정이 필요하다.

 

for (int i = 1; i <= 20; i++) {

int n = (int) (Math.random() * 10) + 1;

System.out.println(n);

}

 

▶ 배열을 순서대로 정렬해주는 array 클래스의 sort 메서드 /리스트를 순서대로 정렬해주는 Collections 클래스의 sort 메서드 also 역순 정리
형태 : Arrays.sort(배열)     input : 배열     output : 배열

형태 : Collections.sort(리스트)     input : 리스트     output : 리스트

 


 


▶ split

형태 : 문자열.split("스플릿기준")   input : 문자열   output : 배열

 

 java.lang은 디폴트로 제공되는 import 이므로 굳이 표시할 필요없다.


※String의 split함수는 정규식을 이용할 수 있다. 따라서 |나 .을 기준으로 split을 사용할 때는 조금 다른 사용법이 필요하다.

예를 들어 String A = "12.33.2.52"; 를 스플릿 하고 싶다면

A.split(".");                 → X
A.split("\\.");
         → O

이스케이프문자 \를 이용해, 정규식이 아님을 알려줘야하는 것이다.

 

▶ 리스트 내에서 최소값, 최대값 구하기

형태 : Collections.max/min(list)    input : 리스트   output : 리스트내 최대/최소값

ArrayList와 Collections 클래스를 활용하여, 리스트내의 최대, 최소값을 구할 수 있다. 
Collections.max() 최대값, Collections.min() 최소값

import java.util.ArrayList;
import java.util.Collections;

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(12);
list.add(39);
list.add(8);
list.add(10);

//최대값
Integer i = Collections.max(list);
System.out.println(i);                     //39 출력

//최소값
Integer i2 = Collections.min(list);
System.out.println(i2);                   //8 출력

▶ 클래스로 타입을 선언하는 것의 의미

Student 클래스가 존재 한다고 하자.int jackson와 같이 기본타입으로 선언된 경우는jackson 변수가 숫자를 갖을 수 있다 라는 명확한 의미를 가지고 있는데 , Student jackson와 같은 경우처럼 Student 클래스로 jackson이라는 변수의 타입을 정의한다는 것은 어떤 의미를 갖는 것일까? 그러기 위해선 먼저 클래스의 정의 부터 살펴 보아야 한다. 클래스란 int jackson, String daniel 과 같은 상태 그리고 동작을 표현하는 메서드가 모여있는 집합이다. 따라서, Student jackson으로 변수타입을 선언하면 Student의 상태와 동작을 표현할 수 있는 변수에 접근할 수 있는 권한 얻게 된 것이다.(jackson.varible, jackson.method()로 Student의 내용을 가져다 쓸 수 있음) 또한 그러한 선언으로 인해 다른 클래스에서 Counter 클래스의 기능을 가져와서 사용할 수도 있게 된다.

쉬운 예로 다음과 같은 것이 있다.  

학생이라면 이름이 필요하고 학번도 필요하고 기타 신상 정보도 필요하겠죠?

그걸 학생이라는 이름의 클래스로 선언해서 하위 멤버 변수들을 상황에 맞게 사용하는 거죠

정말 간단하게만 설명 드리자면

studentname1. studentname2......
studentid1, studentid2.....
학생이 가져야 할 정보가 100개라고 생각해 보세요 그럼 배열을 쓰더라도 100개의 배열을 선언해야겠죠?
그런데 student라는 클래스를 만들면 student[100]이라고 한번만 선언해도
id, name같은 모든 인자를 학생별로 분리해서 쓸수 있으니까요




▶ length 와 .length() 의 차이점


<tbodytr style="color: rgb(85, 85, 85); font-family: Tahoma, 굴림, sans-serif; font-size: 12px; text-align: justify; white-space: normal; background-color: rgb(255, 255, 255);"></tbodytr>

 .length.length()
형태변수메서드
input배열문자열
output배열의 갯수문자열의 길이


▶ ArrayList객체가 취급하는 값

ArrayList 객체는 레퍼런스 값만 담을 수 있기때문에 프리머티브는 파라미터로 설정할 수 없다.


ArrayList <int> = new ArrayList<int>(10); (X) ArrayList <Integer> = new ArrayList<Integer>(10); (O)

▶ String의 값을 비교하는 equal 메서드

다음의 예를 보자.

String a = "hello";
String b = "java";
String c = "hello";
System.out.println(a.equals(b)); // false
System.out.println(a.equals(c)); // true

문자열 a 와 문자열 b 는 "hello"와 "java"로 서로 같지 않다. 따라서 equals 메소드 호출 시 false 를 리턴한다. 문자열 a 와 문자열 c 는 "hello"와 "hello"로 서로 같다. 따라서 true 를 리턴한다.

문자열의 값을 비교할때는 반드시 equals 를 사용해야 한다. == 연산자를 사용할 경우 다음과 같은 경우가 발생할 수 있다.

String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a.equals(b));
System.out.println(a==b);

문자열 a와 b와 c는 모두 "hello"로 같은 값이지만 참조하는 위치가 다르다. a와 b는 heap 메모리 내의 String pool에 저장된 hello의 위치를 같이 참조하기 때문에 같지만, c는 heap 메모리 내에 독립적인 메모리 주소값을 갖기 때문에 참조하는 위치가 a,b와는 다르다.   == 은 두개의 자료형이 동일한 객체인지를 판별할 때 사용하는 연산자이기 때문에 false를 리턴하게 되는 것이다.


▶ if조건판단문 내에서 쓰이는 and(&&), or(||), not(!)

 조건 판단에 쓰이는 것으로 and, or, not이란 것이 있다. 파이썬과 다르므로 주의할 것
 

▶ 주어지는 수에 의해 변수가 계속 변해 갈때의 프로그래밍

import java.util.Scanner; public class practice { public static void main(String[] args) { int[] card = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; int[] arg = new int[2]; // arg = {int1,int2} Scanner scan = new Scanner(System.in); for(int i = 0; i < 10; i++){ arg[0] = scan.nextInt(); arg[1] = scan.nextInt(); System.out.println(arg[0] + " " +arg[1]); card = reverse_card(arg[0], arg[1], card); } for(int i = 0; i < 20; i++) System.out.print(card[i]+ " "); } private static int[] reverse_card(int i, int j, int[] card) { // i=6, j=10 int[] arrangment = new int[2]; for(;i <= j;i++,j--){ //i와 j의 값은 주어지는 값이기 때문에 비워둔다. arrangment[0] = card[i-1]; //arrangment = {6,10} arrangment[1] = card[j-1]; card[i-1] = arrangment[1]; //card = {1,2,3,4,5,"10,9,8,7,6",11,12,13,14,15,16,17,18,19,20}; card[j-1] = arrangment[0]; } return card; } }



▶ 배열에서의 내용물 비교


array1.equals(array2)는 array1 == array2 이 완전히 동일하다는 의미로, 완전히 동일하다는 것은 두 배열이 포함하는 내용을 넘어서 같은 "객체"인지를 비교하는 것이다. 따라서 단순히 내용물만 비교하기 위해서는 다른 메서드를 사용해야 하는데, Arrays.equals(array1,array2)는 두 배열의 내용물만이 같은지를 비교한다.

import java.util.*;
public class practice {
        public static void main(String[] args) {
               int [] card1 = {1,2,3};
               int [] card2 = {1,2,3};

               if(card1.equals(card2)){System.out.println("객체일치");}
               else
{System.out.println("객체불일치");}

               if(Arrays.equals(card1, card2)){System.out.println("내용물일치");}
               else
{System.out.println("내용물불일치");}
        }
}

>>>
객체불일치
내용물일치


▶ 하나의 문제에 여러가지의 풀이법을 생각해보기

 하나의 문제에 대해 여러가지 풀이법을 생각해 보는 활동은 자기자신이 일반적으로 구상하는 알고리즘을 벗어나 창의적인 알고리즘으로 발돋움 할 수 있는 기회를 제공해준다. 이는 프로그래밍 뿐만아니라 일반적인 문제풀이에도 통하는 이야기이다.


▶ 리스트에서 remove를 사용할 시에 주의사항

 리스트의 remove함수는 기존 리스트의 모양을 변형시켜버린다는 점에서 사용시 주의를 요한다.  

String [] array_s1 = s1.split("");  // {"c","a","t","s"}

String [] array_s2 = s2.split("");  // {"c","s","t"}



ArrayList <String> list_s1 = new ArrayList <String>(); 

ArrayList <String> list_s2 = new ArrayList <String>();

for (String i : array_s1){list_s1.add(i);}  //list_s1 = [c, a, t,s]

for (String l : array_s2){list_s2.add(l);}  //list_s2 = [c, s, t]

ArrayList <Integer> filter = new ArrayList <Integer>();

if (list_s1.size() > list_s2.size()){  

for (int i =0;i<list_s1.size();i++){  //list_s1 = [c, a, t, s]

list_s1.remove(i);  //리스트 요소제거 -> 원형훼손

if (list_s1.equals(list_s2)){filter.add(1);list_s1.add(i,array_s1[i]);}  //리스트 요소 재추가 = 원형유지

else {filter.add(0);list_s1.add(i,array_s1[i]);continue;}

}

if (filter.contains(1)){System.out.println("true");}

else{System.out.println("false");}

else{

for (int i =0;i<list_s2.size();i++){

list_s2.remove(i);  //리스트 요소제거 -> 원형훼손

if (list_s2.equals(list_s1)){filter.add(1);list_s2.add(i,array_s2[i]);}   //리스트 요소 재추가 = 원형유지

else {filter.add(0);list_s2.add(i,array_s2[i]);continue;}

}

if (filter.contains(1)){System.out.println("true");}

else{System.out.println("false");}

}

 위의 예는 기존의 문자에서 단 하나의 문자만이 추가 되었을 때, 두개의 문자를 같은 것으로 판별하는 프로그래밍이다.(예를 들어 s1 = "cats", s2 = "cat"라면 두 문자는 같다.
 list_s1=[c,a,t,s]이고 이 리스트의 원형을 유지해가면서, 코딩이 진행되어야 하는데, remove를 쓰게 되면 remove가 작동할 때마다 list_s1의 요소들이 삭제되어 원형이 훼손되게 된다. 따라서, 위의 코딩에서는 제거된만큼 다시 추가해주는 작업을 진행했다. 이 외에도 파이썬의 경우, 제거되어야할 인덱싱만 제외하고 제거대상 요소 앞뒤의 요소들을 합치는 코딩도 있지만, 기본적으로 자바는 리스트나 배열의 더하기 기능을 제공하지 않기 때문에 불가능하다.

▶ print, println, printf
- System.out.print()
()안의 문장을 출력하고 커서가 그 줄에 위치하게 되므로 \n을 통해 직접 개행해야 한다.

- System.out.println()
()안의 내용을 출력하지만 커서를 다음 줄로 자동 개행 시킨다.

-System.out.printf()
파이썬의 문자열 포매팅과 비슷한 기능
 System.out.printf("오늘의 날씨는 %s 도 입니다", 13);
 System.out.printf("오늘의 날씨는 %s 도 이고 %d 요일 입니다", 13,"수");


▶ 리스트 중복 요소 제거
TreeSet을 이용해 리스트의 중복을 제거할 수 있다.
TreeSet <type> 트리셋리스트명 = new TreeSet<type> (중복 제거 대상 리스트);
 

import java.util.*;
public class practice {
     public static void main(String[] args){

             ArrayList <Integer> ugly_collections=new ArrayList <Integer>();

             ugly_collections.add(1);
             ugly_collections.add(1);
             ugly_collections.add(2);
             ugly_collections.add(2);
             ugly_collections.add(3);
             ugly_collections.add(4);
             TreeSet <Integer> distinctdata = new TreeSet<Integer>(ugly_collections);
             System.out.println(distinctdata);
             }
    }

▶ 클래스 변수 선언이 가지는 의미와 다형성의 이해
 ⓐ클래스 객체주소를 참조할 수 있는 공간을 마련한다 
ⓑ클래수 변수 선언에 의해 선언된 변수는 클래스 객체주소의 각각의 요소에 접근할 수 있는 권한을 가진다. 
 

interface Shape{

public static final double Pi = 3.14;

public abstract double calculateArea();

public abstract double calculatePerimeter();


}


class Rectangle implements Shape{

private double length;

private double breadth;

//constructor

public Rectangle(double length, double breadth){

this.length = length;

this.breadth = breadth;

}


public void Rectanglecall(){

System.out.println("I'm Rectangle");

}

//inheritance override

public double calculateArea(){

return length*breadth;

}

//inheritance override

public double calculatePerimeter(){

return 2*(length*breadth);

}

}

Shape s 의 shape 타입의 경우, s는 double Pi = 3.14/ double calculateArea() / double calculatePerimeter()의 3부분에 접근할 수 있는 권한을 가진다. Rectangle r의 Rectangle 타입의 경우, r은 상속한 부분 : double Pi = 3.14/ double calculateArea() / double calculatePerimeter()  Rectagle타입의 고유부분 : double length/ double breadth / Rectangle(double length, double breadth){}; / void Rectanglecall(){}; 의 7부분에 접근할 수 있는 권한을 가진다. 

때문에, Shape s = new Rectangle(); 의 다형성을 구현해도 s는 double length/ double breadth / void Rectanglecall(){}; 에는 접근권한이 없기때문에 구현할 수 없다. (Rectangle은 생성자이기 때문에 객체 생성시 자동으로 접근한다)  접근하고 싶다면 상향형변환을 통해 접근이 가능하다.

▶ 상속시 멤버변수의 접근제어자 관리의 중요성
 
메서드의 경우 조상 클래스의 메서드를 자손의 클래스에서 오버라이딩한 경우에도 참조변수의 타입에 관계없이 항상 실제 인스턴스의 메서드(오버라이딩된 메서드)가 호출되지만, 멤버변수의 경우 참조변수의 타입에 따라 달라진다. 자손클래스를 참조하여 조상클래스에 없는 멤버변수를 호출할 수 없은 것은 당연하고, 멤버변수가 조상 클래스와 자손 클래스에 중복으로 정의된 경우라 하더라도,  멤버변수를 호출시 자손클래스의 멤버변수가 아니라 조상클래스의 변수가 호출된다.

 따라서 상속시 멤버변수 상속에 의한 혼란을 피하기 위해, 애초에 자손클라스의 멤버변수를 private로 한정하고 메서드를 통해서 이니시에이팅 하는 경우가 많다.


package hellojava;



public class practice2{


//어트리부트(멤버변수, 인스턴스 변수) 는 private으로 설정

private String name;

private String employeeNo;

private int password;


//getter 와 setter 설정

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmployeeNo() {

return employeeNo;

}

public void setEmployeeNo(String employeeNo) {

this.employeeNo = employeeNo;

}

public int getPassword() {

return password;

}

public void setPassword(int password) {

this.password = password;

}


}

※How to make getter and setter ? 마우스 오른쪽 -> source -> generate getter and setter 



▶ 인터페이스의 다양한 접근제어자

기본적인 인터페이스의 접근제어자는 멤버변수의 경우 public final, 메서드의 경우 public abstract 이지만 그 외에도, public static, public default가 있다. 

interface Address {


String getStreet();

String getCity();


default String getAddress() {  // 인터페이스의 defaul, static 메서드는 {}중괄호 까지 포함한 완전한 메서드의 모습이다.

return getStreet() + ", " + getCity();

}


static String getCountry() {   // 인터페이스의 defaul, static 메서드는 {}중괄호 까지 포함한 완전한 메서드의 모습이다.

return ("India");

}

}


public class Letter implements Address {

private String street;

private String city;


public void Letter(String street, String city) {

this.street = street;

this.city = city;

}


@Override

public String getCity() {

return city;

}


@Override

public String getStreet() {

return street;

}


//인터페이스의 ​default String getAddress() ;와 static String getCountry() {}은 구현되지 않았다.

public static void main(String[] args) {

Letter letter = new Letter("1001 Lotus Panache", "Delhi");

System.out.println(letter.getAddress()); //슈퍼클래스의 상속처럼, '객체.메서드'의 형태로 사용한다.

System.out.println("Country " + Address.getCountry());//생성자의 경우 '인터페이스 이름. 메서드'로 사용한다.

       }

}


▶ 클래스에 대한 더 깊은 이해

지금까지 클래스에 대한 내용을 정리하면 다음과 같다.
Water w1= new Water ();

Water w2= new Water ();


( new Water () : 설계도, Water w1/Water w2 : Water라는 설계도로 만들어진 각각의 제품)


 Water 타입변수(클래스 타입의 변수) w는 2가지 기능을 갖는다. 

ⓐ Water 클래스의 주소값을 참조하여 클래스 전체를 저장해 두는 기능 

ⓑ Water 클래스의 각각의 멤버변수(필드), 메서드를 사용할 수 있는 권한 

ⓒ w1과 w2는 Water라는 동일한 클래스의 내용을 참조하고 있지만, 단지 참조하는 것일 뿐이므로 w1에 저장된 값과 w2에 저장된 값은 다른다.(w1과 w2는 독립성을 지닌 객체이다) ⓒ 변수 w은 Water 클래스 내부의  멤버변수와 메서드를 사용할 수 있는 권한만을 지니기 때문에, 그 이상의 멤버변수와 메서드를 가지고 있는 다른 클래스를 다형성으로 받았을때 본래 멤버변수와 메서드 이외의 부분은 구현할 수 없다.


class Water{

String water = "water";

public void water(){

System.out.println("water");

}

// public String toString(){

// return "water";

// }


}


public class practice{

public static void main(String[] args){

String Fire = "Fire";

Water w = new Water();  // Water타입 변수 w은 1.인스턴트 변수 water, 2. water메서드에 접근할 수 있는 권한을 부여받는다.

System.out.println(Fire);

System.out.println(w);            //    클래스 전체를 프린터

System.out.println(w.water);  // 변수 w을 통해 멤버 변수를 프린터

w.water();

}

}

>>>

Fire

hellojava.Water@1db9742    →    ★클래스 전체가 프린터된다!! 하지만 읽을 수는 없다.

water

water

>>>   toString을 구현했을 때의 결과값

Fire

water    →    클래스 전체의 프린트 내용이 String으로 명확해졌다.

water

water

▶ What is the difference between Collection and Collections in java?

This is one of the most confusing java interview question asked many a times to java freshers. Most of time, this question has been asked to java freshers to check their basic knowledge about the Java Collection Framework. This question seems confusing because both “Collection” and “Collections” look similar. Both are part of java collection framework, but both serve different purpose. Collection is a top level interface of java collection framework where as Collections is an utility class. In this article, we will discuss the differences between Collection and Collections in java.

<ins id="aswift_0_anchor" style="box-sizing: border-box; margin: 0px; padding: 0px; vertical-align: baseline; outline: 0px; background: 0px 0px transparent; border: none; text-decoration-line: none; display: block; height: 90px; position: relative; visibility: visible; width: 757px;">CollectionInterface :
Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.</ins>




Collections Class:
Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.
Collections.max()This method returns maximum element in the specified collection.
Collections.min()This method returns minimum element in the given collection.
Collections.sort()This method sorts the specified collection.
Collections.shuffle()This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection()This method returns synchronized collection backed by the specified collection.
Collections.binarySearch()This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint()This method returns true if two specified collections have no elements in common.
Collections.copy()This method copies all elements from one collection to another collection.
Collections.reverse()This method reverses the order of elements in the specified collection.



▶ java collection framework에서 다형성을 빈번하게 사용하는 이유

 아래의 예에서 Set <String> placeSet = new HashSet<>();  와 같이 JCF의 클래스가 상위의 인터페이스를 다형성을 통해 참조시키는 경우를 빈번하게 볼 수 있다. List <String> list = new ArrayList<>();도 그 예 중하나다. 하위 클래스가 상위 인터페이스를 다형성을 통해 참조시키는 이유는, 상위 인터페이스로 변수를 선언하면 하위의 클래스를 실행할 때마다 일일이 새로운 변수를 선언할 필요가 없이 인터페이스의 변수 하나만으로 코딩을 전개할 수 있기 때문이다. 가령, Set인터페이스의 아래에는 HashSet과 SortedSet의 클래스가 있으며, Set <String> placeSet = new HashSet<>(); Set <String> placeSet = new SortedSet<>(); 과 같이 placeSet 변수로 HashSet과 SortedSet의 클래스를 모두 받아올 수 있어서 편리하다.


package hellojava;


import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;


public class practice {

public static void main(String[] args) {

Set <String> placeSet = new HashSet<>();  

System.out.println(placeSet.add("Zoo"));  

System.out.println(placeSet.add("Park"));

System.out.println(placeSet.add("Museum"));

System.out.println("Output for Set Collection : ");


for (Iterator<String> iterator = placeSet.iterator(); iterator.hasNext();) {

System.out.println("Elements are : " + iterator.next());

}

}

}

▶ 자바이클립스 단축키모음

ctrl + O :클래스 내부의 클래스, 메서드 이름 및 구성확인

ctrl + t : 상속 인터페이스하는 클래스와의 클래스의 위계관계를 볼 수 있다.  
오브젝트. + ctrl + space : 오브젝트 클래스의 메서드확인

F3 :  메서드나 클래스의 원래 위치로 이동

F2 :  메서드나 클래스의 설명이 나옴
ctrl + shift + r : 이클립스내부의 class, xml, html 등의 파일을 검색할 수 있다.

ctrl + shift + o : import되지 않은 클래스를 자동으로 import 해준다.



▶ Package 가 다른 Class를 불러올 때는 Import package.class; 를 통해 calling 해야 사용할 수 있다.

▶ Static import

static import:It has function that static method or static field can be used

not declaring Class object


ex] Class Daseul has static head field argument.


in Sooyeon Class import static org.junit.Daseul.*; (*could call all static inside Daseul class)


25. 디버깅 단축키

F6 : 한줄 씩 디버깅

F7 : 이전 브레이크 포인트로 돌아가기

F8 : 다음 브레이크 포인트로 넘어가기

F11 : 디버깅 초기화



▶ 한 클래스 내의 한 함수에서 다른 함수를 부를 때는 객체 생성할 필요가 없다.


package com.java.ex4;


import java.util.ArrayList;


public class MyInfo {

private String name;

private double height;

private double weight;

private ArrayList<String> hobbys;

private BMICalculator bmiCalculator;


public void bmiCalculation(){

bmiCalculator.bmiCalculation(height, weight);

}

public void getInfo(){

System.out.println("name: " + name);

System.out.println("height: " + height);

System.out.println("weight: " + weight);

System.out.println("hobby: " + hobbys);

bmiCalculation();

}

▶ 자바의 설계에서의 팁 ★

다음의 자바 클래스 설계는 내가 구현하고자 하는 유저 인터페이스에서 부터 역으로 생각하여 클래스를 설계하는 팁이다.

1. 먼저 내가 구현하고자하는 인터페이스를 실제로 그려라.

2. 그 유저이터페이스에 필요한 변수가 무엇이며, 하나하나의 변수들이 어떠한 계산의 결과 아웃풋된 대상인지 생각하라.

3. 아웃풋을 유발한 논리적 구조를 클래스로 구현해라.

*클래스를 구현할 때는 다음과 같은 요소에 주의하라.

-하나의 클래스가 하나의 기능만을 가지고 있는가?(가령, 변수를 지정한다, 한 변수를 아웃풋한다.. 등등)

-발생할 수 있는 유지.보수들을 고려했을 때, 유지보수가 용이한가?

4. 역으로 생각한 마지막 단계는 인풋값이 들어가는 클래스이다.


5.클래스의 설계가 끝난 이후엔, 역순의 역 그러니까 순방향으로 생각하여 "인풋 - 알고리즘 - 아웃풋" 이 가능한지 검증한다.


▶ main메서드의 (String[] args)의 의미

cmd에서 자바를 시행하면 args에 값을 시스템 내부값으로 인풋할 수 있다.  이것이 존재하는 이유는 자바파일을 시행시킬 때 초기값을 전달할 수 있기 때문이다.  


//Test.java

public class Test{


public static void main(String[] args){

for(int i=1;i<10;i++){

for(int k=1;k<10;k++){

System.out.println(i+"*"+k+"="+i*k);

}

}

if(args.length != 0){

System.out.println(args[0]);

System.out.println(args[1]);

}

}

//cmd

javac Test.java
java  Test Hi Hello

▶ package의 이름은 단순한 파일명이 아니라, 디렉토리를 패싱해주는 역할을 한다.

Package com.java.ex 라 함은, .../com/java/ex의 의미이다.아래는 패키지가 설정되어 있는 java파일을 cmd에서 여는 방법이다.


C:\Users\daseul.kim\Desktop\JavaManuelTest\com\java\exha에 Test.java파일이 있고 현재 디렉토리는 C:\Users\daseul.kim\Desktop\JavaManuelTest라고 할때


[cmd]

C:\Users\daseul.kim\Desktop\JavaManuelTest>javac com/java/exha/Test.java


C:\Users\daseul.kim\Desktop\JavaManuelTest>java com.java.exha.Test

▶ 자바에서 중괄호{}는 라이프 사이클을 시작과 끝을 의미한다. 

 지금까지는 중괄호가 반드시 class, method, for, while, if문 뒤에만 쓰이는 줄 알았지만, 어디에도 올 수 있으며, 중괄호는 그 안에 포함된 변수의 라이프 사이클의 시작과 끝을 의미한다. 때문에 class 중괄호 이후에 오는 변수는 전역변수, 메소드 중괄호 이후에 오는 변수는 지역변수로 구분되는 것이다.


▶ try ~ catch문에서 가장 마지막 catch문은 Exception 예외를 처리해주도록 쓰여야한다. 


▶ 일반적으로 변수의 초기화는 디폴트 생성자에서 담당하도록 한다.

 이유로는 1. 따로 setter를 통해 초기화를 시켜줄 번거로움이 사라진다는 것. 2. 프로그래밍을 하다보면 변수의 초기화가 이루어지지 않아 오류가 발생하는 경우가 많은데 이러한 오류를 초기에 예방할 수 있다는 점이 있다.



▶ 새로운 객체의 주소값이 생성되는 키워드는 new 뿐이다.

 new는 새로운 객체 주소값을 생성시키고 특정한 값을 담아둔다.(Test test = new Test()) 그리고 그 주소값을 그대로 같은 타입의 변수에게 전달하면 그 변수도 같은 주소값을 공유하게 되므로 한쪽에서 객체를 수정하면 다른 쪽에서도 반영되게 된다.(Test test2 = new Test())


▶ static initializer

static initializer is executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).


It can be thought of as a "class constructor".


Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.

스태틱 이니셔라이져가 디폴트 생성자보다 먼저 생성된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.java.prac;
 
public class LalaLand{
 
    private int var1;
    private int var2;
 
    public LalaLand() {
        System.out.println("default constructor has been performed");
    }
 
    static {
        System.out.println("static has been performed");
    }
 
}
cs


1
2
3
4
5
6
7
8
9
10
11
package com.java.prac;
 
public class MainClass{
 
    public static void main(String[] args) {
 
        LalaLand k = new LalaLand();
 
    }
 
}
cs


>>>

static has been performed

default constructor has been performed


▶자바는 각 블록{} 이 독립적으로 움직이지만, 자바스크립트는 독립된 블록범위를 갖지 않는다.

JAVA

1
2
3
4
5
int x = 1;
{
  int = 2;
}
system.out.println(x) // outputs 1
cs



JAVASCRIPT

1
2
3
4
5
int x = 1;
{
  int = 2;
}
console.log(x) // outputs 2
cs




▶src파일과 bin파일

source code 파일(.java)과 byte code 파일(.class)이 한 폴더에 함께 있는 것은 바람직하지 못하다.
배포할 때에는 실행파일인 바이트코드 파일, 즉 class파일만 배포하는데 여기에 소스코드 파일인 java 파일이 섞여 있으면 관리하기가 불편하기 때문이다.

따라서 두 종류의 파일을 서로 다른 폴더로 분리시켜야 한다.


구분하는 방법은 쉽다.
class파일은 컴파일이 완료되면 생성된다. 
그 말은 컴파일 할 때 옵션을 줘서 어느폴더에 저장될지 지정해주면 된다는 말씀이다.

폴더를 지정해주기 전에, 그 폴더를 만들어줘야 한다.
있지도 않은 폴더에 무언가를 담을 수는 없으니까.

보통은. 일반적으로는. 대부분은.
소스코드(자바 파일)는 source의 약자로 'src'라는 이름으로, 클래스 파일은 binary의 약자로 'bin'이라는 이름으로 폴더를 지정해준다.



+ Recent posts