Enum, number, string

Содержание

Слайд 2

Enum

Enum

Слайд 3

Enum An enum type is a special data type that enables

Enum

An enum type is a special data type that enables

for a variable to be a set of predefined constants.

public enum Gender {
MALE,
FEMALE;
}
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}

Слайд 4

The enum class body can include methods and other fields. public

The enum class body can include methods and other fields.

public

enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
...
private final double mass;
private final double radius;
private Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double getMass() {
return mass;
}
public double getSurfaceGravity() {
return G * mass / (radius * radius);
}
}
Слайд 5

Enum example public enum Direction { NORTH(0, 1), EAST(1, 0), SOUTH(0,

Enum example

public enum Direction {
NORTH(0, 1),
EAST(1, 0),
SOUTH(0, -1),

WEST(-1, 0);
private final int x;
private final int y;
private Direction(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
...
public void move(Direction direction) {
currentX += direction.getX();
currentY += direction.getY();
}
Слайд 6

Enum All enums implicitly extend java.lang.Enum. All enum constants implicitly have

Enum

All enums implicitly extend java.lang.Enum.
All enum constants implicitly have public static

final modifier
You cannot create instance of enum with new operator
You cannot extend enum
Слайд 7

Enum Non static methods of enum: ordinal() - Returns the ordinal

Enum

Non static methods of enum:
ordinal() - Returns the ordinal of this

enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
compareTo() - compares this enum with the specified object for order
Static enum methods:
values() – All the constants of an enum type can be obtained by calling this method
valueOf(String name) – Returns the enum constant of the specified enum type with the specified name
Слайд 8

Annotation Annotation is a form of metadata, provide data about a

Annotation

Annotation is a form of metadata, provide data about a program

that is not part of the program itself
Annotations have a number of uses, among them:
Information for the compiler
Compile-time and deployment-time processing
Runtime processing
Слайд 9

Predefined Annotation Types @Deprecated @Override @SuppressWarnings /** * @deprecated explanation of

Predefined Annotation Types

@Deprecated
@Override
@SuppressWarnings

/**
* @deprecated explanation of why it was deprecated

*/
@Deprecated
static void deprecatedMethod() {
}

@Override
int overriddenMethod() {
}

@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
deprecatedMethod();
}

Слайд 10

Number

Number

Слайд 11

Math

Math

Слайд 12

Math

Math

Слайд 13

Number classes All of the numeric wrapper classes are subclasses of

Number classes

All of the numeric wrapper classes are subclasses of

the abstract class

Number

BigInteger

Byte

Short

Integer

Long

Float

Double

BigDecimal

Слайд 14

Numbers There are three reasons that you might use a Number

Numbers

There are three reasons that you might use a Number

object rather than a primitive:
As an argument of a method that expects an object (often used when manipulating collections of numbers).
To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).
Слайд 15

Number methods

Number methods

Слайд 16

Integer public static Integer decode(String nm) public static int parseInt(String s)

Integer

public static Integer decode(String nm)
public static int parseInt(String s)
public static int

parseInt(String s, int radix)
public static String toString(int i)
public static Integer valueOf(int i)
public static Integer valueOf(String s)
public static Integer valueOf(String s, int radix)
Слайд 17

Double

Double

Слайд 18

BigInteger handling very large integers provides analogues to all of Java's

BigInteger

handling very large integers
provides analogues to all of Java's primitive

integer operators
provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation

public BigInteger(String val)
public BigInteger(byte[] val)
public static BigInteger valueOf(long val)

Слайд 19

BigInteger methods public BigInteger add(BigInteger val) public BigInteger subtract(BigInteger val) public

BigInteger methods

public BigInteger add(BigInteger val)
public BigInteger subtract(BigInteger val)
public BigInteger multiply(BigInteger val)
public

BigInteger divide(BigInteger val)
public BigInteger mod(BigInteger m)
public BigInteger pow(int exponent)
public BigInteger abs()
public BigInteger negate()
public int signum()
public BigInteger and(BigInteger val)
public BigInteger or(BigInteger val)
public BigInteger xor(BigInteger val)
public BigInteger not()
Слайд 20

BigDecimal java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison,

BigDecimal

java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing,

and format conversion.
BigDecimal is immutable

public BigDecimal(String val)
public BigDecimal(BigInteger val)
public BigDecimal(double val)
public static BigDecimal valueOf(double val)
public static BigDecimal valueOf(long val)

Слайд 21

BigDecimal methods public BigDecimal add(BigDecimal augend) public BigDecimal subtract(BigDecimal subtrahend) public

BigDecimal methods

public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand,

MathContext mc)
public BigDecimal divide(BigDecimal divisor,
MathContext mc)
public BigDecimal pow(int n, MathContext mc)
public BigDecimal abs()
public int signum()
public int scale()
public int precision()
Слайд 22

Character – wrapper for char public static boolean isLetter(char ch) public

Character – wrapper for char

public static boolean isLetter(char ch)
public static boolean

isDigit(char ch)
public static boolean isWhitespace(char ch)
public static boolean isUpperCase(char ch)
public static boolean isLowerCase(char ch)
public static char toUpperCase(char ch)
public static char toLowerCase(char ch)
public static String toString(char c)
Слайд 23

Autoboxing Autoboxing is the automatic conversion that the Java compiler makes

Autoboxing

Autoboxing is the automatic conversion that the Java compiler makes

between the primitive types and their corresponding object wrapper classes
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing.
Слайд 24

Autoboxing The Java compiler applies autoboxing when a primitive value is:

Autoboxing

The Java compiler applies autoboxing when a primitive value is:
Passed as

a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
The Java compiler applies unboxing when an object of a wrapper class is
Passed as a parameter to a method that expects a value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive type.
Слайд 25

Wrapper classes

Wrapper classes

Слайд 26

Autoboxing Integer integer = 1; // Integer.valueOf(1) int i = integer;

Autoboxing

Integer integer = 1; // Integer.valueOf(1)
int i = integer; // integer.intValue()
Character

character = 'a';
char c = character;
Double value = 1.0;
double d = value;
Byte byteValue = null;
byte b = byteValue; // NullPointerException
Слайд 27

Autoboxing public static List asList(final int[] a) { return new AbstractList

Autoboxing

public static List asList(final int[] a) {
return new AbstractList() {

public Integer get(int i) {
return a[i];
}
public Integer set(int i, Integer value) {
Integer old = a[i];
a[i] = value;
return old;
}
public int size() {
return a.length;
}
};
}
Слайд 28

String

String

Слайд 29

String Строка – объект класса String String creation public final class

String

Строка – объект класса String
String creation

public final class String
implements java.io.Serializable,

Comparable, CharSequence

String greeting = "Hello world!";
char[] array = {'h', 'e', 'l', 'l', 'o'};
String helloString = new String(array);

Слайд 30

Working with strings Длина строки String concatenation String s = "Some

Working with strings

Длина строки
String concatenation

String s = "Some text";
s.length();
"Text".length();

s = s.concat("Additional

text");
s = "Text".concat("Another text");
s = "Text" + "Another text";
Слайд 31

Converting string to number Wrapper classes Primitive types Integer value =

Converting string to number

Wrapper classes
Primitive types

Integer value = Integer.valueOf("1");
Double value =

Double.valueOf("1.0");

int value = Integer.parseInt("1");
double value = Double.parseDouble("1.0");

Слайд 32

Converting number to string String Number classes String.valueOf(1); String.valueOf(1.0); Integer.toString(1); Double.toString(1.0);

Converting number to string

String
Number classes

String.valueOf(1);
String.valueOf(1.0);

Integer.toString(1);
Double.toString(1.0);

Слайд 33

Getting Characters and Substrings by Index String text = "Niagara. O

Getting Characters and Substrings by Index

String text = "Niagara. O roar

again!";
char aChar = text.charAt(9);
String roar = text.substring(11, 15);
Слайд 34

String methods public String[] split(String regex) public String[] split(String regex, int

String methods

public String[] split(String regex)
public String[] split(String regex, int limit)
public CharSequence

subSequence(int beginIndex,
int endIndex)
public String trim()
public String toLowerCase()
public String toUpperCase()
Слайд 35

Searching for Characters and Substrings in a String public int indexOf(int

Searching for Characters and Substrings in a String

public int indexOf(int ch)
public

int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public boolean contains(CharSequence s)
Слайд 36

Replacing Characters and Substrings into a String public String replace(char oldChar,

Replacing Characters and Substrings into a String

public String replace(char oldChar, char

newChar)
public String replace(CharSequence target,
CharSequence replacement)
public String replaceAll(String regex,
String replacement)
public String replaceFirst(String regex,
String replacement)
Слайд 37

Comparing Strings and Portions of Strings public boolean endsWith(String suffix) public

Comparing Strings and Portions of Strings

public boolean endsWith(String suffix)
public boolean startsWith(String

prefix)
public int compareTo(String anotherString)
public int compareToIgnoreCase(String str)
public boolean equals(Object anObject)
public boolean equalsIgnoreCase(String str)
public boolean matches(String regex)
Слайд 38

String immutability String objects are immutable String is not changed: Currently

String immutability

String objects are immutable
String is not changed:
Currently “s” refers to

new String object that was created during concantenation

s = s.concat(“big");

s.concat(“big");

Слайд 39

String modification Each String modification creates new String. N Strings will

String modification

Each String modification creates new String.
N Strings will be created

String

s = "";
for (int i = 0; i < n; i++) {
s += "*";
}
Слайд 40

StringBuilder Like String objects, except that they can be modified. Strings

StringBuilder

Like String objects, except that they can be modified.
Strings should always

be used unless string builders offer an advantage in terms of simpler code or better performance.
if you need to concatenate a large number of strings, appending to a StringBuilder is more efficient

StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; i++) {
builder.append("*");
}

Слайд 41

StringBuilder Конструкторы Length and capacity public StringBuilder() public StringBuilder(int capacity) public

StringBuilder

Конструкторы
Length and capacity

public StringBuilder()
public StringBuilder(int capacity)
public StringBuilder(String str)
public StringBuilder(CharSequence seq)

public int

length()
public void setLength(int newLength)
public int capacity()
public void ensureCapacity(int minimumCapacity)
Слайд 42

StringBuilder methods public StringBuilder append(Object obj) public StringBuilder delete(int start, int

StringBuilder methods

public StringBuilder append(Object obj)
public StringBuilder delete(int start, int end)
public StringBuilder

deleteCharAt(int index)
public StringBuilder insert(int offset, Object obj)
public StringBuilder replace(int start, int end, String str)
public void setCharAt(int index, char ch)
public StringBuilder reverse()
public String toString()
Слайд 43

String & StringBuilder

String & StringBuilder

Слайд 44

Date

Date

Слайд 45

Working with dates Main classes java.util.Date java.util.Calendar For Database java.sql.Timestamp java.sql.Date java.sql.Time

Working with dates

Main classes
java.util.Date
java.util.Calendar
For Database
java.sql.Timestamp
java.sql.Date
java.sql.Time

Слайд 46

java.util.Date Constructors Main methods The most part of other methods are

java.util.Date

Constructors
Main methods
The most part of other methods are deprecated

public Date()
public Date(long

date)

public boolean before(Date when)
public boolean after(Date when)
public int compareTo(Date anotherDate)
public long getTime()
public void setTime(long time)

Слайд 47

Calendar Main methods Constants: ERA, YEAR, MONTH, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_MONTH, DAY_OF_YEAR,

Calendar

Main methods
Constants:
ERA, YEAR, MONTH, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK, AM_PM, HOUR,

HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND

public static Calendar getInstance()
public final void setTime(Date date)
public final void set(int year, int month, int date)
public void set(int field, int value)
public final Date getTime()
public int get(int field)
public void add(int field, int amount);

Слайд 48

DateFormat DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); Date date = dateFormat.parse("04.06.2012"); String text = dateFormat.format(new Date());

DateFormat

DateFormat dateFormat
= new SimpleDateFormat("dd.MM.yyyy");
Date date = dateFormat.parse("04.06.2012");
String text = dateFormat.format(new

Date());
Слайд 49

DateFormat

DateFormat

Слайд 50

Слайд 51

Task№3 – Общие требования Общие требования: Код должен быть отформатирован и

Task№3 – Общие требования

Общие требования:
Код должен быть отформатирован и соответствовать

Java Code Convention.
Решение поставленной задачи, должно быть реализовано в классе, который находится в пакете com.epam.firstname_lastname.java.lesson_number.task_number, например: com.epam.anton_ostrenko.java.lesson3.task3.
Класс, который содержит main-метод, должен иметь осмысленное название. Внутри метода main создайте объект его класса, у которого вызовете метод, являющийся стартовым для решения вашей задачи.
По возможности документируйте код.
Слайд 52

Task№3 – Задание №1 В Учебном Центре компании проходят обучение студенты.

Task№3 – Задание №1

В Учебном Центре компании проходят обучение студенты. Каждый

студент проходит обучение по определенной индивидуальной программе. Программа обучения состоит из набора курсов, которые студент проходит последовательно. Каждый курс имеет определенную длительность.
Приложение должно позволять:
• определить относительно текущей даты закончил студент изучение программы или нет.
• рассчитать, сколько дней и часов осталось студенту до окончания программы или сколько дней и часов назад студент закончил изучение программы обучения.
Слайд 53

Task№3 – список данных о студентах: STUDENT: Ivanov Ivan CURRICULUM: J2EE

Task№3 – список данных о студентах:

STUDENT: Ivanov Ivan
CURRICULUM: J2EE Developer
START_DATE: <указать

дату получения задания>
COURSE DURATION (hrs)
--------------------------------------------
1. Технология Java Servlets 16
2. Struts Framework 24
STUDENT: Petrov Petr
CURRICULUM: Java Developer
START_DATE: <указать дату получения задания>
COURSE DURATION (hrs)
--------------------------------------------
1. Обзор технологий Java 8
2. Библиотека JFC/Swing 16
3. Технология JDBC 16
Непосредственно в коде следует прописать дату получения данного задания
Слайд 54

Task№3 – список данных о студентах: STUDENT: Ivanov Ivan CURRICULUM: J2EE

Task№3 – список данных о студентах:

STUDENT: Ivanov Ivan
CURRICULUM: J2EE Developer
START_DATE: <указать

дату получения задания>
COURSE DURATION (hrs)
--------------------------------------------
1. Технология Java Servlets 16
2. Struts Framework 24
STUDENT: Petrov Petr
CURRICULUM: Java Developer
START_DATE: <указать дату получения задания>
COURSE DURATION (hrs)
--------------------------------------------
1. Обзор технологий Java 8
2. Библиотека JFC/Swing 16
3. Технология JDBC 16
Непосредственно в коде следует прописать дату получения данного задания
Слайд 55

Task№3 – Задание 1 Условия: Учебными считаются все дни недели при

Task№3 – Задание 1

Условия:
Учебными считаются все дни недели при условии

8-ми часового учебного дня с 10 до 18.
Ввод/Вывод:
Результат расчета вывести в консоль с указанием имени студента и изучаемой программы.
Пример вывода.
Ivanov Ivan (Java Developer) - Обучение не закончено. До окончания осталось 1 д 6 ч.
Petrov Petr (J2EE Developer) - Обучение закончено. После окончания прошло 3 ч.
Расчет этого времени учитывает длительность учебного дня.
Слайд 56

Task№3 – Задание 1 Условия: Учебными считаются все дни недели при

Task№3 – Задание 1

Условия:
Учебными считаются все дни недели при условии

8-ми часового учебного дня с 10 до 18.
Ввод/Вывод:
Результат расчета вывести в консоль с указанием имени студента и изучаемой программы.
Пример вывода.
Ivanov Ivan (Java Developer) - Обучение не закончено. До окончания осталось 1 д 6 ч.
Petrov Petr (J2EE Developer) - Обучение закончено. После окончания прошло 3 ч.
Расчет этого времени учитывает длительность учебного дня.
Слайд 57

Task№3 – Задание 1 2. Вывести подробный отчет по обучению: ФИО,

Task№3 – Задание 1

2. Вывести подробный отчет по обучению: ФИО, рабочее время

(с 10 до 18), название программы, длительность программы в часах, дата старта, дата завершения, сколько прошло/осталось до завершения.
Выбор варианта запуска осуществляется входящим параметром (нет параметра или параметр 0 – сокращенный вид отчета, иначе – подробный.
Слайд 58

Task№3 – Дополнительное задание Реализовать template generator. Например, есть шаблон: “Hello,

Task№3 – Дополнительное задание

Реализовать template generator. Например,
есть шаблон: “Hello, ${name}”

, и значение name=”Reader” , TemplateGenerator должен вернуть “Hello Reader”
“Hello, ${name}”, и значение для name не было установлено -> Error
“${one}, ${two}, ${three}”, значения one=”1”, two=”${2}”, three = 3
“1, ${2}, 3”
Шаблон и значения вводяться с консоли.
Пример,
Введите шаблон:
“${greeting}, ${name}”
Введите переменные:
greeting=Hi, name=Petro
Результат: Hi, Petro