Knowledge in Java Collection

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++; } } }

Switch in Java

SwitchThe switch statement can be used to handle several alternatives if they are based on the same constant value.switch (expression) { case constant1: command; break; // will prevent that the other cases or also executed case constant2: command; break; ... default: } // Example: switch (cat.getLevel()) { case 0: return true; case 1: if (cat.getLevel() == 1) { if (cat.getName().equalsIgnoreCase(req.getCategory())) { return true; } } case 2: if (cat.getName().equalsIgnoreCase(req.getSubCategory())) { return true; } } // you can also use the same logic for different constants public static void main(String[] args) { for (int i = 0; i < 6; i++) { switch (i) { case 1: case 5: System.out.println("Hello"); break; default: System.out.println("Default"); break; } } } }

Base Java language structure

Base Java language structure1)ClassA class is a template that describes the data and behavior associated with an instance of that class.A class is defined by the class keyword and must start with a capital letter. The body of a class is surrounded by {}.package test; class MyClass { } The data associated with a class is stored in variables ; the behavior associated to a class or object is implemented withmethods.A class is contained in a text file with the same name as the class plus the .java extension. It is also possible to define inner classes, these are classes defined within another class, in this case you do not need a separate file for this class2)ObjectAn object is an instance of a class.The object is the real element which has data and can perform actions. Each object is created based on the class definition. The class can be seen as the blueprint of an object, i.e., it describes how an object is created.

What is Java?

Java is a popular programming language, created in 1995.It is owned by Oracle, and more than 3 billion devices run Java.It is used for:Mobile applications (specially Android apps)Desktop applicationsWeb applicationsWeb servers and application serversGamesDatabase connectionAnd much, much more!

Why Use Java?

Why Use Java?Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)It is one of the most popular programming language in the worldIt is easy to learn and simple to useIt is open-source and freeIt is secure, fast and powerfulIt has a huge community support (tens of millions of developers)

Java Syntax

Java SyntaxIn the previous chapter, we created a Java file called MyClass.java, and we used the following code to print "Hello World" to the screen:MyClass.javapublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } } Example explainedEvery line of code that runs in Java must be inside a class. In our example, we named the class MyClass. A class should always start with an uppercase first letter.Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename. To run the example above on your computer, make sure that Java is properly installed: Go to the Get Started Chapter for how to install Java. The output should be:Hello World

The main Method

The main MethodThe main() method is required and you will see it in every Java program:public static void main(String[] args) Any code inside the main() method will be executed. You don't have to understand the keywords before and after main. You will get to know them bit by bit while reading this tutorial.For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.System.out.println()Inside the main() method, we can use the println() method to print a line of text to the screen:public static void main(String[] args) { System.out.println("Hello World"); } Note: In Java, each code statement must end with a semicolon.Test Yourself With ExercisesExercise:Insert the missing part of the code below to output "Hello World".public class MyClass { public static void main(String[] args) { ..("Hello World"); } }

Java Comments

Java CommentsComments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.Single-line comments start with two forward slashes (//).Any text between // and the end of the line is ignored by Java (will not be executed).This example uses a single-line comment before a line of code:Example// This is a comment System.out.println("Hello World"); This example uses a single-line comment at the end of a line of code:ExampleSystem.out.println("Hello World"); // This is a comment Java Multi-line CommentsMulti-line comments start with /* and ends with */.Any text between /* and */ will be ignored by Java.This example uses a multi-line comment (a comment block) to explain the code:Example/* The code below will print the words Hello World to the screen, and it is amazing */ System.out.println("Hello World");

Java Variables

Java VariablesVariables are containers for storing data values.In Java, there are different types of variables, for example:String - stores text, such as "Hello". String values are surrounded by double quotesint - stores integers (whole numbers), without decimals, such as 123 or -123float - stores floating point numbers, with decimals, such as 19.99 or -19.99char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotesboolean - stores values with two states: true or falseDeclaring (Creating) VariablesTo create a variable, you must specify the type and assign it a value:Syntaxtype variable = value; Where type is one of Java's types (such as int or String), and variable is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.To create a variable that should store text, look at the following example:ExampleCreate a variable called name of type String and assign it the value "John":String name = "John"; System.out.println(name); To create a variable that should store a number, look at the following example:ExampleCreate a variable called myNum of type int and assign it the value 15:int myNum = 15; System.out.println(myNum); You can also declare a variable without assigning the value, and assign the value later:Exampleint myNum; myNum = 15; System.out.println(myNum); A demonstration of how to declare variables of other types:Exampleint myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello";