Knowledge in Java

Strings in Java

The String class represents character strings. All string literals, for example, "hello", are implemented as instances of this class. An instance of this class is an object. Strings are immutable, e.g., an assignment of a new value to aString object creates a new object.To concatenate Strings use a StringBuilder.Try Your Self:StringBuilder sb =new StringBuilder("Hello ");sb.append("Eclipse");String s = sb.toString();Avoid using StringBuffer and prefer StringBuilder. StringBuffer is synchronized and this is almost never useful, it is just slower.

Working With Strings

The following lists the most common string operations. Command Description"Testing".equals(text1);                Return true if text1 is equal to "Testing". The check is case-sensitive."Testing".equalsIgnoreCase(text1);       Return true if text1 is equal to "Testing". The check is not case-sensitive. For example, it would also be true for"testing".StringBuilder str1 = new StringBuilder();    Define a new StringBuilder which allows to efficiently add "Strings".str.charat(1);                  Return the character at position 1. (Note: strings are arrays of chars starting with 0)str.substring(1);                       Removes the first characters.str.substring(1, 5);          Gets the substring from the second to the fifth character.str.indexOf("Test")            Look for the String "Test" in String str. Returns the index of the first occurrence of the specified string.str.lastIndexOf("ing")                  Returns the index of the last occurrence of the specifiedString "ing" in the String str.str.endsWith("ing")            Returns true if str ends with String "ing"str.startsWith("Test")      Returns true if String str starts with String"Test".str.trim()                               Removes leading and trailing spaces.str.replace(str1, str2)                  Replaces all occurrences of str1 by str2str2.concat(str1);                         Concatenates str1 at the end of str2.str.toLowerCase() / str.toUpperCase()      Converts the string to lower- or uppercasestr1 + str2                                   Concatenate str1 and str2

Lambdas in Java

What is Lambdas?The Java programming language supports lambdas as of Java 8. A lambda expression is a block of code with parameters. Lambdas allows to specify a block of code which should be executed later. If a method expects afunctional interface as parameter it is possible to pass in the lambda expression instead.The type of a lambda expression in Java is a functional interface.Purpose of lambdas expressions.Using lambdas allows to use a condensed syntax compared to other Java programming constructs. For example theCollection interfaces has forEach method which accepts a lambda expression.List<String> list = Arrays.asList("vogella.com","google.com","heise.de" ) list.forEach(s-> System.out.println(s)); Using method references.You can use method references in a lambda expression. Method reference define the method to be called viaCalledFrom::method. CalledFrom can be * instance::instanceMethod * SomeClass::staticMethod * SomeClass::instanceMethodList<String> list = new ArrayList<>(); list.add("vogella.com"); list.add("google.com"); list.add("heise.de"); list.forEach(System.out::println); Difference between a lambda expression and a closure.The Java programming language supports lambdas but not closures. A lambda is an anonymous function, e.g., it can be defined as parameter. Closures are code fragments or code blocks which can be used without being a method or a class. This means that a closure can access variables not defined in its parameter list and that it can also be assigned to a variable.

Streams

