Arrays programming Interview questions in Java for freshers

Java Programming Interview Questions for freshers

  1. What is Java Array?
    It refers to a variable-size, ordered collection whose elements have the identical type.

  2. What are the types of Java arrays?
    Single-dimensional arrays (for example, of type int[] arr = new int[5]) and multi-dimensional arrays (e.g.,int[][] arr = new int[3][3].

  3. How do you initialize an array in Java?
    Use either int[] arr = {1, 2, 3, 4, 5}; (remember the semicolon) or int[] arr = new int[5];.

  4. What is the default value of an array in Java?
    Numeric types default to 0, boolean to false, and reference types such as an object's field value through a NULL pointer exception error.

  5. Is the size of an array in Java changeable after initialization?
    No! An array has no dynamic conversion and will always be the same from the day it is initialized until the end.

  6. What's the difference between Java array and ArrayList?

  7. How do you copy an array in Java?
    You can use System.arraycopy(), Arrays.copyOf(), or the clone() method.

  8. How do you sort an array in Java?
    Arrays.sort(array);

  9. How do you search for an element in an array?
    Use a loop or Arrays.binarySearch(array, key); for sorted arrays.

  10. How do you convert an array to an exact corresponding index in a List?
    Arrays.asList(array); A method that returns a fixed-size list backed by the array.

Java Interview Programming Questions

  1. Write a Java program to reverse a string.

    public class ReverseString {
      public static void main(String[] args) {
        String str = "Hello";
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println("Reversed String: " + reversed);
      }
    }
    
  2. Write a Java program to test a number for prime status.

    public class PrimeCheck {
      public static boolean isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i <= Math.sqrt(num); i++) {
          if (num % i == 0) return false;
        }
        return true;
      }
      public static void main(String[] args) {
        int number = 29;
        System.out.println(number + " is prime: " + isPrime(number));
      }
    }
    
  3. Write a Java program to find the largest number in an array.

    public class LargestElement {
      public static void main(String[] args) {
        int[] arr = {10, 20, 5, 8, 30};
        int max = arr[0];
        for (int num : arr) {
          if (num > max) {
            max = num;
          }
        }
        System.out.println("Largest Element: " + max);
      }
    }
    
  4. Write a Java program to delete duplicates from an array.

    import java.util.HashSet;
    import java.util.Arrays;
    public class RemoveDuplicates {
      public static void main(String[] args) {
        int[] arr = {1, 2, 3, 1, 2, 4, 5};
        HashSet<Integer> set = new HashSet<>();
        for (int num : arr) {
          set.add(num);
        }
        System.out.println("Array without duplicates: " + set);
      }
    }
    
  5. Write a Java program to find the missing number in an array of 1 to N.

    public class MissingNumber {
      public int findMissing(int[] arr, int n) {
        int sum = n * (n + 1) / 2;
        for (int num : arr) {
          sum -= num;
        }
        return sum;
      }
      public static void main(String[] args) {
        int[] arr = {1, 2, 4, 5, 6};
        int n = 6;
        System.out.println("Missing number: " + new MissingNumber().findMissing(arr, n));
      }
    }
    


Top 65 java interview questions on collections

1.What Is The Java Collections Framework (JCF)?

Interfaces and classes for storing data in ways compatible with data structures (that is, memory-efficient).

2.What Are The Primary Interfaces In The Java Collections Framework?

Collection, List, Set Queue Map and all of their subinterfaces.

3.What is the difference between Collection and Collections in Java?

Collection: the root interface for data structures.

Collections: a utility class that has static methods.

4.Is There A difference among List, Set, and Map*

List: Sequential order, no duplication.

Set: No order, no duplication.

Map: Key value pairs--like a dictionary house keys in general practice--with unique keys.

5.What are the key differences between ArrayList and LinkedList?

ArrayList: Faster access to random locations but slow in the middle of things.

LinkedList: Quick updates anywhere on list, slower access than with less predictable block sizes.

6.What is the difference between HashSet, LinkedHashSet, and TreeSet?

HashSet: Unordered, fast.

LinkedHashSet: Maintains order of insertion (or addition)

TreeSet: A set in alphabetical or other order, depending on the key.

7.How Does HashMap Work in Java?

The key-value storage system uses buckets and hashing to handle collisions. With Java 8, it has been modified to handle collisions (e.g. using red-black trees).

8.What is the default capacity of an ArrayList?

10 (increases by 50% when full).

9.What are fail-fast and fail-safe iterators and how do they differ?

Fail-fast: throws a ConcurrentModificationException if modified during iteration

Fail-safe: permits modification (CopyOnWriteArrayList, ConcurrentHashMap).

10.Why is HashSet faster than TreeSet?

HashSet uses hashing (O(1)), while TreeSet uses a Red-Black tree (O(log n)).

11.What is the internal implementation of HashMap?

Behind the scenes: It's an array of buckets with linked lists for collision handling.

12.Why is the load factor in HashMap set to 0.75?

It's a trade-off between memory efficiency and speed (reduces rehashing costs).

13.What is the difference between Comparable and Comparator?

Comparable is for natural ordering (compareTo).

Comparator only does sorting (compare).

14.How Does ConcurrentHashMap Work Internally?

SEGMENT LOCKING. (Java 7), BUCKET LEVEL LOCKING. (Java 8) allow instantaneous access

15.What is the difference between synchronized and concurrent collections?

