model/Users.java

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;
}

repository/UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}

service/UserService.java

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User registerUser(User user) {
        // 비밀번호 강도 확인
        if (!isPasswordStrong(user.getPassword())) {
            throw new IllegalArgumentException("비밀번호는 최소 8자 이상이어야 합니다.");
        }

        // 중복 사용자명 확인 (UserRepository의 findByUsername 메서드 사용)
        Optional<User> existingUser = userRepository.findByUsername(user.getUsername());
        if (existingUser.isPresent()) {
            throw new IllegalArgumentException("이미 사용 중인 사용자명입니다.");
        }

        // 필수 필드 검사
        if (user.getUsername() == null || user.getUsername().isEmpty() ||
            user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new IllegalArgumentException("사용자명과 비밀번호는 필수 입력값입니다.");
        }

        // 이메일 유효성 검사 등 추가 검사가 필요한 경우도 추가 가능

        // 유효성 검사를 통과한 경우 사용자 저장
        return userRepository.save(user);
    }

    private boolean isPasswordStrong(String password) {
        // 비밀번호 강도 확인 로직 추가 (예: 최소 길이, 특수 문자 포함 등)
        return password != null && password.length() >= 8;
    }
}

controller/UserController.java

@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseEntity<User> registerUser(@RequestBody User user) {
        User newUser = userService.registerUser(user);
        return new ResponseEntity<>(newUser, HttpStatus.CREATED);
    }
}

1. jdk 설치

https://www.oracle.com/java/technologies/downloads/ 

 

Download the Latest Java LTS Free

Subscribe to Java SE and get the most comprehensive Java support available, with 24/7 global access to the experts.

www.oracle.com

 

2. 환경변수 설정

환경변수 --> 시스템변수 --> JAVA_HOME 에 설치된 jdk 경로 추가

환경변수 --> 시스템변수 --> Path 누르고 편집 누르기 --> 새로 만들기 누르기 --> %JAVA_HOME%/bin 추가

 

3. vscode 마켓플레이스에서 확장팩 설치

  • Java Extension Pack
  • Spring Boot Extension Pack
  • Lombok Annotations Support for VS Code

4. Ctrl + Shift + P 누르고 선택창에서 "Spring initalizr: Create a Gradle Project" 선택 후

spring boot 3.1.5

language Java

Java version 17

Packaging type jar

Dependencies 

  • Spring Boot DevTools
  • Lombok
  • Spring Configuration Processor
  • Spring Web
  • Spring Data JPA
  • H2 Database
  • Flyway Migration
  • MariaDB Driver <- PostgreSQL Driver 등 사용하는 DB driver로

선택

 

5. 프로젝트 만들 폴더 선택

6. 완료

 

 

▶ 메소드로 기초변수 전달

public class MyCounter {

int value;

int inc(int a) {

return a=a+1;

}

}

class MyCounterTest {

public static void main(String[] args) {

MyCounter obj = new MyCounter();

int x =10;

obj.inc(x);

System.out.println(x);

System.out.print(obj.inc(x));

}

}

실행결과

10

11

설명) 

인수 x가 매개변수 a로 복사되는 것이 아니라,

인수 x의 값이 매개변수 a로 복사 된다.

그래서 x의 값은 변하지 않는다.

그리고 obj.inc(x)와 x의 값이 다른 것을 볼 수 있다.


▶ 메소드로 참조변수 전달

public class MyCounter {

int value=0;

void inc(MyCounter ctr) {

ctr.value =ctr.value+1;

}

}

class MyCounterTest {

public static void main(String[] args) {

MyCounter obj = new MyCounter();

System.out.println(obj.value);

obj.inc(obj);

System.out.println(obj.value);

}

}

실행결과

0

1

설명)

참조 변수의 경우, 참조값이 매개변수로 복사되기 때문에

인수와 매개 변수 모두 동일한 객체를 가리키게 된다.

참조변수를 매개변수로 갖는 메소드에서 값을 변경하면 

인수도 값이 변경된것과 마찬가지이다


▶ 메소드로 배열 전달

public class MyCounter {

void inc(int[] array) {

for(int i=0;i<array.length;i++)

array[i]=array[i]+1;

}

}

class MyCounterTest {

public static void main(String[] args) {

int[] list = {1,2,3,4};

MyCounter obj = new MyCounter();

obj.inc(list);

for (int i=0; i<list.length;i++)

System.out.print(list[i]+" ");

}

}

실행결과

