0% found this document useful (0 votes)
21 views8 pages

Preguntas para Practicar Entrevistas

The document provides an overview of core Java concepts including differences between abstract classes, interfaces and final classes; sets, lists and maps; generics; reflection; algorithms; try-with-resources; objects; pass by value vs reference; constructors and overloading; exceptions; JPA annotations; lambda expressions; streams; immutable objects; object oriented principles like abstraction, encapsulation, inheritance and polymorphism; abstraction vs encapsulation; overloading vs overriding; and concurrency using executors and executor services.

Uploaded by

Jesús
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views8 pages

Preguntas para Practicar Entrevistas

The document provides an overview of core Java concepts including differences between abstract classes, interfaces and final classes; sets, lists and maps; generics; reflection; algorithms; try-with-resources; objects; pass by value vs reference; constructors and overloading; exceptions; JPA annotations; lambda expressions; streams; immutable objects; object oriented principles like abstraction, encapsulation, inheritance and polymorphism; abstraction vs encapsulation; overloading vs overriding; and concurrency using executors and executor services.

Uploaded by

Jesús
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Core Java

Difference between an abstract class, interface, and a final class:


● An abstract class can have abstract and concrete methods, while an interface only has abstract methods. A
final class cannot be subclassed. Abstract classes and interfaces can be inherited by multiple classes.

Behavioral differences between a Set, a List, and a Map:


● A Set does not allow duplicate elements, a List allows duplicate elements and maintains order, and a Map is a
collection of key-value pairs where keys are unique.

Generics and its importance:


● Generics allow the creation of classes, interfaces, and methods that operate on types parameterized at compile
time. It enhances type safety by detecting errors at compile time rather than runtime. Also, it allows Code
Reusability
// A generic class that represents a simple Box holding a value of any type
public class Box<T> {
private T value;

public Box(T value) {


this.value = value;
}

public T getValue() {
return value;
}

public void setValue(T value) {


this.value = value;
}

public void displayBoxContents() {


System.out.println(value);
}

public static void main(String[] args) {


// Creating a Box of Integer type
Box<Integer> integerBox = new Box<>(42);
integerBox.displayBoxContents();

// Creating a Box of String type


Box<String> stringBox = new Box<>("Hello, Generics!");
stringBox.displayBoxContents();

// Generic Class returns: 42


// Generic Class returns: Hello, Generics!
}
}

Reflection and an example:


● Reflection is a feature that enables the inspection and manipulation of classes, interfaces, fields, and methods at
runtime. An example is accessing private fields or invoking private methods of a class.
public class AccesoPrivadoEjemplo {

public static void main(String[] args) throws Exception {


// Crear una instancia de la clase
MiClase instancia = new MiClase();

// Acceder a un campo privado


Field campoPrivado = MiClase.class.getDeclaredField("campoPrivado");
campoPrivado.setAccessible(true); // Hacer que el campo sea accesible
String valorCampo = (String) campoPrivado.get(instancia);
System.out.println("Valor del campo privado: " + valorCampo);

// Invocar un método privado


Method metodoPrivado = MiClase.class.getDeclaredMethod("metodoPrivado");
metodoPrivado.setAccessible(true); // Hacer que el método sea accesible
metodoPrivado.invoke(instancia);

1
}
}

class MiClase {
private String campoPrivado = "¡Este es un campo privado!";

private void metodoPrivado() {


System.out.println("¡Este es un método privado!");
}
}te ejemplo

Criteria to choose between two algorithms (e.g., sorting):


● Criteria include the size of the dataset, time complexity, space complexity, stability, and whether the data is
nearly sorted or random.

What is the Java feature: try with resources?


● try-with-resources is a feature that automatically closes resources (like files, sockets) when they are no longer
needed. It simplifies resource management and helps prevent resource leaks.

String filePath = "example.txt";

// Using try-with-resources to automatically close the BufferedReader


try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
// Reading the content of the file line by line
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
//BufferedReader is automatically closed when the try block is exited, even if an exception occurs.
}
}