Synchronized: Slower, blocks threads (eg.Collections.synchronizedList). Concurrent: optimized for chucks of work (ConcurrentHashMap).

16.How does CopyOnWriteArrayList work?

When the list is modified, it creates a new copy for every call (which makes the program thread-safe). This causes a great shortfall in memory usage efficiency.

17.What is the difference between Hashtable and HashMap?

Hashtable: Hashtable is synchronized (slow).

HashMap: HashMap is not synchronized (faster).

18.Why should you override hashCode() and equals() in HashMap keys?

So that you act upon both the correct key and never retrieve any duplicates

19.How to make an ArrayList thread-safe?

Use Collections.synchronizedList() or CopyOnWriteArrayList.

20.What are weak keys in WeakHashMap?

If there are no strong references left, the keys are eligible for garbage collection. This is true of all of them in a WeakHashMap.

Advanced Level Questions

21.What are the differences between ConcurrentHashMap and SynchronizedMap?

ConcurrentHashMap: More efficient, with bucket-level locking. SynchronizedMap: locks entire collection.

22.How Does TreeMap Maintain Ordering?

It uses a Red-Black Tree, which orders elements in natural/comparator order.

23.How Does LinkedHashMap Maintain Insertion Order?

LinkedHashMap: Hash table and double chain.("

24.What Does remove() do in Iterator?

It Removes the last element returned by Iterator and Disallows exceptions when something goes wrong. It just bites! (So to speak.)

25.What is PriorityQueue, and how does it work?

A queque based on a minimum value of min-heap orders elements naturally in the queue or by comparing at run-time

26.What is BlockingQueue, and how does it help in multithreading?

It's one of the series of Implementations BlockingQueues: Full.put() will block until space is available, and (take() Empty BC) ditto for take. only blocking queue

27.What are IdentityHashMap and EnumMap?

IdentityHashMap: uses object identity values for keys. EnumMap: optimized to work with enum keys.

28.How Does The computeIfAbsent() Method Work In Java 8?

Adds value to a map only if key is missing.

29.How Does The Spliterator Work?

In parallel processing mode of a series of chunks

30.What are the performance considerations when choosing between different collection types?

Choose ArrayList for fast read, LinkedList for frequent inserts/deletes, Hash stark areas, Terence <>TreeSet for sorted data.

31. What is the difference between Collection and Collections in Java?

  • Collection: The collection framework is the root of the List, Set, and Queue classes.
  • Collections: A utility class, such as sort() or reverse(), that holds only static methods.

32. How is Iterator different from ListIterator?

  • Iterator: Only supports forward traversal.
  • ListIterator: You can go forwards and backwards. You can change the elements on the list.

33. What are Java′s different kinds of queues?

  • PriorityQueue: Sorts by priority.
  • Deque: A double-ended queue.
  • BlockingQueue: Supports thread-safe operations. Examples include: ArrayBlockingQueue, LinkedBlockingQueue.

34. What’s the difference between a Stack and a Queue?

  • Stack: Last In, First Out.
  • Queue: First In, First Out.

35. What is an Enumeration in Java?

  • A way to iterate over collections. It is used for iterating through collections (e.g., Vector, Hashtable).
  • A substitute for Iterator and ListIterator used in modern Java.

36. What is a LinkedHashMap in Java?

  • A HashMap with insertion order of elements on a doubly linked list.

37. What happens when a HashMap's capacity is exceeded?

  • It makes new changes (doubling capacity), rehashes elements, and puts them into new buckets.

38. How do you synchronize a List or a Set?

  • Use Collections.synchronizedList(myList or Collections.synchronizedSet(mySet).

39. What are the differences between a HashMap and a TreeMap?

  • HashMap: Not in order. O(1) lookup time.
  • TreeMap: The order of elements is O(log n) lookup time (Red-Black Tree).

40. What are the differences between Arrays and ArrayLists? - Array: Fixed size, faster to access. - ArrayList: Dynamic resizing, slower than the array but flexible.

41. How does the remove(Object o) method work in a Collection? - Removes the first occurrence.

42. What happens when two objects have the same hashCode() but are not equal? - One bucket of the same number holds the elements as a tree or a linked list.

43. What is a NavigableSet in Java? - It is a SortedSet with methods like lower(), higher(), ceiling(), and floor().

44. What’s the difference between poll() and remove() in a Queue? - poll(): This removes and returns the header element. When the queue is empty, it returns null. - remove(): Same as poll() but throws a NoSuchElementException if the queue is empty.

45. What's the point of the containsKey() and containsValue() methods in Map? - containsKey(): Makes certain that a given key exists. - containsValue(): Checks to see if a value exists (slower because it must search through all values).

46. What’s the difference between peek(), poll(), and remove() in a Queue? - peek(): Returns the head without removing it. - poll(): Returns the head, removes it, and returns null if empty. - remove(): Similar to poll() except if empty, it throws a NoSuchElementException.

47. What's the difference between IdentityHashMap and HashMap? - IdentityHashMap uses reference equality (==), while HashMap uses .equals().

48. How does TreeMap sort its elements? - It uses natural ordering (Comparable) or a custom comparator (Comparator).

49. What is a WeakHashMap in Java? - A HashMap where the keys are weak references and are removed from the map when not referenced any further.

50. What exactly is a ConcurrentLinkedQueue? - It's a thread-safe, non-blocking queue that relies on lock-free linked nodes to operate.

51. What are the advantages of ConcurrentHashMap over HashMap? - It uses segment-level locking in Java 7 and bucket-level locking in Java 8. - Multiple threads can make changes to different segments simultaneously.

52. What does Java 8 do to improve the performance of HashMap? - It uses balanced trees (Red-Black trees) instead of linked lists if the bucket size is > 8.

53. What are ConcurrentSkipListMap and TreeMap’s differences? - ConcurrentSkipListMap: A thread-safe sorted map that relies on a Skip List. - TreeMap: A Red-Black Tree that is not thread-safe.

54. What is BlockingQueue and its implementations? - A thread-blocking queue that fills the threads to keep the water level constant or empty. Examples include: LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue.

55. What is the difference between SoftReference, WeakReference, and PhantomReference? - SoftReference: Collected only when memory is low. - WeakReference: Collected at the next garbage collection if it has no strong references. - PhantomReference: Used for finalization and releasing resources.

56. How and when does CopyOnWriteArrayList give you thread safety? - After a list is changed, it copies the old list so that no thread can modify it while working with the new list.

57. What is the difference between TreeSet and HashSet? - TreeSet: Ordered, implemented using Red-Black Tree (O(log n) time). - HashSet: Unordered, using Hashing (O(1) time).

58. What is a BitSet? - An efficient bit-sponging tool.

59. What is the forEach() method in Java 8 collections? - It uses lambda expressions to iterate over a collection (e.g., list.forEach(System.out::println)).

60. What's the difference between unmodifiable and immutable collections? - Unmodifiable: A wrapper that prevents any changes (e.g., Collections.unmodifiableList()). - Immutable: Can't be changed in any way (e.g.,List.of() ,Set.of(0).

61. Why are HashMap keys immutable in Java? 
- To prevent inconsistent behavior from 'hashCode' changes.

62. What is a ConcurrentHashMap compute() method? - It allows atomic updates of the value associated with a key. (e.g., map.compute(key, (k, v) -> v + 1)).

63. How does the parallelStream() method in Java 8 work? - Splits the collection into segments and processes them in parallel using the Fork/Join system.

64. Why is EnumMap faster than HashMap for Enums? - It uses an array-based internal storage system, avoiding the overhead of computing hashes.

65. What’s the difference between TreeSet and LinkedHashSet? -

  TreeSet: Ordered set (O(log n)). 

- LinkedHashSet:Maintains insertion order (O(1)).


man command in linux

 Learn man Command in Linux: Start Using Linux Manual Pages the Right Way

The true power of Linux lies in the command-line interface. Whether you're a complete beginner or an advanced user, man will be one of the most important tools in your Linux toolbox. Follow this blog post to find out what the man command is, how to use it, and how to work effectively with it.

 What is the man Command?

The manual command, or man for short, prints out documentation in the form of manual pages for other commands, utilities, and functions on a Linux system. These manual pages give a detailed explanation of the usage, options, and examples associated with a command.

If you want to know how to use the ls command, for example, simply type:

man ls

This will display the ls manual page, explaining what the command does, how to use it, available options, and examples.

 Why is the man Command Important?

  • Built-in Documentation: The man command provides detailed, comprehensive documentation covering nearly every Linux command and utility.
  • No Internet Required: Manual pages are stored locally, so you don't need an internet connection.
  • Standard Format: Manual pages follow a consistent structure, making it easy to find the information you need.
  • Learn As You Go: You can explore new commands without relying on external materials.

 How to Use the man Command

The basic syntax of the man command is:

man [options] <command_name>

For example:

man grep

 Navigating Manual Pages

You can navigate through a manual page using the following keys:

  • Arrow Keys: Move up and down within the document.
  • Spacebar: Advance one page forward.
  • Enter: Move one line forward.
  • b: Move one page backward.
  • /search_term: Search for a specific term (e.g., /pattern).
  • n: Go to the next occurrence of the search term.
  • N: Go to the previous occurrence of the search term.
  • q: Quit the manual page.

 Sections of Manual Pages

Manual pages are divided into sections, each focusing on different types of content. Here are the standard sections:

  • Section 1: General user commands (e.g., ls, grep).
  • Section 2: System calls (e.g., open, read).
  • Section 3: Library functions (e.g., printf, malloc).
  • Section 4: Special files (e.g., /dev).
  • Section 5: File formats and conventions (e.g., /etc/passwd).
  • Section 6: Games and screensavers.
  • Section 7: Miscellaneous (e.g., man, bash).
  • Section 8: System administration commands (e.g., iptables, fdisk).

To view a specific section of a manual page:

man <section_number> <command_name>

For example:

man 5 passwd

 Advanced Usage of the man Command

CommandDescription
man -k <keyword>Search for manual pages related to a keyword
man -a <command>Display all available sections for a command
man <section_number> <command>View a specific section of a command
man -w <command>Show the file path of a manual page
man -f <command>Display a short description of a command (same as whatis)

 1. Search for Manual Pages

man -k <keyword>

For example:

man -k network

  2. Display All Sections

man -a <command_name>

For example:

man -a passwd

 3. View a Specific Section

man <section_number> <command_name>

For example:

man 3 printf

 4. Display the Location of Manual Pages

Use the -w option to get the location of a manual page on your system:

man -w <command_name>

For example:

man -w ls

 5. View a Short Description

Use the -f option to display a brief description of a command:

man -f <command_name>


This is the same as using the whatis command.

 Tips and Tricks

1. Use man man: To learn more about the man command itself, type:
   man man
2. Learn less Commands: The man pages are displayed using the less pager. Learning less commands will improve your navigation.
3. Customize Output: Set environment variables like MANPAGER and PAGER to change how man operates.
4. Install Missing Manual Pages: If a manual page is missing, install it using a package manager.
   On Debian-based systems:
   sudo apt install manpages-dev
5. Use tldr for Quick Examples: If man pages are too lengthy, try the tldr command for concise explanations:
   tldr <command_name>

The man command is an essential tool for working with Linux. Its rich and accurate documentation makes it easy for users to master their command-line skills. Whether you're a beginner or an experienced Linux user, mastering man will significantly enhance your productivity and confidence.


Ascii value of a to z Java program

 Understanding ASCII and How to Print ASCII Values in Java

ASCII is a character encoding standard: It is used to represent text in computers and other devices. Each of its characters is assigned a unique numerical value comprising, amongst others, letters, digits, punctuation and control. For example, the ASCII value of the letter 'A' is 65, and of the letter 'a' is 97.

In this blog post I will explain a simple Java program that outputs the ASCII values for lower case letters deathnbsp;'a' to 'z'; this helps you understand how characters are actually represented by the computer as well as work with ASCII values in Java.

What is ASCII

ASCII is a 7-bit character encoding standard that can represent 128 characters (0 to 127). These characters include:

Uppercase letters: A to Z (ASCII values 65 to 90)

Lowercase letters: a to z (ASCII values 97 to 122)

Digits: 0 to 9 (ASCII values 48 to 57)

Special characters: !, @, #, $, etc.

Control characters: Newline (\n), tab (\t), etc.

Subsequently, when writing programs for programming matrix (i.e. application software), you will want to use ASCII values instead of characters themselves in order to handle different character sets: for example to sort escort compare different characters.

Java program to print ASCII values from a to z

public class AsciiValues {

    public static void main(String[] args) {

        // Loop through characters 'a' to 'z'

        for (char ch = 'a'; ch <= 'z'; ch++) {

            // Print the character and its ASCII value

            System.out.println("Character: " + ch + ", ASCII Value: " + (int) ch);

        }

    }

}

Top 100 Java Interview Questions for experienced

1) What is the @Transactional annotation?

The @Transactional annotation in Spring indicates that a method or class should be executed within a transactional context. It manages the transaction boundaries for a method or class, ensuring that all operations within it are either committed or rolled back as a unit. This annotation is useful for managing database transactions automatically. However, it’s important to note that Spring's @Transactional does not define one query as a "unit transaction" but rather handles the overall transaction flow.

2) What is @Repository for?

The @Repository annotation is used to define a Data Access Object (DAO) in Spring. It marks the class as a repository that handles database operations and allows Spring to configure AOP (Aspect-Oriented Programming) to manage exceptions. Specifically, it enables the translation of database-related exceptions into Spring’s DataAccessException, improving exception handling in data access layers.

3) What is @Transient in Spring Boot?