2 3 4 5

설명)

배열도 객체이므로 객체가 전달되는 것과 동일하게 처리된다.

참조값이 복사되고 메소드에서 배열을 변경하면 원래 배열도 변경된다.



▶ 정적멤버

멤버를 정의할 때 앞에 static을 붙이면 정적멤버가 된다

모든 객체에 공통인 변수나 메소드가 필요할 때 사용한다 = 정적 변수, 정적 메소드

객체를 생성하지 않고도 사용할 수 있다

정적메소드는 this키워드를 사용할 수 없다 참조할 객체가 없기 때문이다

클래스이름.변수이름

클래스이름.메소드이름

public class MyCounter {

static void inc(int[] array) {

for(int i=0;i<array.length;i++)

array[i]=array[i]+1;

}

}

class MyCounterTest {

public static void main(String[] args) {

int[] list = {1,2,3,4};

MyCounter.inc(list);

for (int i=0; i<list.length;i++)

System.out.print(list[i]+" ");

}

}

실행결과

2 3 4 5

설명) 메소드로 배열 전달 예제를 변형시켰다

void inc() 메소드를 정적 멤버로 정의했다

객체를 생성하지 않아도 되기 때문에 MyCounter.inc(list);를 바로 썼다


▶ 인스턴스 멤버와 정적 멤버

-인스턴스 멤버

동일한 클래스를 이용하여 여러 객체들이 생성될 때 각각의 객체들마다 별도로 멤버를 갖는다

이것을 인스턴스 멤버라고 한다


-인스턴스 변수에 값을 대입하거나 메소드를 호출할 때

객체이름.변수(메소드)이름

-정적 변수에 값을 대입하거나 메소드를 호출할 때

클래스이름.변수(메소드)이름


public class Car {

private String model;

private String color;

private int speed;

private static int numbers =0;

public Car(String m,String c, int s) {

model=m;

color=c;

speed=s;

++numbers;

}

public static int getNumberOfCars() {

return numbers;

}

void print() {

System.out.println(model+color+speed);

}

}

class CarTest{

public static void main(String[] args) {

Car c1=new Car("S600","white",80);

Car c2=new Car("E500","blue",60);

int n = Car.getNumberOfCars();

System.out.println(n);

c1.print();

c2.print();

}

}

2

S600white80

E500blue60

설명)

정적 메소드 안에는 인스턴스멤버를 사용할 수 없다

정적 변수 numbers가 private로 선언되었기 때문에 바로 접근 할 수 없다

정적 메소드로 numbers를 반환해서 사용한다

Car()생성자와 print()메소드는 매개변수이름과 안에 사용한 인스턴스 변수이름이 겹치지 않기 때문에 this.model 이라고 쓰지 않았다


▶ 상수

static final int MAX_SPEED = 350;

- 상수를 정적 멤버로 선언하는 이유

상수를 인스턴스 변수로 선언하면 각 객체마다 하나씩 만들어지므로 저장 공간이 낭비된다


▶ 정적 초기화 블록

static {

//정적 변수 초기화

}

public class MyClass {

static int x;

static int y;

static String xy;

static {

x=10;

y=5;

xy="("+x+","+y+")";

}

}

class MyClassTest {

public static void main(String[] args) {

System.out.println(MyClass.xy);

}


}

실행결과

(10,5)


▶ 상속(inheritance)

부모클래스(수퍼클래스)

자식클래스(서브클래스)

자식 클래스는 부모 클래스의 멤버를 모두 물려받는다

class 자식클래스이름 extends 부모클래스이름

public class Car {

private String model;

private String color;

private int speed;

private static int numbers =0;

public Car(String m,String c, int s) {

model=m;

color=c;

speed=s;

++numbers;

}

public static int getNumberOfCars() {

return numbers;

}

void print() {

System.out.println(model+color+speed);

}

}

class SportCar extends Car {

public SportCar(String m, String c, int s) {

super(m, c, s);

}

boolean turbo;

public void setTurbo(boolean flag) {

turbo = flag;

}

}

class CarTest{

public static void main(String[] args) {

Car c1=new Car("S600","white",80);

Car c2=new Car("E500","blue",60);

SportCar c3=new SportCar("P300","red",50);

int n = Car.getNumberOfCars();

System.out.println(n);

c1.print();

c2.print();

c3.print();

c3.setTurbo(true);

System.out.println(c3.turbo);

}

}

실행결과)

3

S600white80

E500blue60

P300red50

true

설명)

super(m,c,s) : 생성자 호출 방식 - 명시적인 호출

boolean turbo, void setTurbo() : 멤버 추가

부모 클래스의 private 멤버는 상속되지 않는다


▶ 패키지

서로 관련된 클래스들을 묶음

폴더와 비슷한 개념

같은 이름의 클래스를 여러개 만들 때 다른 패키지에 넣으면 구별 가능

다른 패키지에 있는 클래스를 사용하려면 import 해야한다


▶ 접근 제어(access control)

public class A {

private int a; //전용

int b;                 //디폴트

public int c;         //공용

}

public class Test {

public static void main(String args[]) {

A obj = new A();

  //obj.a=10; 전용멤버는 다른 클래스에서는 접근 안 됨

obj.b=20;         //디폴트 멤버 가능

obj.c=30;         //공용 멤버 가능

}

}


public 

 공용, 누구나 접근 가능

 private 

 전용, 같은 클래스 안에서만 접근 가능

 protected 

 자식 클래스만 접근 가능 (상속)

 없음 

 디폴트(default), 동일한 패키지 안에서만 접근 가능



▶ 정보 은닉(information hiding)

클래스 안의 데이터를 외부에서 마음대로 변경하지 못하게 한다


 

 메소드

 기능

필드

 접근자(getters)

 필드값 반환

 설정자(setters)

 필드값 설정


public class Account {

private int regNumber;

private String name;

private int balance;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;                //this : 생성된 객체 자신의 주소를 참조하는

}

public int getBalance() {

return balance;

}

public void setBalance(int balance) {

this.balance = balance;

}

}

public class AccountTest {

public static void main(String args[]) {

Account obj = new Account();

obj.setName("Tom");

obj.setBalance(100000);

System.out.println("이름은 "+obj.getName()+" 통장 잔고는 "+obj.getBalance());

}

}


-접근자와 설정자를 사용하는 이유

  1. 클래스를 업그레이드할 때 편하다
  2. 잘못된 값이 넘어오는 경우, 사전  차단할 수 있다
  3. 필요할 때마다 필드값을 계산하여 반환할 수 있다
  4. 접근자만을 제공하면 자동적으로 읽기만 가능한 필드를 만들 수 있다


▶ 생성자

클래스 이름과 동일하다

반환값을 가지지 않는다

생성자 이름 앞에 아무 것도 붙이지 않는다

주로 필드에 초기값을 부여할 때 사용된다

생성자는 객체를 만들 때 new 연산자에 의하여 호출된다

※만약 클래스가 생성자를 가지지 않는다면 자바에 의하여 제공되는 기본 생성자를 사용하기 때문에 어떤 클래스든지 생성자가 호출된다.

public class Car {

. . .

Car() {            //생성자

. . .

}

. . .

}


-매개변수를 갖지 않는 생성자

public class MyCounter {

int counter;

MyCounter( ) {            //생성자

counter =1;

}

}

public class MyCounterTest {

public static void main(String args[]) {

MyCounter obj1 = new MyCounter( );    //MyCounter() : 생성자 호출

MyCounter obj2 = new MyCounter( );

System.out.println("객체 1의 counter = "+obj1.counter);    //(실행결과) 객체 1의 counter = 1

System.out.println("객체 2의 counter = "+obj2.counter);    //(실행결과) 객체 2의 counter = 1

}

}


-매개변수를 가지는 생성자

public class MyCounter {

int counter;

MyCounter(int value) {

counter =value;

}

}

public class MyCounterTest {

public static void main(String args[]) {

MyCounter obj1 = new MyCounter(100);   

MyCounter obj2 = new MyCounter(200);   

System.out.println("객체 1의 counter = "+obj1.counter);    //(실행결과) 객체 1의 counter = 100

System.out.println("객체 2의 counter = "+obj2.counter);    //(실행결과) 객체 2의 counter = 200

}

}


▶ new 연산자

새로 생성된 객체를 가리키는 참조값을 반환한다

이 참조값은 참조변수에 저장된다


▶ 생성자 오버로딩

생성자를 여러개 정의할 수 있다, 매개변수는 다르게 해야한다

public class Student {

private int number;

private String name;

private int age;

private int score;

Student() {

number =100;

name= "New Student";

age = 18;

}

Student(int number, String name, int age) {

this.number=number;

this.name=name;

this.age=age;

}

Student(int score){

this.score=score;

}

void print() {

System.out.println(number+"/"+name+"/"+age+"/"+score);

}

}

