✅네이버클라우드 캠프/개발일기

[네이버클라우드캠프] 23일차. 자바기초 리터럴 & 보수 자바실습 gitignore, gradle UTF-8 실행

우동한그릇 2023. 5. 25. 18:14
반응형

 

 

* literal (리터럴) : 데이터 표기

문자열 →  "홍길동",  '홍길동' 문법오류  |  "홍" ← 문자열  / " " ← 빈문자열

문자 →  '홍' , '홍길동' 문법오류

 


숫자             → 정수→ 4 byte 10 (4byte 메모리 사용) ← 주소 사용 약 -21억 ~ +21억

                                → 8 byte (10L (8byte 메모리 사용)  ← -922경 ~ 922경

        → 부동소수점 → 4byte 10f (4byte 메모리 사용), 10.2f, 3.14f   -? ~ +? 유효자릿수 6~7자리 소수점을 제외한 숫자

                                → 8byte 10.2 (8byte 매모리 사용), 10.20/10.2d

 

논리  → true,false (int크기, 4byte 메모리 사용) 단 배열일 경우 1byte 메모리 사용

 


System.out.println("홍길동");

System : 삼자 = 클래스 (class)

out : 도구 = 객체 = object = instance

println : 기능(function) = 메서드 (method)

("홍길동") : 기능 수행에 필요한 값 = argument = 파라미터(parameter)

 


* 정수 리터럴 과 부동소수점(float)  

부동1, 浮動
명사
떠서 움직이는 것.
 

78 ← 10진수

0116 ← 8진수

 

0X4E ← 16진수

0X4E ← 16진수

    ↓

0601001110 ← 2진수

0B01001110 ← 2진수

 

floating point 소수점이 둥둥 떠다닌다.  (부동)

3.14 ← 일반 표기법

   ↓

31.4e-1 * 10^-1

31.4e-1  * 10^-2

   ↓

314e-2 = 314 * 10^-2

   ↓

0.314e1 = 0.314 * 10^1

0.0314e2 = 0.0314 * 10^2 


* 문자 리터럴

'가' → '\nACOD

escape character , 유니코드

 

'A' → '\u0041'   '\041'

 

"\uACOD나다" = "가나다"

문자열 안에 유니코드 표기법을 삽입할 수 있다.

 


* 데이터 → 전기 신호 : 정수

① sign-Magnitude 방식

 

                           128 64 32 16 8 4 2 1  

-24 (10진수)      1    0   0   0  1 0 0 0 

+24 (10진수)     0    0   0   0  1 0 0 0 

 

- 장점
  - 이해하기 쉽다!

 

 단점
  - 두 개의 0(+0, -0)이 존재한다.
  - 양수와 음수를 더했을 때 옳지 않은 값이 나온다.
     예) 4비트일 경우, 1 + -1 = ?
         0001(+1) + 1001(-1) = 1010 (-2) <-- 계산 결과가 옳지 않다.
  - 빼기를 처리하는 컴퓨팅 회로를 별도로 설계해야 하므로 하드웨어가 복잡해진다.

 

 

② 1의 보수(Ones' Complement)


- 모든 비트를 반대 값으로 바꾼다.
  예) +24 => 0001 1000

  예) -24 => 1110 0111

- 단점
  - 두 개의 0(+0, -0)이 존재한다.
  - 두 수를 더한 후 비트 크기를 초과한 1 값을 다시 맨 뒤에 더해야만 옳은 값이 된다.
    

예) 4비트일 경우,
       0001(+1)
       1110(-1)
       --------
       1111(-0) <--- 음수 0과 양수 0을 다뤄야 하는 것이 번거롭다.

       0101(+5)
       1100(-3)
       --------
     1 0001(1) <--- 옳지 않은 값.
     +    1    <--- 4비트를 초과하는 값을 다시 맨 뒤에 더함.
     ---------
       0010(2) <--- 옳은 값!


