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 applications
  • Web applications
  • Web servers and application servers

Docs
Cheatsheet
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. Install Redis Stack in Docker
    1. redis/redis-stack-server
                         
                         docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest
                            
    

    2. redis/redis-stack
                         
                        docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
                            
    
  2. Connect with redis-cli
                         
                        docker exec -it c8cfa46e8843 bash
                            
    
  3. 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!");
                
            
  4. Take inputs
                         
                            Scanner input=new Scanner(System.in);
                            float marks =input.nextFloat();
                            
    
  5. 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 */
    
    
  6. 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;
    
    
  7. 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
  8. 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";    
                        
                        
  9. 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
                            
                            
  10. 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)
  11. 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"));
                
  12. 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
  13. Java Math

                                        
                                            Math.max(5, 10);     
                                    
                                    

                                    
                                        Math.min(5, 10);
                                
                                

                                        
                                            Math.sqrt(64);    
                                    
                                    

                                        
                                            Math.abs(-4.7);  
                                    
                                    

                                        
                                            Math.random();
                                    
                                    
  14. 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
                                                  }
                                        
                                        
  15. 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
                                                  }  
                                        
                                        
  16. 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;
                        
                        
  17. 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;
                        
                        
  18. 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"};
    
    
  19. 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} };
                        
                        
  20. 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
                                }
                              }
                        
                        
  21. 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.
  22. 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
  23. 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)