JavaScript

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 applications
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection
  • And much, much more!

Java
  1. Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  2. It is one of the most popular programming language in the world
  3. It has a large demand in the current job market
  4. It is easy to learn and simple to use
  5. It is open-source and free
  6. It is secure, fast and powerful
  7. It has a huge community support (tens of millions of developers)
  8. Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
  9. As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
  1. Java Syntax
    Java Syntax
    The curly braces {} marks the beginning and the end of a block of code.

    System is a built-in Java class that contains useful members, such as out, which is short for "output". The println() method, short for "print line", is used to print a value to the screen (or a file).

    Don't worry too much about System, out and println(). Just know that you need them together to print stuff to the screen.

    You should also note that each code statement must end with a semicolon (;).
                         
                            public class Main {
                                public static void main(String[] args) {
                                  System.out.println("Hello World");
                                }
                              }
                            
    
  2. Print Text
    Print Text
    1) The Print() Method
    There is also a print() method, which is similar to println().
    The only difference is that it does not insert a new line at the end of the output


    2) Println()
    You can add as many println() methods as you want. Note that it will add a new line for each method

    Print()

                     
                    System.out.print("I will print on the same line.");
                
            

    Println()

                     
                    System.out.println("Hello World!");
                
            
  3. Java Comments
    Java Comments
    Comments 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
    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).

    Java Multi-line Comments
    Multi-line comments start with /* and ends with */.
    Any text between /* and */ will be ignored by Java.

    single linecomment

        
            // This is a comment
    
    

    Multi-Line comments

        
            /* The code below will print the words Hello World
    to the screen, and it is amazing */
    
    
  4. Java Variables
    Java Variables
    Variables are containers for storing data values.

    In Java, there are different types of variables, for example:
    1. String - stores text, such as "Hello". String values are surrounded by double quotes
    2. int - stores integers (whole numbers), without decimals, such as 123 or -123
    3. float - stores floating point numbers, with decimals, such as 19.99 or -19.99
    4. char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
    5. boolean - stores values with two states: true or false


    Final Variables
    If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only)

    Declaring (Creating) Variables (Syntax)

        
            type variableName = value;
    
    

    Final Variables

    
        final int myNum = 15;
    
    
  5. Identifiers
    Identifiers
    All Java variables must be identified with unique names.
    These unique names are called identifiers.
    Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

    Note: It is recommended to use descriptive names in order to create understandable and maintainable code

    The general rules for naming variables are:
    Names can contain letters, digits, underscores, and dollar signs
    Names must begin with a letter
    Names should start with a lowercase letter and it cannot contain whitespace
    Names can also begin with $ and _ (but we will not use it in this tutorial)
    Names are case sensitive ("myVar" and "myvar" are different variables)
    Reserved words (like Java keywords, such as int or boolean) cannot be used as names
  6. Java Data Types
    Java Data Types
    Data types are divided into two groups:

    1)Primitive data types - includes byte, short, int, long, float, double, boolean and char
    2)Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)
    Non-primitive data types are called reference types because they refer to objects.
    The main difference between primitive and non-primitive data types are:
    Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
    Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
    A primitive type has always a value, while non-primitive types can be null.
    A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
    The size of a primitive type depends on the data type, while non-primitive types have all the same size.

    1) Primitive Data Types
    A primitive data type specifies the size and type of variable values, and it has no additional methods.
    There are eight primitive data types in Java:

    Data Type Size Description
    byte 1 byte Stores whole numbers from -128 to 127
    short 2 bytes Stores whole numbers from -32,768 to 32,767
    int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
    long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
    double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
    boolean 1 bit Stores true or false values
    char 2 bytes Stores a single character/letter or ASCII values


    Primitive number types are divided into two groups:

    A) 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.


    B) Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.

    3)Boolean Types:Very often in programming, you will need a data type that can only have one of two values, like:

    YES / NO
    ON / OFF
    TRUE / FALSE
    For this, Java has a boolean data type, which can only take the values true or false

    4)Characters:
    The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'

    5)Strings:
    The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes

    Premitive number type : Integer type

                                    
                                        byte myNum = 100;    
                                
                                

                                    
                                        short myNum = 5000;
                                
                                

                                    
                                        int myNum = 100000;      
                                
                                

                                      
                                        long myNum = 15000000000L;     
                                  
                                  


    Premitive number type : Floating Point Types

                                      
                                        float myNum = 5.75f;    
                                  
                                  

                                      
                                        double d1 = 12E4d;
                                  
                                  


    Boolean Types

                            
                                boolean isJavaFun = true;    
                        
                        

    Characters

                            
                                char myGrade = 'B';   
                        
                        

    Strings

                            
                                String greeting = "Hello World";    
                        
                        
  7. Java Type Casting
    Java Type Casting
    Type casting is when you assign a value of one primitive data type to another type.
    In Java, there are two types of casting:
    Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double

    Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte

    Widening Casting

                                
                                    int myInt = 9;
                                    double myDouble = myInt; // Automatic casting: int to double  
                            
                            

    Narrowing Casting

                                
                                    double myDouble = 9.78d;
        int myInt = (int) myDouble; // Manual casting: double to int
                            
                            
  8. Java Operators
    Java Operators
    Operators are used to perform operations on variables and values.

    Java divides the operators into the following groups:
    1) Arithmetic operators
    2) Assignment operators
    3) Comparison operators
    4) Logical operators
    5) Bitwise operators


    1)Arithmetic Operators
    Arithmetic operators are used to perform common mathematical operations.
    Operator Name Description Example
    + Addition Adds together two values x + y
    - Subtraction Subtracts one value from another x - y
    * Multiplication Multiplies two values x * y
    / Division Divides one value by another x / y
    % Modulus Returns the division remainder x % y
    ++ Increment Increases the value of a variable by 1 ++x
    -- Decrement Decreases the value of a variable by 1 --x


    2) Java Assignment Operators
    Assignment operators are used to assign values to variables.

    Operator Example Same As
    = x = 5 x = 5
    += x += 3 x = x + 3
    -= x -= 3 x = x - 3
    *= x *= 3 x = x * 3
    /= x /= 3 x = x / 3
    %= x %= 3 x = x % 3
    &= x &= 3 x = x & 3
    |= x |= 3 x = x | 3
    ^= x ^= 3 x = x ^ 3
    >>= x >>= 3 x = x >> 3
    <<= x <<= 3 x = x << 3


    3) Java Comparison Operators
    Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

    The return value of a comparison is either true or false.
    Operator Name Example
    == Equal to x == y
    != Not equal x != y
    > Greater than x > y
    < Less than x < y
    >= Greater than or equal to x >= y
    <= Less than or equal to x <= y


    4)Java Logical Operators
    You can also test for true or false values with logical operators.
    Operator Name Description Example
    &&  Logical and Returns true if both statements are true x < 5 &&  x < 10
    ||  Logical or Returns true if one of the statements is true x < 5 || x < 4
    ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
  9. Java Strings
    Java Strings
    Strings are used for storing text.

    A String variable contains a collection of characters surrounded by double quotes

    String declare

        
            String greeting = "Hello";
    
    

    String Length

        
            String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    System.out.println("The length of the txt string is: " + txt.length());
    
    

    Finding a Character in a String

        
            String txt = "Please locate where 'locate' occurs!";
            System.out.println(txt.indexOf("locate")); // Outputs 7
    
    

    String Concatenation

                    
    System.out.println("Doe" + " " + "John");
                
                

                    
                        System.out.println("Doe" + " " +.concat("John"));
                
  10. Java Special Characters
    Java Special Characters
    Escape character Result Description
    \' ' Single quote
    \" " Double quote
    \\ \ Backslash


    Code Result
    \n New Line
    \r Carriage Return
    \t Tab
    \b Backspace
    \f Form Feed
  11. Java Math

                                        
                                            Math.max(5, 10);     
                                    
                                    

                                    
                                        Math.min(5, 10);
                                
                                

                                        
                                            Math.sqrt(64);    
                                    
                                    

                                        
                                            Math.abs(-4.7);  
                                    
                                    

                                        
                                            Math.random();
                                    
                                    
  12. Java Conditions and If Statements
    Java Conditions and If Statements
    Java has the following conditional statements:

    1) Use if to specify a block of code to be executed, if a specified condition is true
    2) Use else to specify a block of code to be executed, if the same condition is false
    3) Use else if to specify a new condition to test, if the first condition is false
    4) Use switch to specify many alternative blocks of code to be executed


    Switch:
    This is how it works:
    The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. The break and default keywords are optional, and will be described later in this chapter

                                            
                                                if (condition) {
                                                    // block of code to be executed if the condition is true
                                                  }
                                        
                                        

                                        
                                            if (condition) {
                                                // block of code to be executed if the condition is true
                                              } else {
                                                // block of code to be executed if the condition is false
                                              }
                                    
                                    

                                            
                                                if (condition1) {
                                                    // block of code to be executed if condition1 is true
                                                  } else if (condition2) {
                                                    // block of code to be executed if the condition1 is false and condition2 is true
                                                  } else {
                                                    // block of code to be executed if the condition1 is false and condition2 is false
                                                  }  
                                        
                                        

                                            
                                                variable = (condition) ? expressionTrue :  expressionFalse;
                                        
                                        

                                            
                                                switch(expression) {
                                                    case x:
                                                      // code block
                                                      break;
                                                    case y:
                                                      // code block
                                                      break;
                                                    default:
                                                      // code block
                                                  }
                                        
                                        
  13. Loops
    Loops
    Loops can execute a block of code as long as a specified condition is reached.
    Loops are handy because they save time, reduce errors, and they make code more readable.

    1) Java While Loop
    The while loop loops through a block of code as long as a specified condition is true

    2) The Do/While Loop
    The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

    3) Java For Loop
    When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop

                                            
                                                while (condition) {
                                                    // code block to be executed
                                                  }     
                                        
                                        

                                        
                                            do {
                                                // code block to be executed
                                              }
                                              while (condition);
                                    
                                    

                                            
                                                for (int i = 0; i < 5; i++) {
                                                    
    
                                                  }   
                                        
                                        

                                            
                                                for (type variableName : arrayName) {
                                                    // code block to be executed
                                                  }  
                                        
                                        
  14. Java Break
    Java Break
    You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.

    The break statement can also be used to jump out of a loop.
                        
                            break;
                        
                        
  15. Java Continue
    Java Continue
    The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
                        
                            continue;
                        
                        
  16. Java Arrays
    Java Arrays
    Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

    To declare an array, define the variable type with square brackets
    
        String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    
    
  17. Multidimensional Arrays
    Multidimensional Arrays
    A multidimensional array is an array of arrays.
    Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and columns.
                        
                            int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
                        
                        
  18. Java Methods
    Java Methods
    A method is a block of code which only runs when it is called.You can pass data, known as parameters, into a method.
    Methods are used to perform certain actions, and they are also known as functions.

    Create a Method:
    A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions

    Explained
    1) myMethod() is the name of the method
    2) static means that the method belongs to the Main class and not an object of the Main class.
    3) void means that this method does not have a return value.
                        
                            public class Main {
                                static void myMethod() {
                                  // code to be executed
                                }
                              }
                        
                        
  19. Parameters and Arguments
    Parameters and Arguments
    Information can be passed to methods as parameter. Parameters act as variables inside the method.

    Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

    When a parameter is passed to the method, it is called an argument.


    Multiple Parameters:
    Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
  20. Return Values
    Return Values
    The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method
  21. Method Overloading
    Method Overloading
    With method overloading, multiple methods can have the same name with different parameters

    Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.
                
    int myMethod(int x)
    float myMethod(float x)
    double myMethod(double x, double y)
                
            
  22. Java Scope
    Java Scope
    In Java, variables are only accessible inside the region they are created. This is called scope.

    1) Method Scope :
    Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared

    2) Block Scope :
    A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared
  23. Java Recursion
    Java Recursion
    Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

    Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.
  24. Halting Condition
    Halting Condition
    Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself.
  25. Java OOP
    Java OOP
    OOP stands for Object-Oriented Programming.
    Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

    Object-oriented programming has several advantages over procedural programming:
    1. OOP is faster and easier to execute
    2. OOP provides a clear structure for the programs
    3. OOP makes it possible to create full reusable applications with less code and shorter development time
    4. OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug


    OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  26. Java Classes/Objects
    Java Classes/Objects
    Java is an object-oriented programming language.

    Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

    Create a Class

                        
                          public class Main {
                            
                          }
                        
                        

    Create a object

                        
                            Main myObj = new Main();
                        
                        
  27. Static vs. Public
    Static vs. Public
    You will often see Java programs that have either static or public attributes and methods.

    In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects

    Static method

                        
                            // Static method
      static void myStaticMethod() {
        
      }
                        
                        

    Public method

                            
                                // Public method
      public void myPublicMethod() {
        
      }
                            
                            

    Main method

                                
                                    // Main method
      public static void main(String[] args) {
       
      }
                                
                                
  28. Java Constructors
    Java Constructors
    A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes

    Note that the constructor name must match the class name, and it cannot have a return type (like void).

    Also note that the constructor is called when the object is created.

    All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
  29. Java Modifiers
    Java Modifiers
    The text-align-last property specifies how to align the last line of a text.

    We divide modifiers into two groups:
    1) Access Modifiers - controls the access level
    2) Non-Access Modifiers - do not control access level, but provides other functionality

    1) Access Modifiers
    For classes, you can use either public or default

    Modifier Description
    public The class is accessible by any other class
    default The class is only accessible by classes in the same package. This is used when you don't specify a modifier.
    For attributes, methods and constructors, you can use the one of the following:
    Modifier Description
    public The code is accessible for all classes
    private The code is only accessible within the declared class
    default The code is only accessible in the same package. This is used when you don't specify a modifier.
    protected The code is accessible in the same package and subclasses


    Non-Access Modifiers For classes, you can use either final or abstract
    Modifier Description
    final The class cannot be inherited by other classes
    abstract The class cannot be used to create objects

    For attributes and methods, you can use the one of the following:
    Modifier Description
    final Attributes and methods cannot be overridden/modified
    static Attributes and methods belongs to the class, rather than an object
    abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from)
    transient Attributes and methods are skipped when serializing the object containing them
    synchronized Methods can only be accessed by one thread at a time
    volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory"

                                        
                                            final double PI = 3.14;
                                        
                                        

                                        
                                            static void myStaticMethod() {
    
                                            }
                                        
                                        

                                        
                                            public abstract void study(); // abstract method
                                            
                                        
  30. Encapsulation
    Encapsulation
    The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
    1) declare class variables/attributes as private
    2) provide public get and set methods to access and update the value of a private variable

    Why Encapsulation?
    1) Better control of class attributes and methods
    2) Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
    3_ Flexible: the programmer can change one part of the code without affecting other parts Increased security of data


    Get and Set
    You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.
    The get method returns the variable value, and the set method sets the value.
                                
                                    public class Person {
                                        private String name; // private = restricted access
                                      
                                        // Getter
                                        public String getName() {
                                          return name;
                                        }
                                      
                                        // Setter
                                        public void setName(String newName) {
                                          this.name = newName;
                                        }
                                      }
                                
                                
  31. Java Packages & API
    Java Packages & API
    A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

    1) Built-in Packages (packages from the Java API)
    2) User-defined Packages (create your own packages)


    1) Built-in Packages
    The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.
    The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.
    The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.
                                
                                    import package.name.Class;   // Import a single class
                                    import package.name.*;   // Import the whole package
                                
                                
  32. User-defined Packages
    User-defined Packages
    To create a package, use the package keyword
                                
                                    package mypack;
                                
                                
  33. Java Inheritance
    Java Inheritance
    In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

    1) subclass (child) - the class that inherits from another class
    2) superclass (parent) - the class being inherited from To inherit from a class, use the extends keyword.


                        
                            class Vehicle {
                                
                              }
                              class Car extends Vehicle {
    
                              }
                        
                        
  34. Java Polymorphism
    Java Polymorphism
    Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

    Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
  35. Java Inner Classes
    Java Inner Classes
    In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

    To access the inner class, create an object of the outer class, and then create an object of the inner class
  36. Java Abstraction
    Java Abstraction
    Abstract Classes and Methods:
    Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces.

    The abstract keyword is a non-access modifier, used for classes and methods:
    Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

    Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
                        
                            abstract class Animal {
                                public abstract void animalSound();
                               
                                 
                                }
                              }
                        
                        
  37. Java Interface
    Java Interface
    Another way to achieve abstraction in Java, is with interfaces.
    An interface is a completely "abstract class" that is used to group related methods with empty bodies

    To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class
    Notes on Interfaces:
    • Like abstract classes, interfaces cannot be used to create objects
    • Interface methods do not have a body - the body is provided by the "implement" class
    • On implementation of an interface, you must override all of its methods
    • Interface methods are by default abstract and public
    • Interface attributes are by default public, static and final
    • An interface cannot contain a constructor


    Why And When To Use Interfaces?
    1) To achieve security - hide certain details and only show the important details of an object (interface).

    2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma
  38. Java Enums
    Java Enums
    An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

    To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters


    Enum is short for "enumerations", which means "specifically listed".


    Difference between Enums and Classes
    An enum can, just like a class, have attributes and methods. The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden).

    An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

    Why And When To Use Enums?
    Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.
                                    
                                        enum Level {
                                            LOW,
                                            MEDIUM,
                                            HIGH
                                          } 
                                    
                                    
  39. Java User Input
    Java User Input
    The Scanner class is used to get user input, and it is found in the java.util package.

    To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings

    Input Types
    Method Description
    nextBoolean() Reads a boolean value from the user
    nextByte() Reads a byte value from the user
    nextDouble() Reads a double value from the user
    nextFloat() Reads a float value from the user
    nextInt() Reads a int value from the user
    nextLine() Reads a String value from the user
    nextLong() Reads a long value from the user
    nextShort() Reads a short value from the user
                                    
                                        import java.util.Scanner;  // Import the Scanner class
    
                                        class Main {
                                          public static void main(String[] args) {
                                            Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    
                                            String userName = myObj.nextLine();  // Read user input
                                        
                                          }
                                        } 
                                    
                                    
  40. Java Date and Time
    Java Date and Time
    Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API.
    Class Description
    LocalDate Represents a date (year, month, day (yyyy-MM-dd))
    LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
    LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
    DateTimeFormatter Formatter for displaying and parsing date-time objects

    Display Current Date

                                            
                                                import java.time.LocalDate; // import the LocalDate class
    
                                                public class Main {
                                                  public static void main(String[] args) {
                                                    LocalDate myObj = LocalDate.now(); // Create a date object
                                                    System.out.println(myObj); // Display the current date
                                                  }
                                                }
                                            
                                            
  41. Java ArrayList
    Java ArrayList
    The ArrayList class is a resizable array, which can be found in the java.util package.

    The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different

                                                
                                                    import java.util.ArrayList; // import the ArrayList class
            
                                                    ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
                                                
                                                

                                                
                                                    cars.add("Volvo");
                                                
                                                

                                                
                                                    cars.get(0);
                                                
                                                

                                                  
                                                    cars.set(0, "Opel");
                                                  
                                                  

                                                  
                                                    cars.remove(0);
                                                  
                                                  

                                                  
                                                    cars.clear();
                                                  
                                                  

                                                  
                                                    cars.size();
                                                  
                                                  

                                                  
                                                    for (int i = 0; i < cars.size(); i++) {
                                                        System.out.println(cars.get(i));
                                                      }
                                                  
                                                  

                                                  
                                                    Collections.sort(cars);  // Sort cars
                                                  
                                                  
  42. Java LinkedList
    Java LinkedList
    ArrayList vs. LinkedList The LinkedList class is a collection which can contain many objects of the same type, just like the ArrayList.

    The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, change items, remove items and clear the list in the same way.

    However, while the ArrayList class and the LinkedList class can be used in the same way, they are built very differently.

    How the ArrayList works The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.

    How the LinkedList works The LinkedList stores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.

    When To Use Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.

    LinkedList Methods

    Method Description
    addFirst() Adds an item to the beginning of the list.
    addLast() Add an item to the end of the list
    removeFirst() Remove an item from the beginning of the list.
    removeLast() Remove an item from the end of the list
    getFirst() Get the item at the beginning of the list
    getLast() Get the item at the end of the list
                                                
                                                    // Import the LinkedList class
                                                    import java.util.LinkedList;
                                                    
                                                    public class Main {
                                                      public static void main(String[] args) {
                                                        LinkedList cars = new LinkedList();
                                                       
                                                      }
                                                    }
                                                
                                                
  43. Java HashMap
    Java HashMap
    In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number (int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

    One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values

                                                
                                                    import java.util.HashMap; // import the HashMap class
    
    HashMap<String, String> capitalCities = new HashMap<String, String>();
                                                
                                                

                                                
                                                    capitalCities.put("England", "London");
                                                
                                                

                                                
                                                    capitalCities.get("England");
                                                
                                                

                                                  
                                                    capitalCities.remove("England");
                                                  
                                                  

                                                  
                                                    capitalCities.clear();
                                                  
                                                  

                                                  
                                                    capitalCities.size();
                                                  
                                                  

                                                  
                                                    // Print keys
                                                    for (String i : capitalCities.keySet()) {
                                                      System.out.println(i);
                                                    }
                                                  
                                                  
  44. Java HashSet
    Java HashSet
    A HashSet is a collection of items where every item is unique, and it is found in the java.util package

                                                
                                                    import java.util.HashSet; // Import the HashSet class
    
    HashSet<String>  cars = new HashSet<String>();
                                                
                                                

                                                                                        
        cars.add("Volvo");
       
                                                
                                                

                                                
                                                    cars.contains("Mazda");
                                                
                                                

                                                  
                                                    cars.remove("Volvo");
                                                  
                                                  

                                                  
                                                    capitalCities.clear();
                                                  
                                                  

                                                  
                                                    cars.size();
                                                  
                                                  

                                                  
                                                    for (String i : cars) {
                                                        System.out.println(i);
                                                      }
                                                  
                                                  
  45. Java Iterator
    Java Iterator
    An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.

    To use an Iterator, you must import it from the java.util package.


    Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.

                                                
                                                    import java.util.Iterator;
                                                    // Get the iterator
        Iterator<String> it = cars.iterator();
    
        // Print the first item
        System.out.println(it.next());
                                                
                                                

                                                
                                                    while(it.hasNext()) {
                                                       
                                                        
                                                      }
                                                
                                                

                                                
                                                    while(it.hasNext()) {
                                                        Integer i = it.next();
                                                        if(i < 10) {
                                                          it.remove();
                                                        }
                                                      }
                                                
                                                
  46. Java Wrapper Classes
    Java Wrapper Classes
    Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

    The table below shows the primitive type and the equivalent wrapper class:
    Primitive Data Type Wrapper Class
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    boolean Boolean
    char Character
  47. Java Exceptions
    Java Exceptions
    When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

    When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).


    Java try and catch
    The try statement allows you to define a block of code to be tested for errors while it is being executed.

    The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


    Finally
    The finally statement lets you execute code, after try...catch, regardless of the result
                            
                                try {
                                    //  Block of code to try
                                  }
                                  catch(Exception e) {
                                    //  Block of code to handle errors
                                  }finally {
                                    // After 'try catch' is finished 
                                  }
                            
                            
  48. The throw keyword
    The throw keyword
    The throw statement allows you to create a custom error.

    The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc
                        
                            throw new ArithmeticException("Access denied - You must be at least 18 years old.");
                        
                        
  49. Java Regular Expressions
    Java Regular Expressions
    A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

    A regular expression can be a single character, or a more complicated pattern.

    Regular expressions can be used to perform all types of text search and text replace operations.

    Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions. The package includes the following classes:


    Pattern Class - Defines a pattern (to be used in a search)
    Matcher Class - Used to search for the pattern
    PatternSyntaxException Class - Indicates syntax error in a regular expression pattern


    Flags
    Flags in the compile() method change how the search is performed. Here are a few of them:

    Pattern.CASE_INSENSITIVE - The case of letters will be ignored when performing a search.
    Pattern.LITERAL - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.
    Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet


    Regular Expression Patterns
    The first parameter of the Pattern.compile() method is the pattern. It describes what is being searched for.
    Brackets are used to find a range of character
    Expression Description
    [abc] Find one character from the options between the brackets
    [^abc] Find one character NOT between the brackets
    [0-9] Find one character from the range 0 to 9
    Metacharacters Metacharacters are characters with a special meaning:
    Metacharacter Description
    | Find a match for any one of the patterns separated by | as in: cat|dog|fish
    . Find just one instance of any character
    ^ Finds a match as the beginning of a string as in: ^Hello
    $ Finds a match at the end of the string as in: World$
    \d Find a digit
    \s Find a whitespace character
    \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
    \uxxxx Find the Unicode character specified by the hexadecimal number xxxx
    Quantifiers Quantifiers define quantities:
    Quantifier Description
    n+ Matches any string that contains at least one n
    n* Matches any string that contains zero or more occurrences of n
    n? Matches any string that contains zero or one occurrences of n
    n{x} Matches any string that contains a sequence of X n's
    n{x,y} Matches any string that contains a sequence of X to Y n's
    n{x,} Matches any string that contains a sequence of at least X n's
                    
                        import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
      public static void main(String[] args) {
        Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher("Visit W3Schools!");
        boolean matchFound = matcher.find();
        if(matchFound) {
          System.out.println("Match found");
        } else {
          System.out.println("Match not found");
        }
      }
    }
                    
                    
  50. Java Threads
    Java Threads
    Threads allows a program to operate more efficiently by doing multiple things at the same time.

    Threads can be used to perform complicated tasks in the background without interrupting the main program.

    created by extending the Thread class

                
                    public class Main extends Thread {
                        public void run() {
                          System.out.println("This code is running in a thread");
                        }
                      }
                
                

    create a thread is to implement the Runnable interface

                    
                        public class Main implements Runnable {
                            public void run() {
                              System.out.println("This code is running in a thread");
                            }
                          }
                    
                    

    Running Threads

                    
                        Main thread = new Main();
                        thread.start();
                    
                    
  51. Java Files
    Java Files
    File handling is an important part of any application.

    Java has several methods for creating, reading, updating, and deleting files.


    Java File Handling:
    The File class from the java.io package, allows us to work with files.

    To use the File class, create an object of the class, and specify the filename or directory name

    The File class has many useful methods for creating and getting information about files. For example:
    Method Type Description
    canRead() Boolean Tests whether the file is readable or not
    canWrite() Boolean Tests whether the file is writable or not
    createNewFile() Boolean Creates an empty file
    delete() Boolean Deletes a file
    exists() Boolean Tests whether the file exists
    getName() String Returns the name of the file
    getAbsolutePath() String Returns the absolute pathname of the file
    length() Long Returns the size of the file in bytes
    list() String[] Returns an array of the files in the directory
    mkdir() Boolean Creates a directory

                                    
                                        import java.io.File;  // Import the File class
    
                                        File myObj = new File("filename.txt"); // Specify the filename
                                    
                                    

                                    
                                        import java.io.File;  // Import the File class
                                        import java.io.IOException;  // Import the IOException class to handle errors
                                        
                                        public class CreateFile {
                                          public static void main(String[] args) {
                                            try {
                                              File myObj = new File("filename.txt");
                                              if (myObj.createNewFile()) {
                                                System.out.println("File created: " + myObj.getName());
                                              } else {
                                                System.out.println("File already exists.");
                                              }
                                            } catch (IOException e) {
                                              System.out.println("An error occurred.");
                                              e.printStackTrace();
                                            }
                                          }
                                        }
                                    
                                    

                                    
                                        import java.io.FileWriter;   // Import the FileWriter class
                                        import java.io.IOException;  // Import the IOException class to handle errors
                                        
                                        public class WriteToFile {
                                          public static void main(String[] args) {
                                            try {
                                              FileWriter myWriter = new FileWriter("filename.txt");
                                              myWriter.write("Files in Java might be tricky, but it is fun enough!");
                                              myWriter.close();
                                              System.out.println("Successfully wrote to the file.");
                                            } catch (IOException e) {
                                              System.out.println("An error occurred.");
                                              e.printStackTrace();
                                            }
                                          }
                                        }
                                    
                                    

                                    
                                        import java.io.File;  // Import the File class
    import java.io.FileNotFoundException;  // Import this class to handle errors
    import java.util.Scanner; // Import the Scanner class to read text files
    
    public class ReadFile {
      public static void main(String[] args) {
        try {
          File myObj = new File("filename.txt");
          Scanner myReader = new Scanner(myObj);
          while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            System.out.println(data);
          }
          myReader.close();
        } catch (FileNotFoundException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }
      }
    }              
                                    

                                    
                                        import java.io.File;  // Import the File class
    
                                        public class GetFileInfo { 
                                          public static void main(String[] args) {
                                            File myObj = new File("filename.txt");
                                            if (myObj.exists()) {
                                              System.out.println("File name: " + myObj.getName());
                                              System.out.println("Absolute path: " + myObj.getAbsolutePath());
                                              System.out.println("Writeable: " + myObj.canWrite());
                                              System.out.println("Readable " + myObj.canRead());
                                              System.out.println("File size in bytes " + myObj.length());
                                            } else {
                                              System.out.println("The file does not exist.");
                                            }
                                          }
                                        }
                                    
                                    

                                    
                                        import java.io.File;  // Import the File class
    
                                        public class DeleteFile {
                                          public static void main(String[] args) { 
                                            File myObj = new File("filename.txt"); 
                                            if (myObj.delete()) { 
                                              System.out.println("Deleted the file: " + myObj.getName());
                                            } else {
                                              System.out.println("Failed to delete the file.");
                                            } 
                                          } 
                                        }
                                    
                                    

                                    
                                        import java.io.File; 
    
                                        public class DeleteFolder {
                                          public static void main(String[] args) { 
                                            File myObj = new File("C:\\Users\\MyName\\Test"); 
                                            if (myObj.delete()) { 
                                              System.out.println("Deleted the folder: " + myObj.getName());
                                            } else {
                                              System.out.println("Failed to delete the folder.");
                                            } 
                                          } 
                                        }
                                    
                                    
  52. Java Reserved Keywords
    Java Reserved Keywords
    Keyword Description
    abstract A non-access modifier. Used for classes and methods: An abstract class cannot be used to create objects (to access it, it must be inherited from another class). An abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from)
    assert For debugging
    boolean A data type that can only store true and false values
    break Breaks out of a loop or a switch block
    byte A data type that can store whole numbers from -128 and 127
    case Marks a block of code in switch statements
    catch Catches exceptions generated by try statements
    char A data type that is used to store a single character
    class Defines a class
    continue Continues to the next iteration of a loop
    const Defines a constant. Not in use - use final instead
    default Specifies the default block of code in a switch statement
    do Used together with while to create a do-while loop
    double A data type that can store whole numbers from 1.7e−308 to 1.7e+308
    else Used in conditional statements
    enum Declares an enumerated (unchangeable) type
    exports Exports a package with a module. New in Java 9
    extends Extends a class (indicates that a class is inherited from another class)
    final A non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override)
    finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not
    float A data type that can store whole numbers from 3.4e−038 to 3.4e+038
    for Create a for loop
    goto Not in use, and has no function
    if Makes a conditional statement
    implements Implements an interface
    import Used to import a package, class or interface
    instanceof Checks whether an object is an instance of a specific class or an interface
    int A data type that can store whole numbers from -2147483648 to 2147483647
    interface Used to declare a special type of class that only contains abstract methods
    long A data type that can store whole numbers from -9223372036854775808 to 9223372036854775808
    module Declares a module. New in Java 9
    native Specifies that a method is not implemented in the same Java source file (but in another language)
    new Creates new objects
    package Declares a package
    private An access modifier used for attributes, methods and constructors, making them only accessible within the declared class
    protected An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses
    public An access modifier used for classes, attributes, methods and constructors, making them accessible by any other class
    requires Specifies required libraries inside a module. New in Java 9
    return Finished the execution of a method, and can be used to return a value from a method
    short A data type that can store whole numbers from -32768 to 32767
    static A non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class
    strictfp Restrict the precision and rounding of floating point calculations
    super Refers to superclass (parent) objects
    switch Selects one of many code blocks to be executed
    synchronized A non-access modifier, which specifies that methods can only be accessed by one thread at a time
    this Refers to the current object in a method or constructor
    throw Creates a custom error
    throws Indicates what exceptions may be thrown by a method
    transient A non-accesss modifier, which specifies that an attribute is not part of an object's persistent state
    try Creates a try...catch statement
    var Declares a variable. New in Java 10
    void Specifies that a method should not have a return value
    volatile Indicates that an attribute is not cached thread-locally, and is always read from the "main memory"
    while Creates a while loop
  53. Java String Methods
    Java String Methods
    Method Description Return Type
    charAt() Returns the character at the specified index (position) char
    codePointAt() Returns the Unicode of the character at the specified index int
    codePointBefore() Returns the Unicode of the character before the specified index int
    codePointCount() Returns the number of Unicode values found in a string. int
    compareTo() Compares two strings lexicographically int
    compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int
    concat() Appends a string to the end of another string String
    contains() Checks whether a string contains a sequence of characters boolean
    contentEquals() Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer boolean
    copyValueOf() Returns a String that represents the characters of the character array String
    endsWith() Checks whether a string ends with the specified character(s) boolean
    equals() Compares two strings. Returns true if the strings are equal, and false if not boolean
    equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
    format() Returns a formatted string using the specified locale, format string, and arguments String
    getBytes() Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array byte[]
    getChars() Copies characters from a string to an array of chars void
    hashCode() Returns the hash code of a string int
    indexOf() Returns the position of the first found occurrence of specified characters in a string int
    intern() Returns the canonical representation for the string object String
    isEmpty() Checks whether a string is empty or not boolean
    lastIndexOf() Returns the position of the last found occurrence of specified characters in a string int
    length() Returns the length of a specified string int
    matches() Searches a string for a match against a regular expression, and returns the matches boolean
    offsetByCodePoints() Returns the index within this String that is offset from the given index by codePointOffset code points int
    regionMatches() Tests if two string regions are equal boolean
    replace() Searches a string for a specified value, and returns a new string where the specified values are replaced String
    replaceFirst() Replaces the first occurrence of a substring that matches the given regular expression with the given replacement String
    replaceAll() Replaces each substring of this string that matches the given regular expression with the given replacement String
    split() Splits a string into an array of substrings String[]
    startsWith() Checks whether a string starts with specified characters boolean
    subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence
    substring() Returns a new string which is the substring of a specified string String
    toCharArray() Converts this string to a new character array char[]
    toLowerCase() Converts a string to lower case letters String
    toString() Returns the value of a String object String
    toUpperCase() Converts a string to upper case letters String
    trim() Removes whitespace from both ends of a string String
    valueOf() Returns the string representation of the specified value String
  54. Java Math Methods
    Java Math Methods
    Method Description Return Type
    abs(x) Returns the absolute value of x double|float|int|long
    acos(x) Returns the arccosine of x, in radians double
    asin(x) Returns the arcsine of x, in radians double
    atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians double
    atan2(y,x) Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). double
    cbrt(x) Returns the cube root of x double
    ceil(x) Returns the value of x rounded up to its nearest integer double
    copySign(x, y) Returns the first floating point x with the sign of the second floating point y double
    cos(x) Returns the cosine of x (x is in radians) double
    cosh(x) Returns the hyperbolic cosine of a double value double
    exp(x) Returns the value of Ex double
    expm1(x) Returns ex -1 double
    floor(x) Returns the value of x rounded down to its nearest integer double
    getExponent(x) Returns the unbiased exponent used in x int
    hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow double
    IEEEremainder(x, y) Computes the remainder operation on x and y as prescribed by the IEEE 754 standard double
    log(x) Returns the natural logarithm (base E) of x double
    log10(x) Returns the base 10 logarithm of x double
    log1p(x) Returns the natural logarithm (base E) of the sum of x and 1 double
    max(x, y) Returns the number with the highest value double|float|int|long
    min(x, y) Returns the number with the lowest value double|float|int|long
    nextAfter(x, y) Returns the floating point number adjacent to x in the direction of y double|float
    nextUp(x) Returns the floating point value adjacent to x in the direction of positive infinity double|float
    pow(x, y) Returns the value of x to the power of y double
    random() Returns a random number between 0 and 1 double
    round(x) Returns the value of x rounded to its nearest integer int
    rint(x) Returns the double value that is closest to x and equal to a mathematical integer double
    signum(x) Returns the sign of x double
    sin(x) Returns the sine of x (x is in radians) double
    sinh(x) Returns the hyperbolic sine of a double value double
    sqrt(x) Returns the square root of x double
    tan(x) Returns the tangent of an angle double
    tanh(x) Returns the hyperbolic tangent of a double value double
    toDegrees(x) Converts an angle measured in radians to an approx. equivalent angle measured in degrees double
    toRadians(x) Converts an angle measured in degrees to an approx. angle measured in radians double
    ulp(x) Returns the size of the unit of least precision (ulp) of x double|float