What is an object?
● An object is a specific instance of a class. It represents a real-world entity and has associated attributes (data)
and methods (functions). An object is created by instantiating a class using the "new" keyword.
What is the difference between pass by value and pass by reference?
● In pass by value, a copy of the original parameter value is passed, while in pass by reference, the memory
address of the original value is passed.
What is a constructor?
● Is a special method within a class that is automatically called when creating an object of that class. It is used
to initialize the object's attributes.
What is constructor overloading?
● Constructor overloading involves having multiple constructors in a class, each with a different signature
(number or type of parameters). It allows for the creation of objects in various ways.
How do you handle exceptions in Java?
● Exceptions in Java are handled using the "try-catch" block. Code prone to errors is placed within the "try" block,
and exceptions are handled in the "catch" block.

What are JPA annotations:


● In Java Persistence API (JPA), annotations are used to map Java objects to database tables and define the
behavior of the persistence layer.
● @Entity: Indicates that the class is a JPA entity, which corresponds to a database table.
● @Table: Specifies the details of the database table to which the entity is mapped, such as the table name and
schema.
● @Id, @GeneratedValue, @Column, @Transient, @OneToMany and @ManyToOne, @JoinTable,
@JoinColumn, @NamedQuery, @NamedQueries

What are Lambda expressions?

2
● Lambda expressions are anonymous functions that don't require a class. Their structure is: (parameters) ->
{lambda body}. They work in conjunction with functional interfaces to assign different behaviors to an abstract
method.

Diference between functional interfaces and lambda expressions:


● A functional interface is an interface with a single abstract method, and lambda expressions provide a concise
syntax for implementing that single method.
@FunctionalInterface
public interface ICalculadoraLambda {
public int operacion (int x,int y);
}

ICalculadoraLambda iSuma = (x,y) -> x + y;


System.out.println(iSuma.operacion(4, 5));

ICalculadoraLambda iMultiplicacion= (x,y) -> x * y;


System.out.println(iMultiplicacion.operacion(4, 5));

What is a Stream and Parallel Stream?


● A stream is a sequence of elements that can manipulate and transform data on collections in a functional
style with a focus on declarative programming. With parallelstream the processing of elements can be split
across multiple threads, potentially leading to better performance, especially for large datasets.

What are the operations does Stream Support?


● Intermediate operations (transforms one Stream<T> into another): filter( ), map( ), distinct( ), sorted( )
● Terminal operations (returns a result of a defined type): forEach( ), count( ), collect( ), reduce( )

Immutable objects
● It envolves careful design practices, such as declaring fields as final, avoiding setter methods, and ensuring that
the object's state is set only through the constructor or static factory methods.

What are Object Oriented principles?


● Abstraction shows only useful data by providing only the most necessary details.
● Encapsulation is used to restrict direct access to attributes and methods of a class by using access modifiers.
● Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object.
● Polymorphism refers to the ability of a class to provide different implementations of a method, depending on the
type of object that is passed to the method.
○ Compile-time Polymorphism: occurs at compile time. It involves method overloading.
○ Runtime Polymorphism: occurs at runtime. It involves method overriding, where a subclass provides a
specific implementation of a method that is already defined in its superclass. The decision about which
method to call is made during runtime.

Difference between Abstraction & Encapsulation


● Abstraction is about simplifying the system by defining essential features, while encapsulation is about grouping
data and methods together to hide internal details and control access to the object's state.

What is Overloading and Overriding?


● Method overloading is a feature that allows a class to have more than one method having the same name but
with different number or type of parameters. The return type of the methods can be the same or different. It is
related to compile-time polymorphism and is resolved during the compile time.
● Method overriding is a feature that allows a subclass to provide a specific implementation of a method that is
already defined in its superclass with same signature (name, return type, and parameters). It is related to runtime
polymorphism and is resolved during the runtime.

Concurrency - Executor and ExecutorService differences:


● Executor is a simple interface for launching and managing threads, while ExecutorService provides a more
complete set of methods to manage, control, and obtain the results of asynchronous tasks.

ExecutorExample:
import java.util.concurrent.Executor;

public class SimpleExecutorExample {

3
public static void main(String[] args) {
// Creating an Executor (in this case, using a simple executor)
Executor executor = Runnable::run; // This runs tasks in the same thread.

// Submitting a task for execution


executor.execute(() -> System.out.println("Task executed asynchronously"));
}
}