In JPA (Java Persistence API) or Hibernate, the @Transient annotation indicates that a particular field should not be persisted in the database. This is useful when you want to mark a field that should be ignored during database operations. The field will be treated as a non-persistent field and will not be mapped to a column in the database.

4) How to inject a service class object into a controller?

You can inject a service class object into a controller using the @Autowired annotation. Here is an example:

@Autowired
private MyService myService;

This allows Spring to automatically inject an instance of MyService into the controller.

5) Write a Java program to find the square of each number in a list (using streams)?

Here is an example using Java Streams:

List<Integer> squares = list.stream()
                            .map(x -> x * x)
                            .collect(Collectors.toList());

This code takes each number from the list, squares it, and collects the results into a new list.

6) Can we declare a variable inside an interface?

Of course, but in an interface all variables are public, static and final by default – they must be constants.

7) How to access variables from an interface?

Once a set of variables have been defined using the statement interface, they can be accessed like any other static properties with ClassName.VARIABLE_NAME.

8) What is intern() in Java?

The intern () method puts a string into a special "string pool", so that if multiple string literals are identical they share the same memory reference and memory usage drops.

9) Which collection classes allow NULL?

ArrayList, LinkedList, HashSet, HashMap (keys & values) and Hashtable (values only) all allow NULL. The two exceptions are TreeMap and TreeSet.

