Knowledge in Java Multi threading

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

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.

Numbers in java

Numbers in javaPrimitive number types are divided into two groups:Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.Even though there are many numeric types in Java, the most used for numbers are int (for whole numbers) and double (for floating point numbers). However, we will describe them all as you continue to read.

Integer Types

Integer TypesByteThe byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and 127:Examplebyte myNum = 100; System.out.println(myNum); ShortThe short data type can store whole numbers from -32768 to 32767:Exampleshort myNum = 5000; System.out.println(myNum); IntThe int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value.Exampleint myNum = 100000; System.out.println(myNum); LongThe long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L":Examplelong myNum = 15000000000L; System.out.println(myNum);

Floating Point Types

Floating Point TypesYou should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.FloatThe float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "f":Examplefloat myNum = 5.75f; System.out.println(myNum); DoubleThe double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should end the value with a "d":Exampledouble myNum = 19.99d; System.out.println(myNum); Use float or double?The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

JavaScript Introduction

JavaScript Can Change HTML ContentOne of many JavaScript HTML methods is getElementById().This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":Exampledocument.getElementById("demo").innerHTML = "Hello JavaScript";JavaScript accepts both double and single quotes:Exampledocument.getElementById('demo').innerHTML = 'Hello JavaScript';

JavaScript Can Change HTML Styles (CSS)

JavaScript Can Change HTML Styles (CSS)Changing the style of an HTML element, is a variant of changing an HTML attribute:Exampledocument.getElementById("demo").style.fontSize = "35px";JavaScript Can Hide HTML ElementsHiding HTML elements can be done by changing the display style:Exampledocument.getElementById("demo").style.display = "none";JavaScript Can Show HTML ElementsShowing hidden HTML elements can also be done by changing the display style:Exampledocument.getElementById("demo").style.display = "block";

JavaScript Where To

JavaScript Where ToThe <script> TagIn HTML, JavaScript code must be inserted between <script> and </script> tags.Example<script>document.getElementById("demo").innerHTML = "My First JavaScript";</script>Old JavaScript examples may use a type attribute: <script type="text/javascript">.The type attribute is not required. JavaScript is the default scripting language in HTML.JavaScript Functions and EventsA JavaScript function is a block of JavaScript code, that can be executed when "called" for.For example, a function can be called when an event occurs, like when the user clicks a button.You will learn much more about functions and events in later chapters.JavaScript in <head> or <body>You can place any number of scripts in an HTML document.Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.JavaScript in <head>In this example, a JavaScript function is placed in the <head> section of an HTML page.The function is invoked (called) when a button is clicked:Example<!DOCTYPE html><html><head><script>function myFunction() {  document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></head><body><h1>A Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button></body></html>

Semicolons ;

Semicolons ;Semicolons separate JavaScript statements.Add a semicolon at the end of each executable statement:var a, b, c;     // Declare 3 variablesa = 5;           // Assign the value 5 to ab = 6;           // Assign the value 6 to bc = a + b;       // Assign the sum of a and b to cWhen separated by semicolons, multiple statements on one line are allowed:a = 5; b = 6; c = a + b;On the web, you might see examples without semicolons.Ending statements with semicolon is not required, but highly recommended.JavaScript White SpaceJavaScript ignores multiple spaces. You can add white space to your script to make it more readable.The following lines are equivalent:var person = "Hege";var person="Hege";A good practice is to put spaces around operators ( = + - * / ):var x = y + z;JavaScript Line Length and Line BreaksFor best readability, programmers often like to avoid code lines longer than 80 characters.If a JavaScript statement does not fit on one line, the best place to break it is after an operator:Exampledocument.getElementById("demo").innerHTML ="Hello Dolly!";JavaScript Code BlocksJavaScript statements can be grouped together in code blocks, inside curly brackets {...}.The purpose of code blocks is to define statements to be executed together.One place you will find statements grouped together in blocks, is in JavaScript functions:Examplefunction myFunction() {  document.getElementById("demo1").innerHTML = "Hello Dolly!";  document.getElementById("demo2").innerHTML = "How are you?";}In this tutorial we use 2 spaces of indentation for code blocks.You will learn more about functions later in this tutorial.