Knowledge in java all notes

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.

Java: array lists

this file will give you the basic way of using arrays in java. it includes how to declare it , how to use it, how to access it, and all the basics you need to know about array lists to use in java. do refer to this and enjoy learning

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 Quickstart

Java QuickstartIn Java, every application begins with a class name, and that class must match the filename.Let's create our first Java file, called MyClass.java, which can be done in any text editor (like Notepad).The file should contain a "Hello World" message, which is written with the following code:MyClass.javapublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } }

Java Quickstart 2

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code above.Save the code in Notepad as "MyClass.java". Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type "javac MyClass.java":C:\Users\Your Name>javac MyClass.javaThis will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type "java MyClass" to run the file:C:\Users\Your Name>java MyClassThe output should read:Hello Worldpublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } } Output.C:\Users\Name\java MyClassHello World

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