-
-
Java 클래스
Java
자바 클래스 핵심
class Student {
int kor, eng, math;
public Student(int kor, int eng, int math){
this.kor = kor;
this.eng = eng;
this.math = math;
} // 생성자(constructor) 라 불리는 함수
};
// 초기값을 주고 싶을때는 동일한 것을 선언하여서 주면된다
class Student {
int kor, eng, math;
public Student(){
this.kor = 0;
this.eng = 0;
this.math = 0;
}
public Student(int kor, int eng, int math){
this.kor = kor;
this.eng = eng;
this.math = math;
}
};
public class Main {
public static void main(String[] args) {
Student student1 = new Student(90, 80, 90); // 넘어간 값을 사용
System.out.println(student1.kor); // 90
System.out.println(student1.eng); // 80
System.out.println(student1.math); // 90
Student student2 = new Student(); // 값이 넘어가지 않는 생성자를 이용
System.out.println(student2.kor); // 0
System.out.println(student2.eng); // 0
System.out.println(student2.math); // 0
}
}
객체 정렬 @override로 / implements Comparable
Java에서는 custom comparator를 만들어야 합니다. 이 함수는 반환 타입이 꼭 int 이어야 하며, 해당하는 class를 type으로 하는 1개의 인자를 갖고 있어야만 합니다. 가장 일반적인 방법은 class 뒤에 implements Comparable를 붙이고 public int compareTo 함수를 class 안에 override annotator와 함께 적어주시면 됩니다.
class Student implements Comparable<Student> {
int kor, eng, math;
public Student(int kor, int eng, int math){
this.kor = kor;
this.eng = eng;
this.math = math;
}
@Override
public int compareTo(Student student) { // 국어 점수 기준 오름차순 정렬
if(this.kor > student.kor)
return 1;
else if(this.kor < student.kor)
return -1;
else
return 0;
}
};
///
@Override
public int compareTo(Student student) { // 국어 점수 기준 오름차순 정렬
return this.kor - student.kor;
}
하지만 Java 8 부터는 굳이 정렬 기준을 class안에 적지 않고, Arrays.sort 사용시 인자로 정렬 함수를 다음과 같이 넣어주는 방식도 가능합니다. 두 인자 값을 순서대로 a, b라 했을 때 국어 점수 기준 오름차순 정렬을 위해서는 a.kor - b.kor를 반환해주면 됩니다. 이는 lambda라는 표현을 사용하여 함수를 간단히 작성이 가능합니다.
Arrays.sort(students, (a, b) -> a.kor - b.kor); // 국어 점수 기준 오름차순 정렬
comparator를 사용한 정렬
// custom comparator를 활용한 정렬
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student a, Student b) { // 키를 기준 오름차순 정렬합니다.
return a.height - b.height;
}
});
comparator를 이용해서 main안에서 정렬 때리기
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
// 학생들의 정보를 나타내는 클래스 선언
class Student {
String name;
int height;
double weight;
public Student(String name, int height, double weight){
this.name = name;
this.height = height;
this.weight = weight;
}
};
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 변수 선언 및 입력:
int n = 5;
Student[] students = new Student[n];
for(int i = 0; i < n; i++) {
String name = sc.next();
int height = sc.nextInt();
double weight = sc.nextDouble();
// Student 객체를 생성해 리스트에 추가합니다.
students[i] = new Student(name, height, weight);
}
// custom comparator를 활용한 정렬
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student a, Student b) { // 이름 기준 오름차순 정렬합니다.
return a.name.compareTo(b.name);
}
});
// 이름순으로 정렬한 결과를 출력합니다.
System.out.println("name");
for (int i = 0; i < n; i++){
System.out.print(students[i].name + " ");
System.out.print(students[i].height + " ");
System.out.printf("%.1f\n", students[i].weight);
}
System.out.println();
// custom comparator를 활용한 정렬
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student a, Student b) { // 키 기준 내림차순 정렬합니다.
return b.height - a.height;
}
});
// 키순으로 정렬한 결과를 출력합니다.
System.out.println("height");
for (int i = 0; i < n; i++){
System.out.print(students[i].name + " ");
System.out.print(students[i].height + " ");
System.out.printf("%.1f\n", students[i].weight);
}
}
}
-
Java 함수
Java
자바 함수 핵심
public static final int MAX_N = 100;
//
//final (Java):
final은 값을 변경할 수 없는 변수를 선언할 때 사용합니다.
기본 데이터 타입(예: int, double)에서는 값 자체가 고정됩니다.
참조 데이터 타입(예: 객체, 배열)에서는 **참조(주소)**가 고정되지만, 객체의 내부 상태는 변경할 수 있습니다.
클래스나 메서드에도 사용할 수 있어 상속을 금지하거나 오버라이딩을 방지할 수 있습니다.
//
//const (JavaScript):
const는 재할당이 불가능한 변수를 선언할 때 사용합니다.
기본 데이터 타입에서는 값 자체가 고정됩니다.
객체나 배열 같은 참조 데이터 타입에서는 **참조(주소)**가 고정되지만, 내부의 값을 변경할 수 있습니다.
const는 **블록 범위(block scope)**를 가지며, 선언된 블록을 벗어나면 유효하지 않습니다.
//
콜 바이 래퍼런스
즉, Java에서의 swap은 Reference type을 이용하여 다음과 같이 구현해야만 합니다
class IntWrapper {
int value;
public IntWrapper(int value) {
this.value = value;
}
}
Java에서 생성자는 반드시 클래스와 같은 이름을 가져야 합니다. 그리고 접근 제어자(access modifier)는 선택 사항입니다. 생성자의 접근 제어자는 다음과 같이 설정할 수 있습니다:
public: 클래스 외부에서도 생성자를 호출할 수 있습니다. 가장 일반적인 접근 제어자입니다.
private: 클래스 내부에서만 생성자를 호출할 수 있습니다. 일반적으로 싱글턴 패턴(Singleton pattern)이나 정적 메서드만을 통해 객체 생성을 허용할 때 사용됩니다.
protected: 같은 패키지에 있는 다른 클래스나 해당 클래스를 상속받은 서브 클래스에서 생성자를 호출할 수 있습니다.
default (아무 접근 제어자도 지정하지 않음): 같은 패키지 내의 클래스에서만 접근할 수 있습니다.
public class Main {
public static void swap(IntWrapper n, IntWrapper m) {
int temp = n.value;
n.value = m.value;
m.value = temp;
}
public static void main(String[] args) {
IntWrapper n = new IntWrapper(10);
IntWrapper m = new IntWrapper(20);
swap(n, m);
System.out.println(n.value + " " + m.value); // 20 10
}
}
clone , 배열
가장 간단한 방법으로, 함수로 값을 넘길때 다음과 같이 .clone()을 하게 되면 기존 배열과 동일한 원소를 갖는 새로운 배열을 만들어 넘겨주게 되므로, 함수 안에서의 변화가 함수 밖의 변수에 영향을 끼치지 않게 됩니다.
public class Main {
public static void modify(int[] arr2) { // arr2는 arr와 관련이 없다.
arr2[0] = 10;
}
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 3, 4};
modify(arr.clone()); // 새로운 배열을 만들어 넘기기
for(int i = 0; i < 4; i++)
System.out.print(arr[i] + " ");
}
}
>> 1 2 3 4 # 값에 변화가 없다
import java.util.Scanner;
public class Main {
public static final int MAX_N = 50;
public static int n;
public static int[] arr = new int[MAX_N];
// 위에 처럼 선언을 main밖에 해줘서 써죽
public static void modify(int[] arr) {
for(int i = 0; i < n; i++)
if(arr[i] % 2 == 0)
arr[i] /= 2;
}
public static void main(String[] args) {
// 변수 선언 및 입력:
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
modify(arr);
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
java는 String도 함수로 바로 연결못함
함수에서 해당 인자 값을 변경하였지만, 함수 밖에 있는 변수에는 영향을 끼치지 않는 것을 확인할 수 있습니다.
이는 String은 immutable하기 때문입니다. immutable하다는 것은 값을 바꿀 수 없는 type이라는 뜻입니다.
값을 바꿀 수 없으니 s += “apple”이라는 구문은 기존 s 문자열 뒤에 apple을 붙이는게 아닌, 실제 s + “apple” 를 계산하여 새로운 문자열을 만든 뒤 이 값을 s에 대입하게 됩니다.
동시에 String은 reference type입니다. 즉, 함수 안에서 변수 s에 새로운 값을 대입시켜봤자, main함수에서 정의된 “banana”라는 값에는 전혀 영향을 끼칠 수가 없는 것입니다.
public class Main {
public static void modify(String s) {
s += "apple";
}
public static void main(String[] args) {
String str = "banana";
modify(str);
System.out.print(str);
}
}
>>> banana
배열 length , 문자열 length()
int[] arr = {1, 2, 3, 4, 5};
int length = arr.length; // 배열의 길이
String str = "Hello, World!";
int length = str.length(); // 문자열의 길이
정렬
import java.util.Arrays;
int[] arr = new int[]{12, 41, 37, 81, 19, 25, 60, 20};
Arrays.sort(arr);
Arrays.sort(arr, 시작 Index, 끝 Index + 1)
///////
// 내림차순
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] arr = new Integer[]{12, 41, 37, 81, 19, 25, 60, 20};
Arrays.sort(arr, Collections.reverseOrder());
for(int i = 0; i < 8; i++) // 81, 60, 41, 37, 25, 20, 19, 12
System.out.print(arr[i] + " ");
}
}
즉 int 배열을
// 내림차순 정렬
Integer[] nums2 = Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(nums2, Collections.reverseOrder());
이렇게 하여서 Integer로 바꾸어주어야한다.
//
반대로 Integer를 int배열로
// Integer[]를 int[]로 변환
int[] intArray = Arrays.stream(nums).mapToInt(Integer::intValue).toArray();
-
Java 문자열
Java
자바 문자열 핵심
기본 입출력
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char c = sc.next().charAt(0);
System.out.println(); //줄바꿈
System.out.printf("%.2f %d",a,b);//포맷
System.out.print();//그냥 출력
//배열
int[] arr = new int[크기];
int[] arr = new int[3]{1,2,3};
문자열 입력
Scanner sc = new Scanner(System.in);
String str = sc.next(); //공백으로 나누어서 입력받음
String str = sc.nextLine(); // space를 포함해서 입력받음
문자열 관련 코드
str.length()// str문자열의 길이 반환
String a = "apple", b = "banana";
a = a + b; //문자열 합치기 가능1
String a = "apple", b = "banana", c = "candy";
String totStr = "";
totStr += a;
totStr += b;
totStr += c;
//문자열 합치기 가능2
str.charAt(5); //str문자열의 인덱스 5번 반환
문자열.substring(시작 인덱스, 끝 인덱스)//시작 인덱스부터 끝 인덱스 전까지로 이루어진 부분문자열이 반환
s.substring(i, i + 2).equals("ab")//i~i+2가 ab랑 같은지
s.contains("ab")//s라는 문자열이 ab를 가지고 있는지 성공하면 true반환 아니면 false반환
s.indexOf("ab")//s에서 ab라는 해당 부분 문자열이 없는 경우에는 -1을, 있는 경우에는 가장 앞에 나오는 부분 문자열의 위치를 반환
문자열 끼리의 == 연산자는 두 문자열의 주소 값이 일치하는지를 비교하는 연산이기에 목적과는 다릅니다. str1.equals(str2) 함수를 써야한다.
문자열을 배열로 만들기
public class Main {
public static void main(String[] args) {
String s = "baaana";
char[] arr = s.toCharArray(); //문자열을 배열로 만들기
arr[2] = 'n';
s = String.valueOf(arr); //배열을 문자열로 만들기
System.out.println(s);
}
}
>> banana
아스키코드 출력
System.out.println((int)'A');
// A의 아스키코드인 65 출력
Math
Math.abs(숫자);
문자열을 정수로 변환하기
int aInt = Integer.parseInt(a) + 1;
정수를 문자열로 변환하기
Integer.toString(a);
사전순 앞 비교
String a = "abc";
String b = "abd";
String c = "aba";
System.out.println(a.compareTo(b)); // -1
System.out.println(a.compareTo(c)); // 2
System.out.println(a.compareTo(a)); // 0
//compareTo() 함수를 사용합니다. 두 문자열 str1, str2가 주어졌을 때 str1.compareTo(str2) 값이 0보다 작으면 str1이 사전순으로 더 앞서고, 0보다 크면 str2이 사전순으로 더 앞서고, 0이면 두 값이 같음을 의미합니다.
Touch background to close