What is streams?A stream from the java.util.stream package is a sequence of elements from a source that supports aggregate operations.IntstreamsAllow to create a stream of sequence of primitive int-valued elements supporting sequential and parallel aggregate operations.package com.vogella.java.streams; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; public class IntStreamExample { public static void main(String[] args) { // printout the numbers from 1 to 100 IntStream.range(1, 101).forEach(s -> System.out.println(s)); // create a list of integers for 1 to 100 List<Integer> list = new ArrayList<>(); IntStream.range(1, 101).forEach(it -> list.add(it)); System.out.println("Size " + list.size()); } }

Reduction operations

Reduction operations with streams and lambdas.Allow to create a stream of sequence of primitive int-valued elements supporting sequential and parallel aggregate operations.Try your self:1St package com.vogella.java.streams;public class Task { private String summary; private int duration; public Task(String summary, int duration) { this.summary = summary; this.duration = duration; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; }}2nd:package com.vogella.java.streams;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.stream.Collectors;import java.util.stream.IntStream;public class StreamTester { public static void main(String[] args) { Random random = new Random(); // Generate a list of random task List<Task> values = new ArrayList<>(); IntStream.range(1, 20).forEach(i -> values.add(new Task("Task" + random.nextInt(10), random.nextInt(10)))); // get a list of the distinct task summary field List<String> resultList = values.stream().filter( t -> t.getDuration() > 5).map( t -> t.getSummary()).distinct().collect(Collectors.toList()); System.out.println(resultList); // get a concatenated string of Task with a duration longer than 5 hours String collect = values.stream().filter( t -> t.getDuration() > 5).map( t -> t.getSummary()).distinct().collect(Collectors.joining("-")); System.out.println(collect); }}

Optional in Java

Optional.If you call a method or access a field on an object which is not initialized (null) you receive a NullPointerException (NPE). Thejava.util.Optional class can be used to avoid these NPEs.java.util.Optional is a good tool to indicate that a return value may be absent, which can be seen directly in the method signature rather than just mentioning that null may be returned in the JavaDoc.If you want to call a method on an Optional object and check some property you can use the filter method. The filter method takes a predicate as an argument. If a value is present in the Optional object and it matches the predicate, the filter method returns that value; otherwise, it returns an empty Optional object.You can create an Optional in different ways:// use this if the object is not null opt = Optional.of(o); // creates an empty Optional, if o is null opt = Optional.ofNullable(o); // create an empty Optional opt = Optional.empty(); The ifPresent method can be used to execute some code on an object if it is present. Assume you have a Todo object and want to call the getId() method on it. You can do this via the following code.Todo todo = new Todo(-1); Optional<Todo> optTodo = Optional.of(todo); // get the id of the todo or a default value optTodo.ifPresent(t-> System.out.println(t.getId())); Via the map method you can transform the object if it is present and via the filter method you can filter for certain values.Todo todo = new Todo(-1); Optional<Todo> optTodo = Optional.of(todo); // get the summary (trimmed) of todo if the id is higher than 0 Optional<String> map = optTodo.filter(o -> o.getId() > 0).map(o -> o.getSummary().trim()); // same as above but print it out optTodo.filter(o -> o.getId() > 0).map(o -> o.getSummary().trim()).ifPresent(System.out::println); To get the real value of an Optional the get() method can be used. But in case the Optional is empty this will throw a NoSuchElementException. To avoid this NoSuchElementException the orElse or the orElseGet can be used to provide a default in case of absence.// using a String String s = "Hello"; Optional<String> maybeS = Optional.of(s); // get length of the String or -1 as default int len = maybeS.map(String::length).orElse(-1); // orElseGet allows to construct an object / value with a Supplier int calStringlen = maybeS.map(String::length).orElseGet(()-> "Hello".length());

System properties in Java

System properties.The System class provides access to the configuratoin of the current working environment. You can access them, viaSystem.getProperty("property_name"), for example System.getProperty("path.separator"); The following lists describes the most important properties."line.separator" - Sequence used by operating system to separate lines in text files"user.dir" - User working directory"user.home" - User home directory == Schedule tasksJava allows you to schedule tasks. A scheduled tasks can perform once or several times.java.util.Timer and java.util.TimerTask can be used to schedule tasks. The object which implementsTimeTask will then be performed by the Timer based on the given interval.package schedule; import java.util.TimerTask; public class MyTask extends TimerTask { private final String string; private int count = 0; public MyTask(String string) { this.string = string; } @Override public void run() { count++; System.out.println(string + " called " + count); } } package schedule; import java.util.Timer; public class ScheduleTest { public static void main(String[] args) { Timer timer = new Timer(); // wait 2 seconds (2000 milli-secs) and then start timer.schedule(new MyTask("Task1"), 2000); for (int i = 0; i < 100; i++) { // wait 1 seconds and then again every 5 seconds timer.schedule(new MyTask("Task " + i), 1000, 5000); } } }

Compare Strings in Java

Compare Strings in JavaTo compare the String objects s1 and s2, use the s1.equals(s2) method.A String comparison with == is incorrect, as == checks for object reference equality. == sometimes gives the correct result, as Java uses a String pool. The following example would work with ==.This would work as expected.String a = "Hello"; String b = "Hello"; if (a==b) { // if statement is true // because String pool is used and // a and b point to the same constant } This comparison would fail.String a = "Hello"; String b = new String("Hello"); if (a==b) { } else { // if statement is false // because String pool is used and // a and b point to the same constant }

The while loop in Java

The while loopA while loop is a repetition control structure that allows you to write a block of code which is executed until a specific condition evaluates to false. The syntax is the following.while(expression) { // block of code to run } The following shows an example for a while loop.public class WhileTest { public static void main(String args[]) { int x = 1; while (x < 10) { System.out.println("value of x : " + x); x++; } } }