Pages

Tuesday 18 July 2023

Code Review

  •  SOLID Principles
    • S – Single Responsibility Principle
      • There should never be more than one reason for a class to change.
    • O – Open-Closed Principle
      • Software entities should be open for extension, but closed for modification.
    • L – Liskov Substitution Principle
      • Functions that use references to base classes must be able to use objects of derived classes without knowing it.
    • I – Interface Segregation Principle
      • Many client specific interfaces are better than one general purpose interface.
    • D – Dependency Inversion Principle
      • Depend upon Abstractions. Do not depend upon concretions.
  • Naming conventions (Class name, method name, variable name, constant name, function name, type declarations)
  • Variable initialization and reset
  • Caching
  • Pattern check/Null Check (@Valid/@Pattern/@NotEmpty)
  • Design Pattern (Creational, Structural, Behavioral)
  • Data structure (Eg. Collections)
  • Exception handling (@ControllerAdvice/Throw custom exception)
  • API Contracts (Request & Response)
  • Security
  • Reusability
  • Extensibility
  • Configurable
  • Check for hardcoding
  • Logging
  • Unused variables, useless declarations
  • Reducing unnecessary iterations (cognitive and cyclometric complexities)
  • New Features implemented (Eg. Java8 Features like stream API)
  • Unit Test Case coverages (JUnit, Karma Jasmine)
  • Documentation (Java Doc, Angular Documentation)
  • Markdown files update (README.md, BUILD.md, DEPLOY.md, etc.,)
  • Build and run the project
  • Run static code analysis tool (Eg. SonarQube/SonarLint)

Friday 14 July 2023

Tic-Tac-Toe Game using Java

In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For example, if you have to select any number then for X or O will be shown on the print board, and turn for next will be there. The task is to create a Java program to implement a 3×3 Tic-Tac-Toe game for two players.

 Game board :

      |---|---|---|        

      | 1 | 2 | 3 |

      |-----------|

      | 4 | 5 | 6 |

      |-----------|

      | 7 | 8 | 9 |

      |---|---|---| 

Sample Input :

Enter a slot number to place X in: 3 

Sample Output :

      |---|---|---|        

      | 1 | 2 | X |

      |-----------|

      | 4 | 5 | 6 |

      |-----------|

      | 7 | 8 | 9 |

      |---|---|---|  

Sample Input :

Now, O’s turn, Enter a slot number to place O in: 5

Sample Output :


      |---|---|---|        

      | 1 | 2 | X |

      |-----------|

      | 4 | O | 6 |

      |-----------|

      | 7 | 8 | 9 |

      |---|---|---|  

So, like this game will be continued.

How to Play the Game :

  • Both the players choose either X or O to mark their cells.
  • There will be a 3×3 grid with numbers assigned to each of the 9 cells.
  • The player who choose X begins to play first.
  • He enters the cell number where he wishes to place X.
  • Now, both O and X play alternatively until any one of the two wins.
  • Winning criteria: Whenever any of the two players has fully filled one row/ column/ diagonal with his symbol (X/ O), he wins and the game ends.
  • If neither of the two players wins, the game is said to have ended in a draw.

Below is the implementation of the game in Java :

// A simple program to demonstrate

// Tic-Tac-Toe Game.

import java.util.*;

public class GFG {

    static String[] board;

    static String turn;

    // CheckWinner method will

    // decide the combination

    // of three box given below.

    static String checkWinner()

    {

        for (int a = 0; a < 8; a++) {

            String line = null;

 

            switch (a) {

            case 0:

                line = board[0] + board[1] + board[2];

                break;

            case 1:

                line = board[3] + board[4] + board[5];

                break;

            case 2:

                line = board[6] + board[7] + board[8];

                break;

            case 3:

                line = board[0] + board[3] + board[6];

                break;

            case 4:

                line = board[1] + board[4] + board[7];

                break;

            case 5:

                line = board[2] + board[5] + board[8];

                break;

            case 6:

                line = board[0] + board[4] + board[8];

                break;

            case 7:

                line = board[2] + board[4] + board[6];

                break;

            }

            //For X winner

            if (line.equals("XXX")) {

                return "X";

            }

             

            // For O winner

            else if (line.equals("OOO")) {

                return "O";

            }

        }

         

        for (int a = 0; a < 9; a++) {

            if (Arrays.asList(board).contains(

                    String.valueOf(a + 1))) {

                break;

            }

            else if (a == 8) {

                return "draw";

            }

        }

 

       // To enter the X Or O at the exact place on board.

        System.out.println(

            turn + "'s turn; enter a slot number to place "

            + turn + " in:");

        return null;

    }

     

