Git commands

Initialize a repository

git init

Clone a repository

git clone <repository_url>

Check repository status

git status

Add files to staging area

git add <file> # Add specific file git add . # Add all files

Commit changes

git commit -m "Commit message"

View commit history

git log

Create a new branch

git branch <branch_name>

Switch branches

git checkout <branch_name> git switch <branch_name> # (Preferred in newer Git versions)

Create and switch to a new branch

git checkout -b <branch_name> git switch -c <branch_name> # (Newer Git versions)

Merge a branch into the current branch

git merge <branch_name>

Delete a branch

git branch -d <branch_name>

Check remote repositories

git remote -v

Push changes to a remote repository

git push origin <branch_name>

Pull latest changes from remote

git pull origin <branch_name>

Fetch changes from remote without merging

git fetch origin

Undo the last commit (discard changes)

git reset --hard HEAD~1

Revert a specific commit (without losing history)

git revert <commit_hash>

Stash uncommitted changes

git stash

Apply the last stash

git stash pop

Cherry-pick a commit from another branch

git cherry-pick <commit_hash>

Squash multiple commits into one

git rebase -i HEAD~n

Java interview

  • OOP
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Constructor
  • Object
  • Interface и class
  • Access modifiers such as private, default, protected and public
  • Abstract class and method
  • Exception and Error

OOP

OOPs in Java organizes a program around the various objects and well-defined interfaces. The OOPs Concepts in Java are abstraction, encapsulation, inheritance, and polymorphism

Inheritance

- it is possible to inherit attributes and methods from one class to another
- is a mechanism in which one object acquires all the properties and behaviors of a parent object
- Java does not support Multiple inheritance

Encapsulation

- By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them
- hiding the implementation of the class and separating its internal representation from the external class or interface

Polymorphism

- is the ability to apply the same methods with the same or different sets of parameters in the same class or in a group of classes connected by an inheritance relation
-

Abstraction

- is the process of hiding implementation details from the user, giving the user only the functionality
- the user will own the information about what the object does, not how it does it

Constructor

- All classes have constructors, whether you define them or not, because Java automatically provides a default constructor
- The constructor is a method that creates a kind of "framework" for the class. Every new object of the class must conform to it

Object

- is an individual member of a class that has a particular state and behavior that is completely determined by the class
- Variables are used to store the state of the object
- The object is an instance of the class
- Any object can have two main characteristics: state - some data that the object stores, and behavior - actions that the object can perform

Class

- A class is a template structure that allows you to describe an object, its properties (class attributes or fields) and behavior (class methods) in a program
- Class can consist methods, objects and constructors. Class is a template of an object, he has a body with fields and methods 

Interface

- An interface is a reference type, it is similar to a class. It is a collection of abstract methods. 
- A class implements an interface, thus inherits the abstract methods of the interface
- There is no implementation inside the interface
The interface only describes the behavior of some object
- Only immutable final fields can be in the interface

Abstract class and method

- Abstract class describes some general state and behavior that future classes - descendants of the abstract class - will have.
- Similar to interfaces, abstract classes can have abstract methods, an abstract method is a method without a body (without implementation), but unlike interfaces, abstract methods in abstract classes must be explicitly declared as abstract.

Access modifiers

- public, protected, default, and private.
- Protected - declarations are visible within the package or all subclasses
- Default - declarations are visible only within the package (package private)

This

- Keyword this is a link to the current class instance, we can use this word to call constructors, variables and object method’s 

Static

- Static methods and variables are related to the class
- Static methods belong to a class, not an object. You can call them without creating an instance of the class
- From a static method you can access only static variables or methods

Stream

Map<Integer, Integer> map = new HashMap<>();
// Collection.stream() + Stream.forEach()
        map.values().stream()
                .forEach(System.out::println);
map.keySet().stream()
                .forEach(System.out::println);
TreeSet<Integer> set = new TreeSet<>();
set.forEach(integer -> {
            System.out.print(integer + " ");
        });

Read from console

Scanner in = new Scanner(System.in);
String name = in.nextLine();
int number = in.nextInt();
//input from file
FileInputStream inputStream = new FileInputStream(name);
    int max = 0;
    while (inputStream.available() > 0) //пока остались непрочитанные байты
    {
        int data = inputStream.read(); //прочитать очередной байт
        if (data>max){
            max = data;
        }
    }
    System.out.println(max);
    inputStream.close();
}

Java collections

List — хранит упорядоченные елементы(могут быть одинаковые); Имеет такие реализации как LinkedList, ArrayList и Vector.

ArrayList

LinkedList

Когда использовать ArrayList и LinkedList?

Если нам требуется произвести большое количество вставок или удалений, то нам следует использовать LinkedList. Если у нас имеется мало вставок или удалений, но выполняется много поисковых операций, то тогда нам следует использовать ArrayList.

 

Set — коллекции, которые не содержат повторяющихся элементов.

Реализации: HashSet, TreeSet, LinkedHashSet

  • TreeSet — упорядочивает элементы по их значениям;
  • HashSet — упорядочивает элементы по их хэш ключам
  • LinkedHashSet — хранит элементы в порядке их добавления


Queue — интерфейс для реализации очереди.

Основные реализации: LinkedList, PriorityQueue.

принцип FIFO – first in first out.

Map — интерфейс для реализации элементов с их ключами.

Основные реализации: HashTable, HashMap, TreeMap, LinkedHashMap

  • HashTable — синхронизирована, объявлена уставревшей.
  • HashMap — порядок елементов рассчитывается по хэш ключу;
  • TreeMap — элементы хранятся в отсортированном порядке
  • LinkedHashMap — элементы хранятся в порядке вставки

Ключи в Мар не одинаковые