Skip to main content

2. Типы данных в Java. Работа со строками и числами

Материалы

Презентация: Типы данных в Java.pptx

Проект с примерами: lesson2.zip

Задачи

CurrencyExchenge​

Необходимо реализовать класс Money с поддержкой валют и методами add, subtract, multiply, devide

Постановка: CurrencyExchange.zip

Чтобы открыть проект в Idea:

  1. Cкачать и распаковать
  2. В Idea выбрать File→Open и выбрать распакованную директорию с проектом

Quantity​

Необходимо реализовать класс Quantity с поддержкой единиц измерения и арифметических операций: add, subtract, multiply, divide

Проект: Quantity.zip

Структура JVM

Структура памяти​

В документации полностью описаны области памяти в JVM -  https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html

Пример с разбором структур памяти в Java:  https://javadevblog.com/chto-takoe-heap-i-stack-pamyat-v-java.html

https://habr.com/ru/articles/744834/

Сборщик мусора​

Документация по GC -  https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Детали по Copy-Collection и Mark-Sweep-Compact:  https://habr.com/ru/post/112676/

Встроенные инструменты​

jvisualvm - мониторинг состояния JVM

jconsole - мониторинг ресурсов, работы GC

Примеры​

Развернуть исходный код

static char[] alphabet;

static {
alphabet = new char[26];
for (char c = 'a'; c <= 'z'; c++) {
alphabet[c - 'a'] = c;
}
}


public static void main(String ... args) {
while(true) {
String word = "";
for (int i = 0; i < 1000; i++) {
word += alphabet[(int)(Math.random()*26)];
}
System.out.println("word = " + word);
}
}


private static recurrent(int i) {
recurrent(++i);
}

Строки

Интернирование​

Пример интернирования Развернуть исходный код

String s1 = "Hello, World";
String s2 = "Hello, World";
System.out.println("Comparing s1 and s2");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

System.out.println("Comparing s1 and s3");
String s3 = new String(s1);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));

System.out.println("Interning s1 and s3");
System.out.println(s1 == s3.intern());

System.out.println("Comparing concatenated strings");
String s4 = s1+"!";
System.out.println(s4 == s1+"!");
System.out.println(s4 == (s1+"!").intern());
System.out.println(s4.intern() == (s1+"!").intern());
System.out.println(s4.equals(s1+"!"));

Полезные ссылки​

    1. String pooling -  http://java-performance.info/string-intern-in-java-6-7-8/

Методы​

Примеры работы со строками Развернуть исходный код

String description = "The class String includes methods for examining\n" +
" * individual characters of the sequence, for comparing strings, for\n" +
" * searching strings, for extracting substrings, and for creating a\n" +
" * copy of a string with all characters translated to uppercase or to\n" +
" * lowercase";

System.out.println("Length: "+description.length()+", is empty: "+description.isEmpty());

String[] words = description.split(" ");
for(String word : words) {
System.out.println(word);
}

String shortDescription = description.substring(10);
System.out.println(shortDescription);
shortDescription = description.substring(description.indexOf("String"));
System.out.println(shortDescription);

String usdNumber = "$101.78";
System.out.println(usdNumber.matches("\\$\\d*\\.\\d*"));

String stringWithPrice = "Cost is 101.56 USD in Target";
System.out.println(stringWithPrice.replaceAll("(\\d*\\.\\d*)( USD)", "\\$$1"));

String[] numbers = new String[] {"one", "two", "three"};
System.out.println(String.join(",", numbers));

StringBuilder  и StringBuffer​

Пример использования StringBuilder Развернуть исходный код

//плохо
String result = "0";
for (int i = 1; i < 10000; i++) {
result += "," + i;
}
System.out.println(result);


//хорошо
StringBuilder sb = new StringBuilder("0");
for (int i = 0; i < 10000; i++) {
sb.append(",").append(i);
}
System.out.println(sb.toString());

Числа

Развернуть исходный код

double d = 0.1;
double result = 0.0;
for (int i = 0; i < 10; i++) {
result += d;
}

System.out.println("result = " + result);


BigDecimal bc = new BigDecimal(0.1, new MathContext(10, RoundingMode.DOWN));
BigDecimal result = new BigDecimal(0.0, new MathContext(10, RoundingMode.DOWN));
for (int i = 0; i < 10; i++) {
result = result.add(bc);
}

System.out.println("result = " + result);

Currency

Развернуть исходный код

Currency usd = Currency.getInstance("USD");
Currency eur = Currency.getInstance("EUR");
Currency gbp = Currency.getInstance("GBP");
System.out.println("usd = " + usd);
System.out.println("eur = " + eur);
System.out.println("gbp = " + gbp);

System.out.println(usd.getDisplayName());
System.out.println(usd.getDefaultFractionDigits());