설명) 생성자인 Student()의 매개변수를 다르게해서 3개를 만들었다

 

public class StudentTest {

public static void main(String args[]) {

Student obj1= new Student();

Student obj2= new Student(5,"tom",16);

Student obj3= new Student(60);

obj1.print();

obj2.print();

obj3.print();

}

}

실행결과)

100/New Student/18/0

5/tom/16/0

0/null/0/60

설명) obj1,obj2는 score를 초기화하지 않았기 때문에 자동 초기화값인 0이 출력됐다

obj3는 score를 뺀 나머지가 초기화되지 않아 각 각 0, null, 0으로 출력됐다



▶ 메소드 오버로딩(method overloading)

이름이 같은 메소드를 여러 개 정의하는 것, 매개 변수는 달라야 한다 (매개변수의 개수, 자료형)

public class MyMath {

int square(int i) {

return i*i;

}

int square (int i,int j) {

return i*j;

}

double square (double i) {

return i*i;

}

}

public class MyMathTest {

public static void main(String args[]) {

MyMath obj1 =new MyMath();

System.out.println(obj1.square(5));

System.out.println(obj1.square(5,6));

System.out.println(obj1.square(2.5));

}

}

설명) 변수이름이 같아도 상관 없고, 다만 매개변수의 개수와 자료형만 다르면 메소드 오버로딩 할 수 있다


▶ this

현재 객체를 나타냄

클래스에서 매개변수와 필드의 이름이 같을 때 this로 구별하여 사용


-this()

명시적인 생성자 호출

public class Rectangle {

private int x,y;

private int width,height;

Rectangle(){

this(0,0,1,1);

}

Rectangle(int x){

this(x,x,x);

}

Rectangle(int width, int height) {

this(0,0,width,height);

}

Rectangle(int x, int width, int height){

this(x,0,width,height);

}

Rectangle(int x, int y, int width, int height){

this.x=x;

this.y=y;

this.width=width;

this.height=height;

}

void print() {

System.out.println("좌표: ("+x+","+y+") 가로/세로길이: "+width+"/"+height);

}

}

class RectangleTest {

public static void main(String args[]) {

Rectangle rc1 = new Rectangle();

Rectangle rc2 = new Rectangle(5,6);

Rectangle rc3 = new Rectangle(2,3,4,5);

Rectangle rc4 = new Rectangle(7);

rc1.print();

rc2.print();

rc3.print();

rc4.print();

}

}

실행결과)

좌표: (0,0) 가로/세로길이: 1/1

좌표: (0,0) 가로/세로길이: 5/6

좌표: (2,3) 가로/세로길이: 4/5

좌표: (7,0) 가로/세로길이: 7/7


설명) 객체 rc4의 경우, 매개변수가 하나인 생성자 -> this(x,x,x)이므로 매개변수가 3개인 생성자 -> this(x,0,width,height)이므로 매개변수가 4개인 생성자 실행



▶ 객체(Object)

상태와 동작을 가짐

상태: 객체의 속성 ->변수->필드(field)

동작: 객체의 동작 ->함수->메소드(method)


▶ 필드(field)

멤버변수

▶ 메소드(method)

멤버함수

반환형 메소드이름(매개변수1,매개변수2,...)

{

문장

}

double add( double x, double y) //반환값을 double형으로

{

return x+y;    //return:반환

}

void print()    //void는 반환값이 없을 때

{

System.out.println("출력");

}



▶ 객체 지향 프로그래밍의 특징


①캡슐화(encapsulation)

알고리즘과 데이터를 하나로 묶음


②상속

기존의 코드를 재사용함


③다형성

동작이 상황에 따라서 달라지는 것


④추상화(abstraction)

중요한 정보만 표현


▶ 클래스(class)

설계도,틀

class 클래스이름 {

//필드

//메소드

 }


▶ 인스턴스(instance)

특정한 클래스로부터 만들어지는 각각의 객체를 그 클래스의 인스턴스라고 함

데이터가 저장됨


▶ 클래스 정의

public class Television {

int channel;    //필드 정의

int volume;    //필드 정의

boolean onOff;    //필드 정의

int volumeControl(int x) {    

return volume = volume+x;

}                                                    //int x: 매개변수

void print() {    

System.out.println("tv의 채널은 "+channel+"이고, 볼륨은 "+volume+"입니다.");       //메소드 정의

}                                                                                                                     

}


▶ 객체 생성

