core java 따라하기 - 1
2017. 6. 13. 18:27ㆍJava
미안합니다.. 전 이렇게 한번씩 써봐야 이해를 하는 바보라서....
Section 1. About Core Java
이 Refcard는 가장 일반적으로 사용되는 툴들(Javac, java, jar) 뿐만 아니라 Java 언어의 주요 측면과
핵심 라이브러리의 치트 시트(formartted output, collections, regular expressions, logging, properties) 들의 개요를 여러분에 제공합니다.
Session 2. Java Keywords
keyword | description | example |
abstract | an abstract class or method | abstract class Wriable{ public abstract void write(Writer out); public void save(String filename){...} } |
assert | with assertions enabled, throws an error if condition not fulfilled | assert param != null; Note:Run with -ea to enable assearions |
boolean | The Boolean type with values true and false | boolean more = false; |
break | breaks out of a switch or loop | while((ch = in.next()) ! = -1){ if(ch == '\n\) break; process(ch); } Note : Also see switch |
byte | the 8-bit integer type | byte b = -1; // Not the same as oxFF Note : Be carefuel with bytes < 0 |
case | a case of a switch | see switch |
catch | the clause of a try block catching an exception | see try |
char | the Unicode character type | char input ='Q'; |
class | defines a class type | class Persion{ private String name; public Persion(String aName){ this.name = aName; } public void print(){ System.out.println(name); } } |
continue | continues at the end of a loop | while((ch = in.next()) != -1){ if(ch =='') continues; process(ch); } |
default | 1) the default clause of a switch 2) denotes default implementation of an interface method | 1) see switch 2) public interface Collection<E>{ @Override default Spliterator<E> spliterator(){ return Spliterator.spliterator(this, o); } } |
do | the top of a do/ while loop | do{ ch = in.next(); }while(ch == ''); |
double | the double-precistion floating-number type | double oneHalf = 0.5; |
else | the else clause of an if statement | see if |
enum | an enummerated type | enum Mood{SAD,HAPPY}; |
extends | defines the parent class of a class | class Student extends Person{ private int id; public Student{String name, int anId){....} pubilc void print{....} } |
final | a constant, or a class or method that cannot be overridden | public static final int DEFAULT_ID = 0; |
finally | the part of a try block that is always executed. | see try |
float | the single-precision floating-point type | float oneHalf = 0.5F; |
for | a loop type | for(int i = 10;i >= 0 ; i==) System.out.println(i); for(String s : line.split("\\s+")) System.out.println(s); Note : In the "generalized" for loop, the expression after the : must be an array or an Iterable |
if | a conditional statement | if(input == 'Q') system.exit(0); else more = true; |
implements | defines the interface(s) that a class implements | class Student implements Printable{ ....} |
import | imports a package | import java.util.ArrayList; import com.test.tests.*; |
instanceof | tests if an object is an instance of a class | if(fred instanceof Student) value = ((Student)fred).getId(); Note : null instanceof T is always false |
int | the 32-bit integer type | int value =0; |
interface | an abstract type with methods that a class can implement | interface Printable{ void print(); } |
long | the 64-bit long integer typpe | long worldPopulation = 6710044745L; |
native | a method implemented by the host system | |
new | allocates a new object or array | Person fred = new Person("Fred"); |
null | a null reference | Person optional = null; |
package | a package of classes | package com.test.tests; |
private | a feature that is accessible only by methods of this class | see class |
protected | a feature that is accessible only by methods of this class, its children, and other classes in the same package | class Student{ protected int id;...} |
public | a feature that is accesible by methods of all classes | see class |
return | returns from a method | int getId(){ return id; } |
short | the 16-bit integer type | short skirtLength = 24; |
static | a feature that is unique to its class, not to objects of its class | public class WriteUtil{ public static void write(Writable[] ws, String filename); pubilc static final String DEFAULT_EXIT = ".dat"; } |
strictfp | Use strict rules for floating-point computations | |
super | invoke a superclass constractor or method | public Student(String name, int anId){ super(name); id = anId; } public void print(){ super.print(); System.out.println(id); } |
switch | a selection statement | switch(ch){ case 'Q': case 'q' : more= false; break; case ''; break; defeault: process(ch); break; } Note : If you omit a break, processing continues with the next case. |
synchronized | a method or code block that is atomic to a thread | public synchronized void addGrade(String gr){ grades.add(gr); } |
this | the implicit argument of a method, or a constructor of this class. | public Student(String id){ this.id = id; } public Student(){ this(""); } |
throw | throws an exception | if(param ==null) throw new IllegalArgumentException(); |
throws | the exceptions that a method can throw | public void print() throws PrinterException, IOException |
transient | marks data that should not be persistent | class Student{ private transient Data cachedData;... } |
try | a block of code that traps exceptions | try{ try { fred.print(out); }catch(PrintException ex){ ex.printStackTrace(); } }finally{ out.close(); } |
void | denotes a method that returns no value | public void println(){...} |
volatile | ensures that a field is coherently accessed by multiple threads | class Student{ private volatile int nextId; .... } |
while | a loop | while(in.hasNext()) process(int.next()); |
session 3 Standard Java Packages
java.applet | Applets (Java Programs that run inside a web page) |
java.awt | Graphics and graphical user interfaces |
java.beans | Support for JavaBeans components(classes with properties and event listeners) |
java.io | Input and output |
java.lang | Lanaguage support |
java.math | Arbitrary-precision numbers (In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system.) arbitrary : 수의의, 임의의 | precision : 정밀한 | arithmetic 산술,산수 |
java.net | Networking |
java.nio | "New" (memory-mapped) I/O |
java.rmi | Remote method invocations |
java.security | Security support |
java.sql | Database support |
java.text | Internationalized formatting of text and numbers |
java.time | Dates, time, duration, time zones, etc. |
java.util | Utilities (including data structures, concurrency, regular expressions, and logging) |
session 4 Operator Percedence (연산자 순위 관계)
Operators with the same precedence | notes | |
[] . () (method call) | Left to Right | |
! ~ ++ -- + (unary) - (unary) () (cast) new | Right to Left | ~flips each bit of a number. unary : 단일체, 1진법의 / flip : 튀기다 튀겨올리다 |
* / % | Left to Right | Be careful when using % with negative numbers. -a % b == -(a%b) , but a % -b == a % b. For example, -7 % 4 == -3 , 7% -4 == 3 |
+ - | Left to right | |
<< >> >>> | Left to right | >> is arithmetic shift ( 산술자리이동, n >> 1 == n/2 for positive and negative numbers), >>> is logical shift (adding o to the highest bits). The right hand side is reduced modulo 32 if the left hand side is an int or modulo 64 if the left hand side ia s long. For example , 1 << 35 == 1 << 3 arithmetic shift : 마이크로 프로세서가 지니는 기능의 하나로, 산술 연산시에 사용되는 명령, 평소에 사용되는 10진수는 오른쪽 끝에 0을 붙이면 원래 숫자의 10배가 되고, 마찬가지로 오른쪽 끝의 0을 떼면 10분의 1이 된다. 이것은 아날로그 컴퓨터에서 사용되고 있는 2진수의 경우도 마찬가지로, 각각 2배, 2분의 1배가 된다. 주의해야 할 점은 음의 수의 표시 법으로써 최상위 비트, 즉 b7을 부호 비토로서 사용하고 있으므로 이 명령이 필요하다는 점이다. Logical shift : 데이터를 오른쪽(또는 왼쪽)으로 직렬로 이동시키고, 이동시킨 후에는 0을 넣는 것. 2진수를 n회 왼쪽으로 논리 시프트 하면 원래의2진수를 2^n 배 할 수 있다. 피연산자를 부호 붙인 수치 또는 문자 표시로써가 아니고 일련의 비트로서 취급하는 자리 이동 조작. Rotate left : The leftmost 1 was moved to the rightmost position. Logical shift Right : The rightmost 1 was dropped and a 0 was added in the leftmost position Roate right : The rightmost 1 was moved to the leftmost position. Logical shift Lest : The leftmost 1 was dropped and a 0 was added the rightmost poisition. Arithmetic shift right : the rightmost 0 was dropped and the leftmost 9 was copied into the new leftmost position. 8 bit word : 0101 1101 rotate right : 1010 1110 Arithmetic shift right : 0010 1110 Logical Shift left : 1011 1010 |
< <= > >= instanceof | Left to right | null instanceof T is always false |
== != | Left to right | Check for identity. Use equals to check for structural equality. |
& | Left to Right | Bitwise AND; no lazy evaluation with bool arguments |
^ | Left to right | Bitwise XOR |
| | Left to right | Bitwise OR; no lazy evaluation with bool arguments |
&& | Left to right | |
|| | Left to right | |
?: | Right to Left | |
= += -= *= /= %= &= |= ^= <<= >>= >>>= | Right to Left |
Section 5 Primitive Types
Type | Size | Range | Notes |
int | 4 Bytes | -2,147,483,648 to 2,147,483,647 (just over 2 billion) | The wrapper type is Integer. Use BigInteger for arbitrary precision integers |
short | 2 Bytes | -32768 to 32,767 | |
long | 8 Bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Literals end with L (e.g. 1L) |
byte | 1 byte | -128 to 127 | Note that the range is not 0 ~ 255 |
float | 4 bytes | approximately -3.40282347E+38F (6-7 significant decimal digits) | Literals end with F |
double | 8 bytes | approximately -1.79769313486231570E+308 (15 significant decimal digits) | Use BigDecimal for arbitrary precsion floating-point numbers |
char | 2 bytes | \u0000 to \uFFFF | The wrapper type is character. Unicode characters >U+FFFF require two char values. |
Legal Conversions Between Primitive Types
Dotted arrows denote conversions that may lose precision
section 6 . Lambda Expressions
Functional interfaces
Interfaces with a single abstract method. (단독 추상 메소드를 가지고 있는 인터페이스들)
@FunctionalInterface public interface Predicate<T>{ boolean test(T t); } |
이 인터페이스의 구현들은 인라인, 람다 표현식으로 적용되어 질수 있습니다.
- 함수적 인터페이스의 익명 구현들
- 파라미터들과 몸체는 화살표("->") 로 구분되어 집니다.
- 추상메소드의 파라메타들은 화살표의 왼쪽에 있습니다.
Implementations of this interface can be supplied in-line as a lambda expression:
- Anonymous implementations of functional interfaces
- Parameters and body are separarted by an "arrow sign" ("->")
- Parameters of the abstract method are on the left of the arrow
Typical usage of lambda expression:
JButton button = new JButton("MyButton"); button.addActionListener(event -> doSomeImportantStuff(event)); //event 는 추상메소드의 파라미터, 몸체는 -> 오른쪽) |
Method References
람다 표현식은 익명 함수들을 나타냅니다.
여러분은 람다 표현식들을 메소드 파라미터들로 전달하거나, 람다 표현식을 리턴할수 있습니다.
메소드 참조들을 사용하여 명명된 메소드들을 가지고 동일한 작업을 수행할 수 있습니다.
Lambda expressions represent anonymous functions.
You can pass them as method parameters or return them.
The same can be done with named methods using method references.
Typical usage of method references :
without method reference | with method referenece |
button.addActionListener(event-> doSomeImportantStuff(event)); | button.addActionListener( this::doSomeImportantStuff); |
list.forEach(element-> System.out.println(element)); | list.forEach( System.out::println); |
메소드 레퍼런스의 4가지 종류가 있습니다.
There are four kinds of method reference
Kind of method reference | example |
To a static method | Collections::emptyList |
To an instance method of a particular(named) object | user::getFirstName |
To an instance method of an arbitrary object (to be named later) of a given type | User::getFirstName |
To a constructor | User::new |
Session 7 Collections and Common Algorithms
ArrayList | An indexed sequence that grows and shinks dynamically. 동적으로 늘어나고 줄어드는 인덱스된 시퀀스 |
LinkedList | An ordered sequence that allows efficient insertions and removal at any location. 어떤 위치든지 효율적으로 추가와 삭제가 가능한 정렬된 시퀀스 |
ArrayDeque | A double-ended queue that is implemented as a circular array. 한개의 원형 배열로 구현된 두개로 끝나는 큐 |
HashSet | An unordered collection that rejects dulpicates. 중복 안되는 정렬이 안된 컬랙션 |
TreeSet | A sorted set 정렬된 셋 |
EnumSet | A set of enumerated type values. 타입값들이 나열된 셋 |
LinkedHashSet | A set that remembers the order in which elements were inserted. 요소들이 추가된 곳에 순서를 기억하는 셋. |
PriorityQueue | A collection that allows effcient removal of the smallest element 최소 요소의 효율적 제거가 가능한 컬렉션 |
HashMap | A data structure that stores key/value associations 키/값 조합을 저장한 데이터 구조 |
TreeMap | A map in which the keys are sorted. 키들을 정렬한 곳에 맵 |
EnumMap | A map in which the keys belong to an enumerated type. 열거된 형태에 속한 곳 키들의 맵 |
LinkedHashMap | A map that remembers the order in which entries were added. 엔트리들이 추가된 곳에 순서를 기억하는 맵 |
WeakHashMap | A map with values that can be reclaimed by the garbage collector if they are not used elsewhere. 어느곳에도 사용되지 않았을 때 가비지컬렉터에 의해서 회수되어 질수 있는 값을 갖는 맵 |
IdentityHashMap | A map with key that are compared by ==, not equals equals 말고, ==에 의해 비교된 키를 갖는 맵 |
Common Tasks
List<String> strs = new ArrayList<>(); | Collection strings 컬렉션 문자열 |
strs.add("Hello"); strs.add("World"); | Add strings 문자열 추가 |
Iterator<String> iter = strs.iterator(); while(iter.hasNext()){ String str = iter.next(); if(someCondition(str)) iter.remove(); } | Remove element that match a condition. The remove method removes the element returned by the preceding call to next. 어떤 조건과 매치되는 요소를 지운다. remove 메소드는 이전호출에 의해 리턴된 요소를 다음으로 제거합니다. |
strs.addAll(strColl); | Add all strings from another collection of strings. 다른 문자열의 컬렉션으로 부터 모든 문자열을 추가합니다. |
strs.addAll(Array.asList(args)) | Add all strings from an array of strings. Array.asList makes a List wrapper for an array. 문자열배열로 부터 모든 문자열을 추가합니다. Array.asList은 배열에 대한 List wrapper를 만듭니다. |
strs.removeAll(coll); | Remove all elements of another collection. Uses equals for comparison 다른 컬렉션의 모든 요소를 제거합니다. 비교를 위한 equals을 사용하세요. |
if(0 < i && i <strs.size()){ str = strs.get(i); strs.set(i,"Hello"); } | Get or set an element at a specified index. 지정한 인덱스의 요소를 가져오거나 배치한다. |
strs.insert(i, "Hello"); str = strs.remove(i); | Insert or remove an element at a specified index, shifting the elements with higher index values 지정한 인덱스의 요소를 추가하거나 지웁니다. 높은 인덱스 값을 가진 요소를 옯깁니다. |
String[] arr = new String[strs.size()]; strs.toArray(arr); | Convert from collection to array 컬렉션을 배열로 변환합니다. |
String[] arr = ....; List<String> 1st = Array.asList(arr); 1st = Array.asList("foo","bar","baz"); | Convert from array to list. Use the varargs form to make a small collection. 작은 컬렉션을 만들기 위해 가변인자 형태를 사용한다. |
List<String> 1st = ...; 1st.sort(); 1st.sort(new Comparator<String>(){ pubilc int compare(String a, String b){ return a.length() - b.length(); } } | Sort a list by the natural order of the elements, or with a custom comparator 요소들의 자연적인 순서 혹은 사용자 비교에 의해 리스트를 정렬합니다. |
Map<String,Person> map = new LinkedHashMap<String, Person>(); | Make a map that is traversed in insertion order( requires hashCode for key type). Use a TreeMap to traverse in sort order (requires that key type is comparable) 주입 순서로 통과되는 맵을 만들어라.(키 타입을 위한 hashCode가 필요합니다.) 정렬 순서로 통과 하기 위해 TreeMap을 사용해라( 키 타입이 비교되는 것이 필요합니다.) |
for(Map.Entry<String, Person> entry: map.entrySet()){ String key = entry.getKey(); Person value = entry.getValue(); ... } | Iterate through all entries of the map. 맵의 모든 엔트리들을 통해 반복합니다. |
Person key = map.get(str); //null if not found map.put(key,value); | Get or set a value for a given key 주어진 키에 대한 값을 주거나 세팅합니다. |
Bulk Operations with Steam API (Stream API로 대량작업)
str.forEach(System.out::println); | Do something with all elements in the collection |
List<String> filteredList = strs.stream() .filter(this::someCondition) .collect(Collectors.toList()); | Filter elements that match a condition 조건에 매칭하는 요소들을 필터하라 |
String concat = strs.stream() .collect(Collectors.joining(",")); | Concatenate the element of a stream. 스트림의 요소를 연결하라 |
List<User> users = ....; List<String> firstNames = users.stream() .map(User::getFirstName) .collect(Collectors.toList()); | Create a new list that maps to the original one. 기존것에 매핑하는 새로운 리스트를 생성하라. |
List<String> adminFirstName = users.stream() .filter(User::isAdmin) .map(User::getFirstName) .collect(Collectors.toList()); | Combine operations this will not result in two traversals of the list elements. 연산을 결합하면 목록 요소를 두번 통과하지 않습니다. |
int sumOfAges = users.stream() .mapToLong(User::getAge) .sum(); | Simple reduction operation |
Map<Role, List<User>> byRole = users.stream() .collect(Collectors.groupingBy(User::getRole)); | Group users by a certain attribute |
int sumOfAges = users.parallelStream() .mapToLong(User::getAge).sum(); | All the above operations can be done in parallel 위 모든 작업은 병렬로 작업할수 있습니다. |
Section 8 Character Escape Sequences
\b | backspace \u0008 |
\t | tab \u0009 |
\n | newline \u000A |
\f | form feed \u000C |
\r | carriage return \u000D |
\" | double quote |
\' | single quote |
\\ | backslash |
\uhhhh(hhhh is a hex number between oooo and FFFF) | The UTF-16 code point with value hhhh |
\000 (000 is an octal number between 0 and 377) | The character with octal value 000 |
* Unlike in C/C++ , \xhh is not allowed
session 9 Formatted Output with printf
Typical Usage
System.out.println("%4d %8.2f" , quantity, price); String str = String.format("%4d, $8.2f", quantity, price); |
Each format specifier has the flolowing form.
Flags
FLAG | DESCRIPTION | EXAMPLE |
+ | Prints sign for positive and negative numbers | +3333.33 |
space | Adds a space before positive number | |3333.33| |
0 | Adds leading zeroes | 003333.33 |
- | Left-justifies field | |3333.33| |
( | Encloses negative number in parentheses | (3333.33) |
, | Adds group separators | 3,333.33 |
#(for f format) | Always includes a decimal point | 3,333. |
#(for x or 0 format) | Adds ox or o prefix | oxcafe |
$ | Specifies the index of the arguement to be formatted; for example, %1$d %1$x prints the first argument in decimal and hexadecimal | 158 9F |
< | Formats the same value as the previous specification; for example, %d%<x prints the same number in decimal and hexadecimal | 159 9F |
Conversion Characters
CONVERSION CHARACTER | DESCRIPTION | EXAMPLE |
d | Decimal integer | 159 |
x | Hexadecimal integer | 9f |
o | Octal integer | 237 |
f | Fixed-point floating-point | 15.9 |
e | Exponential floating-point | 1.59e+01 |
g | General floating-point(the shorter of e and f) | |
a | Hexadecimal floating-point | ox1.fccdp3 |
s | String | Hello |
c | Character | H |
b | boolean | true |
h | Hash code | 42628b2 |
tx | Date and time | See the next table long currentTime = System.currentTimeMillis(); java.util.Date date = new java.util.Date(currentTime); System.out.println( String.format("Current Time: %1$tm/%1$td/%1$tY %1$tH:%1$tM:%1$tS", currentTime) ); |
% | The percent symbol | % |
n | The platform-dependent line separator |
SECTION 10. Formatted Output with MessageFormat
Typical usage:
String msg = MessageFormat.format( "On {1,date,long}, a {0} caused {2,number,currency} of damage.", "hurricane", new GregorianCalendar(2009,0,15).getTime(), 1.0E8); |
Yields "On January 1, 1999, a hurricane caused $100,000,000 of damage"
- The nth item is denoted by {n, format, subformat} with optional formats and subformats shown below.
- {0} is the first item
- The following table shows the available formats.
- Use single quotes for quoting, for example '{] for a literal left curly brace.
- Use " for a literal single quote.
FORMAT | SUBFORMAT | EXAMPLE |
number | none | 1,234,567 |
integer | 1,235 | |
currency | $1,123,455 | |
percent | 93.324% | |
date | none or medium | Jan 15,2009 |
short | 1/15/09 | |
long | January 16,2009 | |
full | Thursday, January 15,2009 | |
time | none or medium | 3:45:00 PM |
short | 3:25 PM | |
long | 3:45:00 PM PST | |
full | 3:34:00 PM PST | |
choise | List of choices, separated by |. Each choice has - a lower bound( use -\u221E for-) - a relational operator : < for "less than", # or \u2264 for. - message format string For example, {1,choice, 0#no house|1#one house|2 #{1} houses} | no houses one house 5 houses |
'Java' 카테고리의 다른 글
core java 따라하기 - 2 (0) | 2017.06.15 |
---|---|
JUnit5 개념 잡기 (0) | 2017.06.02 |
java8 StringJoiner 과 String.join 활용 (0) | 2016.01.05 |
ThreadLocal 이 뭘까요? (0) | 2016.01.05 |
Apache Daemon 에 대해서 (3) | 2015.12.08 |
Runtime.addShutdownHook() (0) | 2015.09.30 |
Top 10 Useful, Yet paranoid Java Programming Techniques (0) | 2015.09.15 |
Exception (0) | 2013.08.04 |
Regular Expressions in Java (0) | 2013.07.30 |
Delegate, Event , Ramda (0) | 2013.07.04 |