    // To print out the board.

    /* |---|---|---|

       | 1 | 2 | 3 |

       |-----------|

       | 4 | 5 | 6 |

       |-----------|

       | 7 | 8 | 9 |

       |---|---|---|*/

   

    static void printBoard()

    {

        System.out.println("|---|---|---|");

        System.out.println("| " + board[0] + " | "

                           + board[1] + " | " + board[2]

                           + " |");

        System.out.println("|-----------|");

        System.out.println("| " + board[3] + " | "

                           + board[4] + " | " + board[5]

                           + " |");

        System.out.println("|-----------|");

        System.out.println("| " + board[6] + " | "

                           + board[7] + " | " + board[8]

                           + " |");

        System.out.println("|---|---|---|");

    }

 

    public static void main(String[] args)

    {

        Scanner in = new Scanner(System.in);

        board = new String[9];

        turn = "X";

        String winner = null;

 

        for (int a = 0; a < 9; a++) {

            board[a] = String.valueOf(a + 1);

        }

 

        System.out.println("Welcome to 3x3 Tic Tac Toe.");

        printBoard();

 

        System.out.println(

            "X will play first. Enter a slot number to place X in:");

 

        while (winner == null) {

            int numInput;

           

           // Exception handling.

           // numInput will take input from user like from 1 to 9.

           // If it is not in range from 1 to 9.

           // then it will show you an error "Invalid input."

            try {

                numInput = in.nextInt();

                if (!(numInput > 0 && numInput <= 9)) {

                    System.out.println(

                        "Invalid input; re-enter slot number:");

                    continue;

                }

            }

            catch (InputMismatchException e) {

                System.out.println(

                    "Invalid input; re-enter slot number:");

                continue;

            }

             

            // This game has two player x and O.

            // Here is the logic to decide the turn.

            if (board[numInput - 1].equals(

                    String.valueOf(numInput))) {

                board[numInput - 1] = turn;

 

                if (turn.equals("X")) {

                    turn = "O";

                }

                else {

                    turn = "X";

                }

 

                printBoard();

                winner = checkWinner();

            }

            else {

                System.out.println(

                    "Slot already taken; re-enter slot number:");

            }

        }

       

        // If no one win or lose from both player x and O.

        // then here is the logic to print "draw".

        if (winner.equalsIgnoreCase("draw")) {

            System.out.println(

                "It's a draw! Thanks for playing.");

        }

       

        // For winner -to display Congratulations! message.

        else {

            System.out.println(

                "Congratulations! " + winner

                + "'s have won! Thanks for playing.");

        }

      in.close();

    }

}

Output:

Below is the output of the above program :

Welcome to 3x3 Tic Tac Toe.

|---|---|---|

| 1 | 2 | 3 |

|-----------|

| 4 | 5 | 6 |

|-----------|

| 7 | 8 | 9 |

|---|---|---|

X will play first. Enter a slot number to place X in:

3

|---|---|---|

| 1 | 2 | X |

|-----------|

| 4 | 5 | 6 |

|-----------|

| 7 | 8 | 9 |

|---|---|---|

O's turn; enter a slot number to place O in:

5

|---|---|---|

| 1 | 2 | X |

|-----------|

| 4 | O | 6 |

|-----------|

| 7 | 8 | 9 |

|---|---|---|

X's turn; enter a slot number to place X in:

6

|---|---|---|

| 1 | 2 | X |

|-----------|

| 4 | O | X |

|-----------|

| 7 | 8 | 9 |

|---|---|---|