여러개의 객체를 생성할 수 있음

public class TelevisionTest {

public static void main(String args[]) {

Television tv = new Television();    //new 연산자를 사용하여 객체 생성, tv에 주소를 저장

tv.channel=7;    //멤버연산자 (.)으로 접근

tv.volume=8;

tv.onOff=true;

tv.print();

tv.volumeControl(5);        //5: 인수

tv.print();

}

}


▶ 멤버변수 자동 초기화

byte 

float 

0.0F 

short 

double 

0.0 

int 

char 

'\u0000'(보이지 않는 문자) 

long

0L 

boolean 

false 


▶ 참조 변수

배열,클래스,인터페이스의 객체를 참조할 때 사용되는 변수

참조변수에는 객체의 참조값이 저장, 참조값은 일반적으로 주소


▶ 참조 변수와 대입 연산

Television tv1 = new Television();

Television tv2 = tv1;    //tv1에 저장된 주소가 tv2에 복사되어 동일한 객체를 참조하게 됨

tv1.channel=7;    //7 저장

tv2.channel=8;    //8 저장(7->8로 바뀜) 

System.out.println(tv1.channel);    //tv1과 tv2는 같은 객체를 참조하기 때문에 8이 출력됨


▶ 히프 메모리(heap memory)

객체들은 히프 메모리에서 할당된다

히프 메모리는 컴퓨터에서 사용 가능한 메모리를 모아 놓은 곳이다

'개발 > Java' 카테고리의 다른 글

7일차 - 객체지향프로그래밍3 ,상속  (0) 2019.01.15
6일차 - 객체지향프로그래밍2  (0) 2019.01.09
4일차 - 제어문,문자열,배열  (0) 2019.01.07
3일차 - 기초 개념들3  (0) 2019.01.04
2일차 - 기초 개념들2  (0) 2019.01.02

▶ 제어문

①조건문 ②반복문


▶ 조건문


① if-else 문


if(조건식) {

문장;    //조건식이 참일 때 실행됨

문장;

}

else {

문장;    //조건식이 거짓일 때 실행됨

문장;

}

 

if(조건식) {

문장;

}

else if(조건식){

문장;

}

else if(조건식){

문장;

}

else {

문장;

}


-삼항연산자

간단한 if - else문일 때 쓸 수 있음


int x 99;

if(x%2==1) {

x=x*3+1;

}

else {

x=x/2;

}




int x = 99;

x = (x%2==1x*3+1 : x/2;



② switch문


switch(변수)

{

case c1:    //변수에 저장된 값과 c1이 일치할 때 실행

처리문장1;

break;    //switch문을 빠져나간다

case c2:    //변수에 저장된 값과 c2이 일치할 때 실행

처리문장2;

break;    //switch문을 빠져나간다

.

.

.

default:    //위가 모두 해당되지 않을 경우 실행

처리문장d;

break;    //switch문을 빠져나간다

}



▶ 반복문


① for문


for (초기식; 조건식; 증감식) { }


초기식: 변수 초기화, 변수 여러개 가능, 변수 선언과 동시에 해도 됨 ex1) int i =0, int sum =0 ex2) i=0

조건식: 수식 ex)i<5

증감식: ex)i++


-무한루프

for ( ; ; ) {

. . .

}


-초기식,증감식 없을 수 있음

int n=20;

for( ;n<253; ){    //초기식과 증감식이 없음, n<253일때까지 반복

n=n+17;

}


-NULL 문장 사용

for (i=0;i<10;i++)

;    //반복처리할 내용이 없을 때 세미콜론 사용


-중첩 반복문

for(i=0;i<5;i++) {   

for(j=0;j<5;j++) {

문장;

}

}



② while문


while(조건식)     //조건이 참이면 실행

{

문장;

}


-무한루프

while(true)

{    

문장;

}


- do-while문

do    // 실행한다

{

문장;

}while(조건);    //조건이 참이면 반복을 계속한다

문장이 적어도 한번은 실행되어야 하는 경우 사용하는 것이 좋다



▶ 반복문 종료

①break문 ②continue문

꼭 필요한 경우에 사용


▶ break문

-레이블이 있을 때

outer_loop:    //중첩 반복문을 모두 종료할 수 있는 레이블

while (조건식)

{

while(조건식)

{

문장;

if(조건식)

break outer_loop;    //중첩반복문을 빠져나온다

}

}


-레이블이 없을 때

break를 만나면 가장 안쪽 반복문을 빠져나온다


▶ continue문

continue를 만나면 가장 안쪽 반복문 처음으로 간다



▶ 문자열(String)


char형은 한 글자

String은 참조형 but new 키워드를 사용하지 않고 생성할 수 있어 기본형처럼 사용한다

참조형이기 때문에 메소드를 갖고 있다


String city1="Asia";

String city2="Europe";

city2=city1;        //대입, city2="Asia"

System.out.println(city1.length());    //글자수세기 메소드 : length()

String city3=String.format("%s like %s",city1,city2);    //포맷만들기 메소드 :format(" ", )

System.out.println(city3);        //(실행결과) Asia like Asia

String city4 = city1+", "+city3;

System.out.println(city4);        //(실행결과) Asia, Asia like Asia 



▶ 배열(array)

동일한 타입(형)의 데이터를 여러 개 저장할 수 있는 저장 장소

변수에는 배열이 저장된 주소가 저장된다

int[ ] s = new int[10]; // 크기가 10인 배열 생성


or


int[ ] s;

s = new int[10];


▶ 배열의 초기값

숫자 : 0, 0L, 0.0F, 0.0

문자 : null

논리 : false


▶ 배열 초기화


- new 키워드를 사용하지 않는 배열

다시 생성, 다시 초기화가 불가능하다

int[ ] a = {1,2,3};

a[0] = 5;    //a={5,2,3}


- new 키워드를 사용한 배열

길이 변경, 다시 생성, 다시 초기화 가능하다

String[ ] lotto = new String[6];    //크기가 6인 배열

lotto[0] ="abcde";    //0번째 인덱스에 "abcde"을 저장

lotto = new String[] {"seoul","busan","daejun"};    //다시 생성하면서 초기화

lotto[1]="new york";    // lotto = {"seoul","new york","daejun"}


▶ 메소드에 배열을 전달

public static int sum(int[] numbers) {

int total =0;

for(int i =0; i<numbers.length;i++)    //배열은 length필드를 갖고있다 배열의 크기를 나타낸다

total = total + numbers[i];

return total;

}


public static void main (String args[]){

a=sum(new int[ ] {1,2,3})    //꼭 초기값을 갖는 배열, new 키워드

}


▶ 배열 복사1

int [] list = {10,20,30,40,50};

int [] num = list;    //주소가 복사된다

num[2] =90;    //같은 배열을 두 변수가 참조하고 있기 때문에 list[2]=90이 된다


-배열 복사2

int [] list = {10,20,30,40,50};

int [] newlist = new int[10];

for(int i=0;i<list.length;i++)

{

newlist[i] = list[i];    //값을 복사한다 , newlist={10,20,30,40,50,0,0,0,0,0}

}



▶ 2차원 배열


int[ ][ ] s = new int[3][5];


  s[0][0] 

  s[0][1]

  s[0][2]

  s[0][3]

  s[0][4]

  s[1][0]

  s[1][1]

  s[1][2]

  s[1][3]

  s[1][4]

  s[2][0]

  s[2][1]

  s[2][2]

  s[2][3]

  s[2][4]


- 2차원 배열 초기화

같은 행의 요소를 중괄호로 묶는다

int[][] a= {

{10,20,30},

{40,50,60},

{70,80,90}

};


-2차원 배열 length필드

전체적으로 하나의 length필드가 있고 행의 개수를 나타냄

각 행마다 length필드가 있고 각 행의 열의 개수를 나타냄

for (int r=0; r<a.length; r++) {

for(int c=0; c<a[r].length; c++) {

System.out.println(r+"행"+c+"열: "+a[r][c]);    // 0행0열: 10 ... 2행2열: 90

}

}


▶ 다차원 배열

double[][][] sales = new double[3][2][2];


'개발 > Java' 카테고리의 다른 글

6일차 - 객체지향프로그래밍2  (0) 2019.01.09
5일차 - 객체지향 프로그래밍  (0) 2019.01.08
3일차 - 기초 개념들3  (0) 2019.01.04
2일차 - 기초 개념들2  (0) 2019.01.02
1일차 - 기초 개념들  (0) 2018.11.18

▶ 수식


일반적으로 상수,변수,연산자의 조합

개별적으로도 수식이라고 함 (상수만, 변수만)

수식은 항상 결과값을 가짐


int x=10;

int y=20;

int sum = x+y;


▶ 연산


-대입 연산

대입 연산자 : =

값을 변수에 저장(대입)


-산술 연산

 연산자

의미 

예 

더하기 

x+y 

빼기 

x-y 

곱하기 

x*y 

몫 

x/y 

나머지 

x%y 


-관계 연산

연산자 

의미 

예 

== 

x와 y가 같은가? 

x == y 

!= 

x와 y가 다른가? 

x != y 

x가 y보다 큰가? 

x > y 

x가 y보다 작은가? 

x < y 

>= 

x가 y보다 크거나 같은가? 

x >= y 

<= 

x가 y보다 작거나 같은가? 

x <= y 


-논리 연산

연산자 

의미 

예 

&& 

AND 연산, x와 y가 모두 참이면 참, 그렇지 않으면 거짓

x && y 

||

OR 연산, x나 y중 하나만 참이면 참, 모두 거짓이면 거짓  

x || y 

NOT 연산, x가 참이면 거짓, x가 거짓이면 참 

!x 


-비트 연산 ...


▶ 형변환 (type conversion)


-자동 형변환


byte -> short ->

int -> long -> float -> double

char -> 


예를 들어 double형은 (byte~float)형보다 더 많은 수를 표현할 수 있기 때문에 

(byte~float)형에서 double형으로의 형변환이 가능함


ex)


float d =23;     // d=23.0F

int a = 21;     // a=21

double c = a+d;    //a는 d와 같은 float형으로 변환, a:21.0F, a+d:44.0F , a+d가 c에 대입될때 double형으로 변환, c:44.0


ex)


char a = 'c';

System.out.println(a);    //(실행결과) c

double b = a;    //아스키에 해당하는 문자를 숫자로 변환한다

int c = a;    //아스키에 해당하는 문자를 숫자로 변환한다

System.out.println(b);    //(실행결과) 99.0

System.out.println(c);    //(실행결과) 99


-강제적인 형변환


(변환할 자료형) 수식;


ex)

double f;

f= 5/4;    //정수끼리 연산이므로 5/4=1, 1이 double형으로 대입될 때 자동 형변환이 일어나서 f:1.0

f= (double)5/4;    //5가 double형으로 강제 형변환이 일어나서 4 연산하기 위하여 4도 double형으로 자동 형변환, 5.0/4.0=1.25, f: 1.25




'개발 > Java' 카테고리의 다른 글

6일차 - 객체지향프로그래밍2  (0) 2019.01.09
5일차 - 객체지향 프로그래밍  (0) 2019.01.08
4일차 - 제어문,문자열,배열  (0) 2019.01.07
2일차 - 기초 개념들2  (0) 2019.01.02
1일차 - 기초 개념들  (0) 2018.11.18

▶ 변수(variable)


데이터를 담아두는 상자, 데이터 저장

변수를 사용하려면 먼저 변수 선언을 함


▶ 변수 선언


자료형 변수이름;

자료형 변수이름 = 값 ;


int value;

int idx = 9;


▶ 변수 초기화

변수 선언을 한 후 초기화하지 않고 사용하면 오류 발생


▶ 자료형(data type)


상자의 종류와 크기


▶ 자료형의 종류


→ 기초형 (실제 값 저장)

-정수형 : byte, short, int, long

-실수형 : float, double

-논리형 : boolean

-문자형 : char


→ 참조형 (실제 객체를 가리키는 주소 저장)

-클래스

-인터페이스

-배열

-문자열 (기본형처럼 사용)


▶ 정수형

자료형 

크기 

최소값

최대값 

 byte

1바이트 

-128 

127 

 short

2바이트 

-32768 

32767 

 int

4바이트 

-2147483648 

2147483647 

 long

8바이트 

-9223372036854775808 

9223372036854775807 


▶ 최소값과 최대값을 알아내기

Byte.MIN_VALUE

Byte.MAX_VALUE

Short.MIN_VALUE

Short.MAX_VALUE

Integer.MIN_VALUE

Integer.MAX_VALUE

Long.MIN_VALUE

Long.MAX_VALUE


▶ 정수형 리터럴


리터럴: x=100; 에서 100과 같은 값을 의미함


10진수

8진수 : 앞에 0을 붙임

16진수 : 앞에 0x를 붙임

2진수 : 앞에 0b를 붙임


기본적으로 정수형 리터럴은 int형으로 저장

아주 큰 수를 다룰때, 값의 끝에 L를 붙여서 long형으로 저장


int x = 025;

System.out.println(x);


(실행결과)

21


▶ 부동소수점형


데이터형 