10) What happens if we add the same key with different values to a HashMap?

The new value replaces the old one because HashMap doesn't allow duplicate keys.

11) What is the use of load factor?

The load factor in collections such as HashMap determines when the table should be resized to balance performance and memory efficiency; default is 0.75.

12) How to make HashMap thread-safe?

Use Collections.synchronizedMap(new HashMap<>) or ConcurrentHashMap for better concurrent performance.

13) What is the parent class of exceptions in Java?

The root class is Throwable, and has two main subclasses: Exception and Error.

14) What is the difference between function and procedure in SQL?

A function returns a single value that, as it were, becomes an element in queries. A procedure sends back some realization of itself in terms of performance and various tasks.

15) What is a composite key in SQL?

It consists of two or more columns that can identify a unique row in a table,

16) What is a LEFT outer join in SQL?

This returns all records from the left table and the matching records from the right table. IF NO MATCH found with any given record in the LEFT table, NULLs are filled in for the RIGHT table.

17) What is the difference between Comparator and Comparable?

Comparable is used to define a natural ordering (compareTo method), while Comparator allows custom sorting logic (compare method).

18) Can I declare a class as static? If yes, what is a static inner class?

A top-level class cannot be static but a nested (inner) class can be static, that is, not need an instance of the outer class.

19) Why should we use an interface?