③ 2의 보수(Two's complement)

현대 컴퓨터는 모두 2의 보수 방식으로 정수를 다룬다.


자바에서 음수를 저장하는 방법이다.
- 1의 보수의 문제점을 해결하기 위해 등장한 방법.
- 음수 0을 없앰으로써 -128까지 표현할 수 있음.
- 2의 보수를 만드는 방법 1:
  - 모든 비트를 반대 값으로 만든 다음 1을 더한다.
  예) 0010 1001(+41)
      1101 0110(1의 보수)
              1
      ---------
      1101 0111(-41)
- 2의 보수를 만드는 방법 2:
  - 오른쪽에서부터 1을 찾는다.
  - 찾은 1의 왼쪽편에 있는 모든 비트를 반대 값으로 바꾼다.
    예) 0010 1001(41) => 1101 0111(-41)
                ^                ^
    예) 0010 1100(44) => 1101 0100(-44)
              ^                ^
- 2의 보수를 만드는 방법 3:
  - 2^n(8비트일 경우 2^8 = 256)에서 음수 값 만큼 뺀다.
    예) -41 => 256 - 41 = 215 = 1101 0111
    예) -44 => 256 - 44 = 212 = 1101 0100
- 수의 범위(8비트 기준): -128 ~ +127
   0111 1111 (127)
   0111 1110 (126)
   0111 1101 (125)
      ...
   0000 0010 (2)
   0000 0001 (1)
   0000 0000 (+0)
   1111 1111 (-1)
   1111 1110 (-2)
      ...
   1000 0011 (-125)
   1000 0010 (-126)
   1000 0001 (-127)
   1000 0000 (-128)
- 장점
  - 양수와 음수의 덧셈이 가능하다.
  - 음수 0이 없다. 0에 대한 표현이 한 가지이다.

 

④ K-초과(Excess-K)


부동 소수점의 지수부(exponent)를 저장할 때 사용한다.
- 오프셋 바이너리(offset binary) 또는 바이어스된 표기법(biased representation) 이라고도 한다.
- K를 바이어스 값이라 부르며, 표현하려는 값에 더할 때 사용한다.
    표현하려는 값 + 초과 값(K) = 결과
- 바이어스 값(K)을 구하는 공식:
    K = 2^(비트수 - 1)

 

 

- IEEE 부동소수점 표준에서는 다음의 공식을 사용한다.
    K = 2^(비트수 - 1) - 1
  예) 8비트일 경우 ---> K = 2^7 - 1 = 127, 결과 = 127 + 값
   1111 1111 = 127 + 128
   1111 1110 = 127 + 127
   1111 1101 = 127 + 126
   1111 1100 = 127 + 125
      ...
   1000 0000 = 127 + 1
   0111 1111 = 127 + 0
   0111 1110 = 127 + (-1)
      ...
   0000 0010 = 127 + (-125)
   0000 0001 = 127 + (-126)
   0000 0000 = 127 + (-127)

 


* 데이터 → 전기신호 : 부동소수점

12.375 => 1100.011 => 정규화 : 소수점 왼쪽에 한 개의 1만 남도록 변경

 

12 => 1100

 

0.375 * 2 = 0.75 = 0

0.75 * 2 = 1.5 = 1

0.5 * 2 = 1.0 = 1

0.375 => 011 

 

1100.011

 

앞자리를 소수점 첫번째로 바꾸어줌

1100.011 * 10^3 이므로,

1.100011 * 2^3 이됨.

 

2^3 은 8bit k초과로 계산

8bit = 2^7 - 1 = 127

3 + k = 130

 

130 => 10000010 (2진수)

 

 5) 32비트로 표현하기
   [0][10000010][10001100000000000000000]
   => 0100_0001_0100_0110_0000_0000_0000_0000
   => 0x41460000

 

 


https://dev-with-gpt.tistory.com/74

 

자바 gitignore, gradle UTF-8 실행하기

git 허브에 push 할 때 gitingnore 을 설정해주기 https://www.toptal.com/developers/gitignore gitignore.io Create useful .gitignore files for your project www.toptal.com Java 웹프로젝트를 할 때 위와 같이 기본적으로 gitignore 을

dev-with-gpt.tistory.com

 

 

git 허브에 push 할 때 gitingnore 을 설정해주기

 

https://www.toptal.com/developers/gitignore

 

gitignore.io