크기(비트) 

범위 

float 

32

약 

double

64

약 

대부분의 경우 double형을 사용

메모리 용량이 제한될 때 float형 사용


▶ 부동소수점형 리터럴


일반 표기법 

지수 표기법 

146.91 

1.4961E + 2 

0.00081 

8.1E - 4 

1800000 

1.8E + 6 


기본적으로 double형으로 저장

float형은 끝에 F를 붙임


float temperature = 12.3F // OK

float temperature = 12.3 // 오류


▶ 문자형


자료형 char 크기(비트) 16비트 

유니코드 문자


char ch1 = '가';


▶ 문자형 리터럴


단일 따옴표를 사용하여 표시

'a' , 'b' , '가' , '나' 등


특수문자는 역슬래쉬를 사용하여 나타냄

\n (역슬래쉬 n) : 새로운 줄 삽입


▶ 논리형


boolean 

논리 연산을 수행할 때 참과 거짓을 나타냄

값 : true/false


System.out.println(5>4)


(실행결과)

true


▶ 상수(constant)

기호상수로 나타내어 다른 사람이 변경하지 못하게 한다

final 키워드를 이용

상수이름은 모든 글자를 대문자로 한다 _를 사용한다

메소드 외부에 정의하면 클래스 안의 모든 메소드가 사용할 수 있다


public class Constant {

public static final double KM_PER_MILE = 1.609344;

public static double kiloMetre(double a) {

return a*KM_PER_MILE;

}

public static void main(String args[]) {

System.out.println(KM_PER_MILE);

System.out.println(kiloMetre(1.55));

}


(실행결과)

1.609344

2.4944832000000003


▶ 식별자


종류 

사용 방법 

예 

클래스명 

각 단어의 첫글자는 대문자로 한다 

StaffMember, ItemProducer 

변수명, 메소드명 

첫번째 단어는 소문자로 시작되어 2번째 단어부터 첫글자는 대문자로 한다 

width, payRate,

getMonthDays(),fillRect() 

상수 

모든 글자를 대문자로 한다 

MAX_NUMBER 




'개발 > Java' 카테고리의 다른 글

6일차 - 객체지향프로그래밍2  (0) 2019.01.09
5일차 - 객체지향 프로그래밍  (0) 2019.01.08
4일차 - 제어문,문자열,배열  (0) 2019.01.07
3일차 - 기초 개념들3  (0) 2019.01.04
1일차 - 기초 개념들  (0) 2018.11.18

◆ 클래스(class)

객체를 생성하는 설계도


◆ 클래스 작성 방법


public class Hello {


}


public : 접근지정자, 누구나 사용 가능

class : 클래스 선언

Hello : 클래스 이름


◆ 클래스 이름 짓기

클래스 이름을 이루는 단어의 첫 번째 글자를 대문자로 함

ex) MyFirstProgram


◆ 메소드(method)

외부로부터 입력을 받아서 작업을 수행하고 결과값을 반환함

클래스 안에 정의함


◆ 메소드 작성방법


public void draw( ) {


}


public : 접근지정자, 누구나 사용 가능

void : 결과값을 반환하지 않음

draw( ) : 메소드 이름, ( ) 을 뒤에 꼭 씀


◆ main( ) 메소드

하나의 자바 프로그램에는 main() 메소드를 갖고 있는 클래스가 반드시 하나 있어야 함.

main() 메소드에서 자바 프로그램의 실행이 시작됨


public static void main(String args[]) {


}


public : 접근지정자, 누구나 사용 가능

static : 정적 메소드, 객체를 생성하지 않아도 실행됨, main( ) 메소드를 실행하기 위해서 필수

void : 결과값을 반환하지 않음

String args[] : 매개변수, 외부에서 주어지는 데이터를 받음


◆ 문장

메소드 안에 문장이 있음

사용자가 컴퓨터에게 작업을 지시하는 단위

문장 맨 끝에 ;(세미콜론)을 씀

순차적으로 문장이 실행됨


System.out.println("Hello World!");


◆ 주석

/* text */

// text

'개발 > Java' 카테고리의 다른 글

6일차 - 객체지향프로그래밍2  (0) 2019.01.09
5일차 - 객체지향 프로그래밍  (0) 2019.01.08
4일차 - 제어문,문자열,배열  (0) 2019.01.07
3일차 - 기초 개념들3  (0) 2019.01.04
2일차 - 기초 개념들2  (0) 2019.01.02

+ Recent posts