Interfaces facilitate multiple inheritance, abstraction and can cut down on the coupling between components.

20) What is the use of encapsulation?

It hides the implementation detail and in fact the data, all through invocations restricted by getters, setters and so on.

21) How to make a class immutable?

Make fields private final, no setters, return deep copies for mutable fields

22) What is the difference between GET and POST?

GET is used to retrieve data, sometimes parameters are added onto the URL. POST sends data to the server in its request body, so it's more suitable for modifying resources.

23) What are the advantages of @GetMapping in Spring Boot?

It simplifies HTTP GET request handling in RESTful APIs and works better than @RequestMapping(method = RequestMethod.GET) in restlaity

24) Where to use @GetMapping & @PostMapping?

Use @GetMapping to retrieve data and @PostMapping to send data to be processed (e.g.,in form submissions).

25) What are the different parts of an HTTP request?

Method (GET, POST, etc.), URL, Headers, Body (optional for GET requests), Parameters.

26) What is Serializable in Java?

It is an interface which allows an object's state to be converted into a byte stream for storage or transfer.

27) What keyword is used to prevent serialization?

Use the transient keyword to exclude fields from serialization.

28) What is the use of serialVersionUID?

It ensures that classes serialize and deserialize compatibly.

29) How to perform Serialization and Deserialization?

Use ObjectOutputStream for serialization and ObjectInputStream for deserialization.

30) What happens if you don't use serialization?

Objects cannot be stored or transmitted as a byte stream, so when encounters error a java.lang. RuntimeException or FileNotFoundException etc will occur.

31) How to connect to Oracle DB from Java application? 

JDBC (Java Database Connectivity) to connect Oracle DB. Oracle JDBC driver, use `DriverManager. Establishing a Connection: By calling `DriverManager.getConnection()`, and executing queries using `Statement` or `PreparedStatement`.

32) Explain the process of connecting Spring application to Oracle DB?  

Set up the Oracle DB connection in `application. properties` or `application. with `DataSource` and `JdbcTemplate` in `application. Use `spring. datasource. url`},`username`, and `password` properties.

33)How to make a Java class Singleton?  

→ Make the constructor private, create a static instance of the class and provide a public static method to access the instance. For Example :  

public class Singleton {  

  private static Singleton instance = new Singleton();  

  private Singleton() {}  

  public static Singleton getInstance() { return instance; }  

}

34) What are the features of Java 8?  

Lambda expressions, functional interfaces, Stream API, default methods in interfaces, Optional class, and new Date and Time API (java. time`).

35) Tell about design patterns which you used in your project? 

Commonly used patterns are Singleton,Factory, and Strategy (adjacent interchangeable algorithms). Singleton: e.g. we make sure there only is one instance of DB connection.

36) What is Spring Batch?

Spring Batch is a batch-processing framework from Spring. It can process large volume of data in batches, has support for retry and skip logic, and integrates with schedulers such as Quartz. 37) Explain about CI/CD tools or Jenkins in your project?  CI/CD tools such as Jenkins help automate building, testing and deploying applications. Automated tests and deployment in production are handled by Jenkins pipelines continuously integrating and delivering code.

38) What are microservices characteristics?  

Microservices are small, independent, and loosely coupled services They are independently deployable, scalable and communicate using APIs (e.g., REST or messaging).

39) How to convert web services to microservices? What are the precautions to take care?

Break monolithic web services into smaller, independent services. Ensure proper API design, data consistency, and fault tolerance. Use tools like API Gateway for routing and monitoring.

40) What are 12 factorS of microservices?  

Those 12 factors are codebase, dependencies, configuration, backing services, build/release/run, processes, port binding, concurrency, disposability, dev/prod parity, logs, and admin processes.

41) List some of the differences between SOAP and RESTful web services?  

SOAP is protocol based XML and supports stateful operations whereas REST is architecture based(JSON/XML) and is stateless. REST is more lightweight and easier to use than SOAP. What are the benefits of RESTful web services? RESTful web services are a lightweight, scalable, stateless and supports multiple data formats (JSON, XML). They have simple integrations with web apps and mobile apps.

42) What are the advantages of RESTful web services?

RESTful web services are lightweight, scalable, stateless, and support multiple data formats (JSON, XML). They are easy to integrate with web and mobile applications.

43) What do you mean with CI/CD tools?  

CI/CD solutions streamline the integration of code updates (Continuous Integration) and the delivery/deployment of those updates to production (Continuous Delivery/Deployment). Some examples of CI tool to list here are Jenkins, GitLab CI, CircleCI etc.

44) Using property file to send data?  

In Spring Boot, we can read data from `application. properties` or `application. yml` files. For example:  

@Value("${app. name}")  

private String appName;

45) What Do You Mean by End-To-End Testing of Microservices?  

End-to-end testing tests the end-to-end functionality of the application, allowing you to check that all the microservices are interacting with each other the way you expected. It allows testing of workflows, APIs and integrations between services.

46) How do you monitor your apps?  

Monitors application performance, logs, and health using tools including Prometheus, Grafana, or Spring Boot Actuator. Create alerts for your important problems.

47) PACT How It Works?  

PACT: A contract testing tool for microservices. Consumer provider contracts ensure that services are integrated based on API contracts defined beforehand and that consumer and provider services fulfil their respective roles in these contracts.

48) What are the multiple strategies of Microservices Deployment?  

Popular strategies are Blue-Green Deployment, Canary Release and Rolling Updates. Most importantly, this allows for zero downtime and gradual rollout of new features. 

49)  List the differences between Monolithic, SOA, and Microservices Architecture with an example for each.

Monolithic: One application (like a Java web app with all modules in a single codebase).  

SOA: ESB (services communication; e.g., banking systems with shared services.) Microservices: Composing independent services (Netflix with separate services for user auth, recommendations, etc.)

50) What is Spring Cloud?  

Spring Cloud addresses tools for building distributed systems and microservices. Features like service discovery (Eureka), configuration management (Config Server), and load balancing (Ribbon) are included.

51) What Are the problems solved by Spring Cloud?

Spring Cloud addresses concerns such as servicediscovery (Eureka), configuration management (Config Server), load balancing (Ribbon), distributed tracing (Sleuth), and API gateway routing (Zuul).

52) What is Cohesion?  

Cohesion is about the degree to which a class or a module's responsibilities arerelated. High cohesion — a class does one thing, making it moremaintainable.

  • High cohesion means the class has a well-defined purpose and performs a specific task, making it easier to maintain and reuse.
  • Low cohesion means the class has unrelated functionalities, leading to complexity and difficulty in understanding.
  • 53) What isCoupling?  

    Couplingis the measure of how much classes or modules depend on each other. Classes are independent, which makes modifying ormaintaining the system easier.

    54) What isDRY from Microservices architecture perspective?  

    In microservices, DRY stands for "don't repeat yourself," which means that we do not want to duplicate code but rather reuse itthrough a common libraryor a command so we don't repeat the business and we want to keep consistency, so you also avoid maintenance efforts.

    55)What is Spring Cloud Bus? Use of it (or) Where did you use Rabbit MQ in yourproject?  

    Spring Cloud Bus ties distributed systems together with a common message broker, suchas RabbitMQ or Kafka. They are also used to publish configurationchanges or events to all microservices.

    56) What is Hashicorp Vault? When to use it with microservices?  

    Hashicorp Vault — A tool for securely accessing secrets like APIkeys, passwords, etc. It works with microservices to offer secure access to criticaldata.

    57)What is JDK, JRE, and JVM?  

    – JDK (Java Development Kit):It contains the tools for developing and compiling the Java programs.  

    JRE (Java Runtime Environment):The runtime environment to run the Java applications.  

    JVM (Java Virtual Machine): Runs Java bytecodeacross different platforms.

    58) A reason why java is platform independent?  

    By compiling Java code into bytecode, Java is platform-independent, and theJVM can run the byte code on any platform.

    59) Why Java isnot 100% Object-oriented?

    Java is not completely object-oriented language as it provides the use of primitive datatypes (like `int`, `char`) which are not objects.

    60) Explain singleton class in java. How can we make a classsingleton?  

    A singleton class makes sure there is onlyone instance. Example:  

    public class Singleton {  

      private static Singleton instance = new Singleton();  

      private Singleton() {}  

      public static Singleton getInstance() { return instance; }  

    }

    61) What is the difference between ArrayList and Vector in java?  

    – ArrayList: unsynchronized, fasterand not thread safe.  

    –Vector: Synchronized, slower and thread-safe.

    62) What are thedifferences between Heap and Stack Memory in Java?

    Heap: Holds objects and isshared between threads.  Stack — A storagefacility for local variables and method calls, thread-specific storage.

    63) If you can tell me about JIT compiler?  

    JIT (Just-In-Time) compiler isresponsible for converting the bytecode into the native code at runtime to enhance the performance.

    64) What areinstance variables? Instance variables are types ofnon-static variables that are declared in a class. 

    They are tied to an objectand can have different values for each.

    65)Explain the difference between break and continue statements?  

    break: Terminates the loop, or switch statement.  

    continue: Jumps tothe next iteration of the loop, skipping the current one.

    66) What is constructor chaining in Java?  

    Constructor chaining :It is calling one constructor from another constructor in the same class by using this() or from a parent class by usingsuper().

    67)What does it mean that Java Strings are immutable?  

    Strings in Java are immutable to provide security to all variables used in the program, thread-safe (they can be shared among threads without having a native code) and optimum formemory (using logical string pooling).

    68) Is it possible tooverride a private or static method in Java?  

    Private and staticmethods are not subject to overriding. Static methods can beoverridden in derived classes.

    69) In how manytypes memory area is allocated by the JVM?  

    There are different memory areas allocated by JVM such as Heap, Stack, Method Area,PC Registers, and Native Method Stack. If I run outof parade with zero args on the command line, the value stored in the String array passed into the main() method is blank or NULL?  

    The Stringarray will be empty (`args. length == 0`), not `null`.

    70) What if I write `static public void` instead of `publicstatic void`?

    The orderof modifiers doesn’t matter. `static public void` is thesame as `public static void`.

    71) What isobject-oriented paradigm?  

    The principles ofobject-oriented paradigm are centred around objects, classes, inheritance, polymorphism, encapsulation and abstraction.

    72) Initially, what will the value ofan object reference be that is defined as an instance variable?  

    The default valueof an object reference is `null`.

    73) Why do we need default constructor?  

    The no-argument constructor initializesan object with default values and is supplied by Java if no constructors is specified.

    74) Whether constructor has any returnvalue?  

    Constructors return no value, not even`void`.

    75) Is constructor inherited?  

    In Java,constructors are not inherited.

    76)Is it possible to make a constructor final?  

    Constructors cannot be declared `final`.

    77) Java static methods in the canbe restricted?

    Static methods do not have direct access to non-static members and cannotuse `this` or `super`.

    78) Are we able to override the staticmethods?  

    no, static methods are never overridden, only hidden in subclasses.

    Here's your formatted text with improved readability while keeping the content unchanged:


    79) What is String Pool?

    In the heap area, there is a special memory called the String Pool. This is where Java stores string literals to avoid duplication and save memory.

    Example:

    String s1 = "Java";
    String s2 = "Java"; // Same reference as s1
    System.out.println(s1 == s2); // Output: true
    

    If a string is created using new, it does not go to the pool.


    80) How many ways can we create a string object?

    There are two ways to create a string:

    1. Using String Literal (Stored in String Pool)
      String s1 = "Hello";
      
    2. Using new Keyword (Stored in Heap Memory)
      String s2 = new String("Hello");
      


    81) What is the difference between throw and throws?

    Feature throw throws
    Purpose Purposely throws an exception. Declares exceptions that may be thrown in a method.
    Usage Inside method body. In method signature.
    Example throw new IOException(); void method() throws IOException {}


    82) Is there any case when finally will not be executed?

    Yes, finally might not execute in these cases:

    • Calling System.exit(0)
    • JVM crashes before execution
    • Infinite loop before finally

    Example:

    try {
        System.exit(0); // JVM exits, so finally will not run
    } finally {
        System.out.println("This won't execute");
    }
    


    83) Can finally block be used without a catch ?

    Yes, a finally block can be used without a catch block.
    It ensures that cleanup operations (like closing resources) always execute.


    84) Is it necessary to have a catch block for every try block?

    No, but a try block must be followed by either:

    • A catch block, OR
    • A finally block

    Example:

    try {
        int a = 10 / 0;
    } finally {
        System.out.println("Finally block executed"); // Runs even without catch
    }
    


    85) How many types of exceptions can occur in Java?

    Java has two main types of exceptions:

    1. Checked Exceptions: Checked at compile-time (e.g.,IOException,SQLException).
    2. Unchecked Exceptions (Runtime Exceptions): Checked at runtime (e.g.,NullPointerException,ArrayIndexOutOfBoundsException).


    86) What is static import?

    static import allows accessing static members without specifying the class name.

    Example:

    import static java.lang.Math.*; // Static import
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(sqrt(16)); // No need to write Math.sqrt()
        }
    }
    


    87) How can we access a class from another class in Java?

    There are three ways to access one class from another:

    1. Same package: Direct access using an object.
    2. Different package: Use import andpublic access modifier.
    3. Static members: Access via ClassName.methodName().

    Example:

    // File: MyClass.java (in package mypackage)
    package mypackage;
    
    public class MyClass {
        public void display() {
            System.out.println("Hello from MyClass");
        }
    }
    
    // File: Main.java (in another package)
    import mypackage.MyClass;
    
    public class Main {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.display(); // Output: Hello from MyClass
        }
    }
    


    88) How to make a write-only class in Java?

    A write-only class allows setting values but restricts reading. This can be done by:

    • Declaring instance variables as private.
    • Providing only setter methods and no getters.

    Example:

    class WriteOnly {
        private String password;
    
        public void setPassword(String password) {
            this.password = password; // No getter method
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            WriteOnly obj = new WriteOnly();
            obj.setPassword("secret123");
            // Cannot retrieve password as there's no getter method
        }
    }
    


    89) How to make a read-only class in Java?

    A read-only class allows reading values but restricts modification. You can achieve this by:

    • Declaring all instance variables as private.
    • Providing only getter methods and no setters.

    Example:

    class ReadOnly {
        private String name;
    
        public ReadOnly(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name; // No setter method
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            ReadOnly obj = new ReadOnly("Java");
            System.out.println(obj.getName()); // Output: Java
        }
    }
    


    89) What is the reason Java does not support pointers? Why not use references?

    For safety and memory management considerations, Java does not support pointers. The use of pointers to access memory directly can lead to vulnerabilities such as memory leaks, buffer overflows, and unsafe memory operations. Therefore, Java manages objects securely by using references to mitigate these risks.

    90) Can we overload the Java main() method?

    Yes, you can overload the main() method by defining multiple versions with different parameter lists. However, public static void main(String[] args) is the only method from which a program can start. Other overloaded methods will not be called automatically by the JVM at runtime.

    public class MainOverload {

    public static void main(String[] args) {

    System.out.println("Main method with String[] args");

    }


    public static void main(int a) {

    System.out.println("Overloaded main method: " + a);

    }

    }

    91) Can we override a static method

    No, static methods cannot be overridden. Static methods belong to the class, not an instance. However, redefining a static method in a subclass is called "method hiding."

    class Parent {

    static void show() {

    System.out.println("Static method in Parent");

    }

    }


    class Child extends Parent {

    static void show() {

    System.out.println("Static method in Child");

    }

    }

    92) Why can't we override a static method?

    Static methods are associated with the class, not any particular object. The concept of runtime polymorphism applies to instance methods at runtime. Since static methods do not rely on objects, they cannot be overridden.

    93) Can we override private methods?

    No, private methods cannot be overridden as they are not accessible outside their class. If you define a method with the same name in a subclass, it is treated as a separate method, not an overridden one.

    class Parent {

    private void display() {

    System.out.println("Private method in Parent");

    }

    }


    class Child extends Parent {

    private void display() {

    System.out.println("Private method in Child");

    }

    }

    94) Can I define the main() method as final?

    Yes, you can define main() as final, and it will function normally. However, once defined as final, it cannot be overridden, but this does not affect its execution.

    public class FinalMain {

    public static final void main(String[] args) {

    System.out.println("Final main method.");

    }

    }

    95) What is the difference between static binding and dynamic binding?

    • Static Binding (Compile-time or Early Binding): Method calls are resolved at compile time (e.g., method overloading).
    • Dynamic Binding (Runtime or Late Binding): Method calls are resolved at runtime based on the actual object type (e.g., method overriding).

    class Parent {

    void show() {

    System.out.println("Parent show()");

    }

    }


    class Child extends Parent {

    void show() {

    System.out.println("Child show()");

    }

    }


    public class Test {

    public static void main(String[] args) {

    Parent obj = new Child(); // Dynamic binding

    obj.show(); // Calls Child's show() method at runtime

    }

    }

    96) What exactly is the instanceof operator in Java?

    The instanceof operator tests whether an object is an instance of a given class or implements a specific interface.

    String s = "Hello";

    System.out.println(s instanceof String); // Output: true

    97) Can you have a method that is both abstract and final?

    No, you cannot define a method that is both abstract and final.

      abstract means: This method must be overridden in a subclass.
    • final means: The method cannot be overridden.

    Thus, these two keywords contradict each other.

    98) Is it possible to instantiate an abstract class?

    No, you cannot create an instance of an abstract class directly. However, you can create an instance of an anonymous subclass.

    abstract class Demo {

    abstract void show();

    }


    public class Test {

    public static void main(String[] args) {

    Demo obj = new Demo() { // Anonymous class

    void show() {

    System.out.println("Abstract method implemented");

    }

    };

    obj.show();

    }

    }

    99) Can you declare an interface method to be static?

    Yes, starting with Java 8, interface methods can be static. However, they cannot be overridden in implementing classes.

    interface MyInterface {

    static void display() {

    System.out.println("Static method in Interface");

    }

    }


    public class Test {

    public static void main(String[] args) {

    MyInterface.display();

    }

    }

    100) Can an interface be final?

    No, an interface cannot be final because final prevents inheritance, and interfaces are designed to be implemented by classes.

    private methods were introduced in Java 9, allowing an interface to have private methods.

  • protected methods are not permitted in interfaces.
  • interface MyInterface {

    private void privateMethod() {

    System.out.println("Private method in Interface");

    }


    default void callPrivate() {

    privateMethod();

    }

    }

    ls command in linux

    ls Command in Linux

    The ls command is one of the most commonly used commands in Linux. It is used to list the contents of a directory, including both files and subdirectories. Below are explanations of the ls command, its options, and examples for your reference.

    Basic Syntax

    ls [options] [directory]
    

    If no directory is provided, ls lists the files and directories in the current directory. Options modify the behavior of the command.

    Common Options

    Option Description
    ls Lists files and directories in the current directory.
    ls -l Displays detailed information (long listing format).
    ls -a Shows hidden files (files starting with a dot .).
    ls -al Combines -l and -a to show detailed information including hidden files.
    ls -h Displays file size in human-readable format (e.g., KB, MB).
    ls -R Recursively lists subdirectories and their contents.
    ls -t Sorts files by modification time (newest first).
    ls -r Reverses the order of the listing.
    ls -S Lists files by size (will cover all files under directories recursively).
    ls -d Lists directories themselves with all contents.
    ls --color Displays output with color-coded file types (enabled by default on most systems).

    Examples

    1. List files in the current directory:

      ls
      

      Output:

      file1.txt  file2.txt  directory1  directory2
      
    2. List files in a specific directory:

      ls /home/user/Documents
      
    3. Display detailed information (long listing format):

      ls -l
      

      Output:

      -rw-r--r-- 1 user user 4096 Oct 1 10:00 file1.txt
      drwxr-xr-x 2 user user 4096 Oct 1 10:00 directory1
      

      Explanation of ls -l output:

      • File Permissions: -rw-r--r--
      • Number of Links: 1
      • Owner: user
      • Group: user
      • File Size: 4096 bytes
      • Last Modified Date: Oct 1 10:00
    4. Display human-readable file sizes:

      ls -lh
      

      Output:

      -rw-r--r-- 1 user user 4.0K Oct 1 10:00 file1.txt
      drwxr-xr-x 2 user user 4.0K Oct 1 10:00 directory1
      
    5. Recursively list all files and subdirectories:

      ls -R
      

      Output:

      .:
      file1.txt  directory1
      
      ./directory1:
      file2.txt
      
    6. Sort files by modification time (newest first):

      ls -t
      
    7. Reverse the order of listing:

      ls -r
      
    8. Combine multiple options (e.g., long listing, human-readable size, and show hidden files):

      ls -lha
      

    Tips

    • Use man ls to see detailed information and explore all available options for the lscommand.
    • Create Aliases for frequently used commands. For example, create an alias ll for ls -la:
      alias ll='ls -la'
      
    • You can toggle color-coded output with --color (if not enabled by default).

    Common Use Cases

    • Check file details: ls -l
    • Find hidden files: ls -a
    • Sort files by size: ls -S
    • List files by modification time: ls -t

    The ls command is an essential tool for navigating and managing files in Linux. Let me know if you need further explanations!



    Select Menu