ExecutorService Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {

public static void main(String[] args) {


// Creating an ExecutorService with a fixed-size thread pool
ExecutorService executorService = Executors.newFixedThreadPool(2);

// Submitting tasks for execution


executorService.submit(() -> System.out.println("Task 1 executed"));
executorService.submit(() -> System.out.println("Task 2 executed"));
executorService.submit(() -> System.out.println("Task 3 executed"));

// Shutting down the executor service


executorService.shutdown();
}
}

Multithreading
Multithreading provides a way to achieve parallelism, and it's important to handle synchronization properly to avoid race
conditions and ensure thread safety.

Thread Lifecycle: New → Runnable (start()) → Running (run()) → Terminated


→ Blocked (suspend(), wait(), sleep())) → Waiting/Timed Waiting
join()→ makes the main Thread waits until the secondary thread (who invoked join) has finished

Extending the Thread Class


class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}

// Creating and starting a new thread


MyThread myThread = new MyThread();
myThread.start();

Implementing the Runnable Interface:


class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}

// Creating and starting a new thread using the Runnable interface


Thread myThread = new Thread(new MyRunnable());
myThread.start();

// Synchronized methods
synchronized (objetoBloqueo) {
// Código que necesita sincronización
}

4
What is a Singleton?
● Is a design pattern that ensures that a class has only one instance and provides a way to access that instance
from any point in the application. Use cases: Database Connection Pooling, Logging, Configuration Management,
Caching.
public class Singleton {
// Instancia única
private static Singleton instancia;

// Constructor privado para evitar instanciación directa


private Singleton() {
// Inicialización del objeto
}

// Método para obtener la instancia única


public static Singleton obtenerInstancia() {
if (instancia == null) {
instancia = new Singleton();
}
return instancia;
}
}

Spring
What is Dependency Injection?
● Is the process of providing the dependencies that a class requires, rather than being created internally. The
Spring IoC container injects these dependencies into the object during its creation. Simplifies unit testing, as it is
easy to provide mock or test implementations of dependencies.

What is a bean in Spring?


● Is an object that is instantiated, assembled, and managed by a Spring IoC container. To create a Spring Bean, you
typically define a Java class as a @Component

How can we inject beans in Spring?


● Constructor Injection, setter Injection, field Injection, method Injection.

What are stereotypes?


● Stereotypes are annotations that help in organizing and configuring Spring components by providing metadata
about the purpose of the class. They allow Spring to understand the role of each class in the application context.
● @Component → @Controller, @Service, @Repository

Difference between SpringMVC and SpringBoot


● While Spring MVC focuses on web application development with an MVC architecture, Spring Boot focuses on
simplifying the configuration and development of Spring applications in general, particularly for building
standalone and microservices applications.

SQL
Diference between Stored procedures and functions:
● Stored procedures are more suitable for operations that directly affect the database, while functions are more
suitable for calculations and data manipulations that return a value.

Difference between SQL and NoSQL databases


● SQL databases are relational and structured, suitable for applications with well-defined schemas and
transactions, while NoSQL databases are more flexible, scalable, and suitable for handling dynamic,
unstructured data in distributed and horizontally scalable environments. The choice between SQL and NoSQL
depends on the specific requirements and characteristics of the application.

What is horizontal and vertical scaling


Horizontal scaling involves adding more machines or nodes to distribute the load, while vertical scaling involves
enhancing the capacity of an existing machine.

5
JOINS

Web
What are the protocols for working with web services?
● SOAP (Simple Object Access Protocol) and REST (Representational State Transfer). These define how
communication should occur between applications on different systems.

What JS/CSS frameworks you know? What's your favorite? Why?


● JS: React.js (Facebook), Angular (Google), Vue.js
● CSS: Bootstrap, Flexbox, Foundation

List several ways you can communicate asynchronously with the server?
● AJAX, Fetch API, WebSockets, Server-Sent Events (SSE)

What is server side data pagination? What is client side pagination?