Create useful .gitignore files for your project

www.toptal.com

 

Java 웹프로젝트를 할 때 위와 같이 기본적으로 gitignore 을 생성하여

github에 Class 파일 등이 업로드 되지 않게 해주는 것이 목적이다.

class 파일을 github에 업로드 하는 것이 권장되지 않는 이유는 다음과 같다.

 

가독성: 클래스 파일은 이진 형식이기 때문에 사람이 직접 읽기 어렵습니다. 따라서, 다른 개발자나 협업자가 클래스 파일을 이해하고 변경하기 어려울 수 있습니다. 소스 코드를 공유하면 다른 개발자들이 코드를 이해하고 수정할 수 있으며, 코드 리뷰나 협업이 원활하게 이루어질 수 있습니다.

보안: 클래스 파일은 실행 가능한 파일이므로 민감한 정보나 알고리즘 등이 포함될 수 있습니다. 이러한 정보가 공개되면 보안상의 문제가 발생할 수 있습니다. 소스 코드를 공개하고 필요한 보안 조치를 적용하는 것이 좋습니다.

빌드 환경 의존성: 클래스 파일은 특정 환경에서 컴파일된 코드이므로, 다른 환경에서 실행될 수 없을 수 있습니다. 개발자들은 소스 코드를 컴파일하여 각자의 빌드 환경에 맞는 실행 가능한 파일을 생성해야 합니다.

 

※ 단, 이미 올라간 데이터는 절대 완전 삭제할 수 없다. 중요한 정보가 포함된 파일이라고해도 

    지정된 위치에 히스토리에는 반드시 존재하게된다. git은 조작을 못하게 하는 것이 목표이다.

 

 

위 사진과 같이 설정하여 생성해주면 다음과 같이 코드가 출력된다.

 

# Created by https://www.toptal.com/developers/gitignore/api/java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node
# Edit at https://www.toptal.com/developers/gitignore?templates=java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node

### C++ ###
# Prerequisites
*.d

# Compiled Object files
*.slo
*.lo
*.o
*.obj

# Precompiled Headers
*.gch
*.pch

# Compiled Dynamic libraries
*.so
*.dylib
*.dll

# Fortran module files
*.mod
*.smod

# Compiled Static libraries
*.lai
*.la
*.a
*.lib

# Executables
*.exe
*.out
*.app

### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders

# External tool builders
.externalToolBuilders/

# Locally stored "Eclipse launch configurations"
*.launch

# PyDev specific (Python IDE for Eclipse)
*.pydevproject

# CDT-specific (C/C++ Development Tooling)
.cproject

# CDT- autotools
.autotools

# Java annotation processor (APT)
.factorypath

# PDT-specific (PHP Development Tools)
.buildpath

# sbteclipse plugin
.target

# Tern plugin
.tern-project

# TeXlipse plugin
.texlipse

# STS (Spring Tool Suite)
.springBeans

# Code Recommenders
.recommenders/

# Annotation Processing
.apt_generated/
.apt_generated_test/

# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet

# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project

### Eclipse Patch ###
# Spring Boot Tooling
.sts4-cache/

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# SonarLint plugin
.idea/sonarlint/

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr

# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/

# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml

# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/

# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$

# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml

# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml

### Java ###
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*

### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### macOS Patch ###
# iCloud generated files
*.icloud

### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar

# Eclipse m2e generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath

### Node ###
# Logs
logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### Node Patch ###
# Serverless Webpack directories
.webpack/

# Optional stylelint cache

# SvelteKit build / generate output
.svelte-kit

### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets

# Local History for Visual Studio Code
.history/

# Built Visual Studio Code Extensions
*.vsix

### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide

### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

### Gradle ###
.gradle
**/build/
!src/**/build/

# Ignore Gradle GUI config
gradle-app.setting

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar

# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties

# Cache of project
.gradletasknamecache

# Eclipse Gradle plugin generated files
# Eclipse Core
# JDT-specific (Eclipse Java Development Tools)

### Gradle Patch ###
# Java heap dump
*.hprof

# End of https://www.toptal.com/developers/gitignore/api/java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node

 

위 코드를 .gitignore 파일 안에 전체 붙여넣기 해주면 된다.

 

 

적용 후 자동으로 Hello.class 파일이 회색으로 변하면 성공적으로 gitignore이 적용 된 것이다.

 

 

git push 명령어를 통해서 github에 업로드 해보았다. 

 

 

repo를 확인해보면 .class 파일은 업로드 되지 않은 것을 확인할 수 있다.

 

 

요약하자면, github에 push 할 때 class 파일은 보안 및 가독성의 이유로 포함되지않게 해주어야하며

.gitignore 설정 파일에 toptal 사이트에서 받은 코드를 추가해줌으로써 적용할 수 있고, 이를 확인해보았다.

 

혹시 오류가 나타나는 경우 !

 

git clone 은 원격 저장소를 로컬로 복제하는 명령이다. 

이때 , 원격저장소에 readme file이 있거나 다른 파일이 이미 존재해서 오류가 나오는 경우가 발생했다.

아래와 같이 명령어를 입력해주어 해결했다.

 

git push -f origin main

 

해당 명령어를 통해 강제로 원격 저장소에 푸시하는 명령어를 통해서 덮어쓰기해주게된다.

단, 중요한 파일은 백업해두어야한다. (사실 무언가 더 좋은 방법이 있을 거라 생각한다.)

 

git pull origin main

 

원격저장소와 clone으로 연결되어있을 때 업데이트 해주는 방법.

여기서 반드시 원격저장소와 폴더 경로가 일치해야한다.

 

 


VScode JAVA Tab키 간격 적용이 안될 때 !

 

settings 에서 indentation 을 검색하고 체크를 해제하여 Java 에서 탭키를 스페이스바 두번으로 바꿔줄 수 있다.

 


Gradle run 으로 java 파일 컴파일 없이 바로 실행시켜보기

App.java 파일 만들기

 

App.java 코드를 작성하고 App.java  파일을 만들어준다.

 

package bitcamp.myapp;

public class App {
  public static void main(String[] args) {
    System.out.println("나의 목록 관리 시스템");
    System.out.println("----------------------");

    System.out.println("번호: ");
    System.out.println("100");

    System.out.printf("이름: %s\n", "홍길동");
    System.out.println();

    System.out.println("나이: " + 20);

    System.out.printf("재직자: %b\n", true);

    System.out.printf("성별(남자(M), 여자(W)): %c\n", 'M');

    System.out.printf("좌우시력: %.1f, %.1f\n", 1.5f, 1.0f);
  }
}

 

 

grand init 과 buid 적용하기

https://dev-with-gpt.tistory.com/71

 

자바 웹프로그래밍 Git clone, Gradle, 컴파일 실행

* Git clone 명령어 "git clone"은 Git 버전 관리 시스템에서 원격 저장소의 프로젝트를 로컬 환경으로 복제하는 명령어 Git을 사용하여 프로젝트를 공유하고 협업하기 위해 중앙 원격 저장소에 프로젝

dev-with-gpt.tistory.com

gradle이 성공하였다면 buid.gradle이 myapp에 생성되었을 것이다.

windosw에서는 기본적으로 UTF-8 실행이 지원되지 않기 때문에

build.gradle 에 아래 코드로 변경해서 적용해주어야한다.

 

plugins {
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'

    implementation 'com.google.guava:guava:31.1-jre'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

application {
    mainClass = 'bitcamp.myapp.App'
}

tasks.named('test') {
    useJUnitPlatform()
}

// 자바 소스를 컴파일 할 때 적용할 옵션
tasks.withType(JavaCompile) {
    // 프로젝트의 소스 파일 인코딩을 gradle에게 알려준다.
    // $javac -encoding UTF-8 ..
    options.encoding = 'UTF-8' 

    // 소스 파일을 작성할 때 사용할 자바 버전
    sourceCompatibility = '17'

    // 자바 클래스를 실행시킬 JVM의 최소 버전
    targetCompatibility = '17'
}

 

gradl -q run 으로 작동시켜보면 성공적으로 출력되는 것을 확인할 수 있다.

 

 

반응형