O's turn; enter a slot number to place O in:

1

|---|---|---|

| O | 2 | X |

|-----------|

| 4 | O | X |

|-----------|

| 7 | 8 | 9 |

|---|---|---|

X's turn; enter a slot number to place X in:

9

|---|---|---|

| O | 2 | X |

|-----------|

| 4 | O | X |

|-----------|

| 7 | 8 | X |

|---|---|---|

Congratulations! X's have won! Thanks for playing.

Hashmap vs Hashtable

HashMap and Hashtable store key and value pairs in a hash table. When using a Hashtable or HashMap, we specify an object that is used as a key and the value that you want to be linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

  • HashMap is non-synchronized. It is not thread-safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  • HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
  • HashMap is generally preferred over HashTable if thread synchronization is not needed.


Program:

// Java program to demonstrate
// HashMap and HashTable
import java.util.*;
import java.lang.*;
import java.io.*;

// Name of the class has to be "Main"
// only if the class is public
class Ideone
{
public static void main(String args[])
{
//----------hashtable -------------------------
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(101," ajay");
ht.put(101,"Vijay");
ht.put(102,"Ravi");
ht.put(103,"Rahul");
System.out.println("-------------Hash table--------------");
for (Map.Entry m:ht.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue());
}

//----------------hashmap--------------------------------
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(104,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
System.out.println("-----------Hash map-----------");
for (Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output:
-------------Hash table--------------
103 Rahul
102 Ravi
101 Vijay
-----------Hash map-----------
100 Amit
101 Vijay
102 Rahul
104 Amit

Spring Bean Scopes

 

  • @Bean & @Scope("singleton") or @Bean
  • @Bean & @Scope("prototype")
  • @Bean & @Scope("request") or @Component & @RequestScope
  • @Bean & @Scope("session") or @Component & @SessionScope
  • @Bean & @Scope("application") or @Component & @ApplicationScope
  • @Component & @Scope("websocket")

Wednesday 21 June 2023

Interview preparation

Java Backend:
  • Oops
    • Object
    • Class
    • Inheritance
    • Polymorphism
    • Abstraction
    • Encapsulation
  • Java keywords
  • Java Basics
  • Java 8 Features
    • Lambda
    • Functional Interface
    • Completable Feature
  • Java Collection Framework
  • Java Spring Boot Framework
    • Annotations
      • @Bean
      • @Restcontroller
      • @Service
      • @Repository
      • @Component
      • @Configuration
      • @Autowired
      • @ControllerAdvice
      • @PathVariable
      • @RequestParameter
      • @RequestBody
      • @Value
      • @Entity
      • @Column
      • @Valid
      • @Pattern
      • @Async
    • Beans
      • Scope
    • Dependency Injection
      • Types
  • Java Repository/JPA/Hibernate
  • Java Spring Security
  • JUnit
Design/Architecture:
  • Microservice Architecture
    • Saga
    • Rules to consider
  • Design Patterns
    • Singleton
    • Factory
  • UML/HLD/LLD
    • Tools
    • Diagrams
Database - Oracle/Mongo:
  • Oracle DB
    • Tables
    • Synonyms
    • Constrains
    • Primary Key
    • Foreign Key
  • Oracle SQL functions
    • COALESCE
    • NVL, NVL2
    • DECODE
    • TO_DATE, TO_CHAR
  • Oracle SQL queries
    • group by
    • having
  • Oracle PLSQL
    • packages
    • procedures
    • functions
    • triggers
    • views
Angular UI:
  • Decorators
  • Lifecycle hooks
  • UI level security - authgarud/filters/interceptors
  • Karma Jasmine
Messaging/ Event based:
  • Kafka
  • IBM MQ
  • Tibo MQ
Caching:
  • In-memory caching - ehcache/memcache
  • Couchbase
Unit Tests:
  • JUnit
  • Karma Jasmine
Performance testing:
  • JMeter
API Testing:
  • Swagger
  • SOAP UI
  • Postman
Deployment - CICD:
  • Jenkins/TeamCity
  • Maven
  • Artifactory - JFrog
  • Docker - docker image
  • urban code deploy - ucd
  • OpenShift/Kubernetes/PCF
    • Deployment configs (template.yml/.params/.sh/docker/jenkins)
    • Containers
    • Pods & instances
    • Memory - CPU
    • ConfigMaps
    • Volume mount
Code analysis:
  • SonarQube - Static code analysis, code coverage
  • Blackduck - Vulnerable jars
  • CheckMarx
Monitoring:
  • ITRS/OSE monitoring - AppDynamics
Tracing:
  • ELK stack - Kibana
Version control:
  • BitBucket/Git
Lead:
  • Code Review
    • coding principles
    • Tools used for coverage/analysis
  • Work assignment
  • Design
Program:
  • Java8 based (filter, map, reduce, max, grouping)
  • String based (prohibited substring, no repeating char substring)
  • Array based (No of duplicate numbers)
  • Regex based (IP validation)
  • Brackets based (Parentheses matching, parentheses match score)
  • Custom LinkedList
  • Reverse LinkedList
  • Custom ArrayList
System design:
  • Parking slot
  • TicTacToe game

Tuesday 20 June 2023

@input and @output properties in angular









COALESCE() Function

 Return the first non-null value in a list.

Example:

SELECT COALESCE(NULL, NULL, NULL, 'value 1', NULL, 'value 2') FROM dual;

Output: value 1

OOPs - Object-Oriented Programming System

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing below concepts:

  1. Object
  2. Class 
  3. Inheritance
  4. Polymorphism
  5. Abstraction
  6. Encapsulation


Object :
  • Any entity that has state and behavior 
  • instance of a class
  • object contains an address & takes up some space in memory.


Class :
  • Collection of objects
  • logical entity 
  • blueprint from which you can create an individual object
  • doesn't consume any space.


Inheritance :
  • One object acquires all the properties and behaviors of a parent object
  • provides code reusability
  • used to achieve runtime polymorphism.

  • Multiple inheritance is not supported in Java through class
    • ambiguity
    • diamond problem/deadly diamond problem/deadly diamond of death
    • Java renders compile-time error.

Polymorphism:
  • one task is performed in different ways
  • method overloading and method overriding to achieve polymorphism.
  1. compile-time polymorphism : method overloading - overload a static method in Java
  2. runtime polymorphism/Dynamic Method Dispatch : method overriding
upcasting



Example


Abstraction:
  • Hiding internal details and showing functionality
  • abstract class and interface.    

Abstract class (0 to 100%)

Interface (100%)

Java compiler adds public static final for elements & public abstract for methods
Multiple inheritance through interface


Encapsulation:
  • Binding (or wrapping) code and data together into a single unit
  • java class, Java bean is the fully encapsulated class because all the data members are private here.


Apart from these concepts, there are some other terms which are used in Object-Oriented design:
  1. Coupling
  2. Cohesion
  3. Association
  4. Aggregation
  5. Composition

Reverse a LinkedList

Input: Head of following linked list 
1->2->3->4->NULL 
Output: Linked list should be changed to, 
4->3->2->1->NULL

Input: Head of following linked list 
1->2->3->4->5->NULL 
Output: Linked list should be changed to, 

5->4->3->2->1->NULL

Code:[Java]

package com.learning.learn.linkedlist;

public class LinkedList {

static Node head;

static class Node {
int data;
Node next;
Node(int d) {
this.data = d;
next = null;
}
}

Node reverse(Node node) {
Node prev = null;
Node curr = node;
Node next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
node = prev;
return node;
}

void printList(Node node) {
while(node != null) {
System.out.print(node.data+" ");
node = node.next;
}
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);

System.out.println("Given :");
list.printList(head);
head = list.reverse(head);
System.out.println();
System.out.println("Reversed :");
list.printList(head);
}

}

 

Wednesday 7 June 2023

Find second max value in the table (nth max value)

--Second maximum column value

SELECT *

FROM customers

ORDER BY age DESC, first_name ASC

LIMIT 1,1; -- 1 - number of row to omit, 1 - no of records to show


Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...