● Server-side pagination involves requesting only a subset of data from the server and rendering that portion on
the client side. When the user requests a new page or set of data, the client sends a request to the server, which
responds with the relevant data for that specific page.
● Client-side pagination involves loading the entire dataset on the client side and then displaying only a subset of
data at a time. Pagination is managed on the client side without making additional requests to the server when the
user navigates between pages.

CSS
What are some of the ways to apply style to a web page?
● Inline Styles, Internal Styles (Embedded Styles) within the <style>, External Styles with CSS file using <link>,
CSS Selector Types, Media Queries, CSS frameworks.

How do CSS cascading rules work?


● 1) Inline Styles 2) ID Selectors (#) 3) Class selectors ( . ) 4) Element Selectors (p)
● !important, source order, inheritance

JavaScript
What is destructuring in JavaScript?
● Destructuring is a feature that allows objects or arrays to be broken down into smaller parts to access their
elements more directly.
const person = { name: 'John', age: 30 };

6
const { name, age } = person;
console.log(name); // Output: John

What is hoisting in JavaScript?


● Hoisting is a behavior where declarations (both variables and functions) are moved to the top of their execution
context during the compilation phase. However, only the declaration is moved, not the assignment.

What are arrow functions in JavaScript?


● Arrow functions are a concise way to write functions in JavaScript introduced in ECMAScript 6. They are
characterized by the use of the => syntax and have a different behavior regarding the value of this.

What is the scope of variables in JavaScript?


● Scope refers to the context in which a variable can be referenced and modified. In JavaScript, there is global
scope and local scope.

What is variable coercion in JavaScript?


● Coercion is the automatic conversion of one data type to another in JavaScript during execution. It can be implicit
(automatic) or explicit (performed by the programmer).

How do you clone an object in JavaScript?


● You can clone an object using the Object.assign() method or the spread operator (...).

// Using Object.assign()
const original = { a: 1, b: 2 };
const clone = Object.assign({}, original);

// Using the spread operator


const clone2 = { ...original };

Is JavaScript syntax case sensitive?


● Yes

Angular Questions
Two way binding in Angular
● Is a mechanism that allows the data synchronization between the model (component) and the view (template).
It combines property binding and event binding into a single syntax using the ngModel directive.

Forms
● Angular provides two types of forms: Template-Driven Forms defined in the template using directives like
ngForm, ngModel, etc. Suitable for simple scenarios and quick development.
● and Reactive Forms (Model-Driven Forms). Defined programmatically in the component using FormBuilder
and FormControl. Suitable for complex scenarios and better control over form logic.

Form groups
● A form group is a collection of form controls that are part of a larger form. It allows you to organize controls
hierarchically and is commonly used in reactive forms.

Design Patterns
● Angular applications often use design patterns such as Singleton, Dependency Injection, and Observer (using
Observables) to enhance modularity, maintainability, and testability.

Difference between Observable and Promise?

Observable Promise

● Represents a stream of values or events over time. ● Represents a single future value or error.
● Can be cancelled. ● Not cancellable.
● Supports multiple values over time. ● Supports a single value resolution.

7
● Lazy, only executes when subscribed to. ● Eager, executes immediately when created.

Difference between Subject and Observable?

Subject Observable

● Represents a stream of values or events over time. ● Represents the idea of an invokable collection
● Can be cancelled. of future values or events.
● Supports multiple values over time. ● Lazy by nature.
● Lazy, only executes when subscribed to.

How do you establish a connection between a parent and child in Angular?

Communication between parent and child components in Angular can be achieved using Input properties for passing
data from parent to child, and using Output properties and EventEmitter for passing data from child to parent.

Example of Parent Component:


// parent.component.ts
@Component({
selector: 'app-parent',
template: '<app-child [data]="parentData" (childEvent)="handleChildEvent($event)"></app-child>'
})
export class ParentComponent {
parentData = 'Data from parent';

handleChildEvent(data: string) {
console.log('Data received from child:', data);
}
}
Example of Child Component:
// child.component.ts
selector: 'app-child',
template: '<p (click)="sendDataToParent()">Click me!</p>'
})
export class ChildComponent {
@Input() data: string;
@Output() childEvent = new EventEmitter<string>();

sendDataToParent() {
this.childEvent.emit('Data from child');
}
}
This allows for bidirectional communication between parent and child components in Angular.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy