Java MCQ PDF
Document Details
Uploaded by IngeniousParallelism2116
Tags
Summary
This document contains a Java multiple-choice question (MCQ) quiz focusing on topics in CORE JAVA, J2EE, and Hibernate. It presents questions and their respective answers to reinforce concepts.
Full Transcript
# CORE JAVA ## 1. What will be the output of the following code? ```java public class Test { public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; String s3 = new String("abc"); System.out.println(s1 == s2); System.out.println(s1 == s3); } } ``` A. true true B. true false C...
# CORE JAVA ## 1. What will be the output of the following code? ```java public class Test { public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; String s3 = new String("abc"); System.out.println(s1 == s2); System.out.println(s1 == s3); } } ``` A. true true B. true false C. false true D. false false **Answer: B. true false** ## 2. What is the output of the following code? ```java public class Test { public static void main(String[] args) { int x = 2; int y = 0; for (;y < 10; ++y) { if (y % x == 0) { continue; } else if (y == 8) { break; } else { System.out.print(y + " "); } } } } ``` A. 1357 B. 13579 C. 13578 D. 13579 10 **Answer: A. 1357** ## 3. Given the following class hierarchy, what will be the output of the code? ```java class A { int a = 10; } class B extends A { int a = 20; } public class Test { public static void main(String[] args) { A obj = new B(); System.out.println(obj.a); } } ``` A. 10 B. 20 C. Compilation error D. Runtime error **Answer: A. 10** ## 4. What will be the output of the following code? ```java public class Test { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; for (int i = 0; i < arr.length; i++) { arr[i] = arr[arr.length - 1 - i]; } System.out.println(Arrays.toString(arr)); } } ``` A. [5, 4, 3, 2, 1] B. [5, 4, 3, 4, 5] C. [5, 5, 3, 2, 1] D. [5, 4, 3, 2, 5] **Answer: B. [5, 4, 3, 4, 5]** ## 5. Consider the following code: ```java interface X { default void print() { System.out.println("X"); } } interface Y { default void print() { System.out.println("Y"); } } class Z implements X, Y { public void print() { X.super.print(); } } public class Test { public static void main(String[] args) { new Z().print(); } } ``` What is the output? A. Compilation error B. X C. Y D. Runtime error **Answer: B. X** # J2EE ## 1. Which of the following is not a component of the J2EE architecture? A. Servlets B. JSP (JavaServer Pages) C. EJB (Enterprise JavaBeans) D. AWT (Abstract Window Toolkit) **Answer: D. AWT (Abstract Window Toolkit)** ## 2. Which of the following is true about Enterprise JavaBeans (EJB)? A. EJB can only be used for web applications. B. EJB supports distributed transactions. C. EJB does not *support* session beans. D. EJB is used for client-side programming. **Answer: B. EJB supports distributed transactions.** ## 3. In the context of J2EE, what does the Java Naming and Directory Interface (JNDI) provide? A. A way to define database schemas B. An API for directory service that allows Java software clients to discover and look up data and objects via a name C. A library for creating graphical user interfaces D. A method to handle HTTP requests and responses **Answer: B. An API for directory service that allows Java software clients to discover and look up data and objects via a name** ## 4. Which of the following best describes the role of a deployment descriptor (web.xml) in a J2EE web application? A. It defines the visual layout of web pages B. It specifies configuration and deployment information for the web application, including servlets and URL mappings C. It is used to manage database connections D. It stores application properties **Answer: B. It specifies configuration and deployment information for the web application, including servlets and URL mappings** ## 5. What is the primary function of a Servlet in the J2EE architecture? A. To handle database interactions B. To generate dynamic web content and handle HTTP requests C. To create and manage user sessions D. To compile and execute Java code **Answer: B. To generate dynamic web content and handle HTTP requests** # Hibernate ## 1. In Hibernate, which of the following is the correct way to map an immutable entity? A. Use @Immutable annotation B. Set @DynamicUpdate to true C. Use @NaturalId annotation D. Configure the mapping file to *mutable=false* **Answer: A. Use @Immutable annotation** ## 2. What does the @Fetch(FetchMode.SUBSELECT) annotation do in Hibernate? A. Fetches data using a secondary select statement for each relationship B. Fetches associated collections using a subselect query in a single round trip C. Eagerly fetches all associations in one single SQL query D. Fetches data using a JOIN operation **Answer: B. Fetches associated collections using a subselect query in a single round trip** ## 3. Which of the following is true about the second-level cache in Hibernate? A. The second-level cache is session-specific. B. Entities cached at the second-level cache are visible to all sessions. C. The second-level cache is cleared at the end of each session. D. The second-level cache is configured per entity and collection. **Answer: B. Entities cached at the second-level cache are visible to all sessions.** ## 4. In Hibernate, what is the effect of using @version annotation on a field? A. It defines the version of the database schema. B. It marks the field to be used for optimistic locking. C. It specifies that the field should be lazy-loaded. D. It indicates that the field is indexed. **Answer: B. It marks the field to be used for optimistic locking.** ## 5. Which of the following statements is correct about the @NaturalId annotation in Hibernate? A. *It marks a field to be uniquely identified but not immutable.* B. It automatically generates a unique identifier for the entity. C. It is used to map a natural business key to a unique constraint in the database. D. It is used to define a composite key for an entity. **Answer: C. It is used to map a natural business key to a unique constraint in the database.** # Spring Framework ## 1. Which annotation is used to define a Spring component that is eligible for Spring's component scanning to detect and register as a Spring bean? A. @Service B. @Component C. @Repository D. @Controller **Answer: B. @Component** ## 2. What is the primary purpose of the @Autowired annotation in Spring? A. To define a custom scope for a bean B. To inject dependencies automatically by type C. To configure a property file for a bean D. To create a new instance of a bean **Answer: B. To inject dependencies automatically by type** ## 3. Which of the following is true about Spring Boot? A. It provides a CLI tool for developing and testing Spring applications. B. It requires extensive XML configuration files. C. It is incompatible with microservices architecture. D. It does not support RESTful web services. **Answer: A. It provides a CLI tool for developing and testing Spring applications.** ## 4. In Spring, what is the use of the @Transactional annotation? A. To mark a method as requiring transaction management B. To define a method as asynchronous C. To automatically create a bean in the application context D. To inject dependencies into a constructor **Answer: A. To mark a method as requiring transaction management** ## 5. How can you define a custom scope for a Spring bean? A. By using the @Scope annotation with the appropriate scope name B. By defining the scope in the *application.properties* file C. By using the @Bean annotation D. By extending the Scope interface and registering it in the application context **Answer: D. By extending the Scope interface and registering it in the application context** # Web Services ## 1. In the context of SOAP-based web services, what is the primary purpose of WSDL (Web Services Description Language)? A. To describe the methods available in a web service, including their signatures and types. B. To handle the HTTP requests and responses for a web service. C. To define security policies for web services. D. To perform schema validation for XML documents used in the web service. **Answer: A. To describe the methods available in a web service, including their signatures and types.** ## 2. Which of the following HTTP methods is idempotent and typically used in RESTful web services to update a resource? A. GET B. POST C. PUT D. DELETE **Answer: C. PUT** ## 3. What is the role of UDDI (Universal Description, Discovery, and Integration) in web services? A. To provide a standard for web services security. B. To define the structure of XML documents used in web services. C. To act as a registry for businesses and their web services. D. To handle transactions in a distributed environment. **Answer: C. To act as a registry for businesses and their web services.** ## 4. In RESTful web services, what does the acronym HATEOAS stand for? A. Hypermedia As The Engine Of Application State B. Hypertext Application Transfer Enabling Object Serialization C. Hypertext And Transfer Enabling Of Application State D. Hypermedia Application Transfer Enabling Object State **Answer: A. Hypermedia As The Engine Of Application State** ## 5. Which of the following is a correct description of the WS-Security standard? A. It is used to ensure the encryption of data at rest. B. It is used to provide message integrity, confidentiality, and authentication in SOAP-based web services. C. It is a protocol for service discovery in RESTful web services. D. It is a format for describing network protocols. **Answer: B. It is used to provide message integrity, confidentiality, and authentication in SOAP-based web services.** # Design Pattern ## 1. In the Strategy pattern, what is the main benefit of using composition over inheritance? A. It allows the algorithm to be selected at runtime. B. It ensures that the class hierarchy remains shallow. C. It enforces the use of a single algorithm throughout the application. D. It allows algorithms to be defined in the base class. **Answer: A. It allows the algorithm to be selected at runtime.** ## 2. Which of the following best describes the Bridge pattern? A. It decouples an abstraction from its implementation so that the two can vary independently. B. It ensures that a class has only one instance. C. It simplifies complex class hierarchies by allowing them to share structure and behavior. D. It allows an object to alter its behavior when its internal state changes. **Answer: A. It decouples an abstraction from its implementation so that the two can vary independently.** ## 3. In the context of the Proxy pattern, which type of proxy is used to control access to an object by permitting some operations and blocking others? A. Virtual Proxy B. Protection Proxy C. Remote Proxy D. Cache Proxy **Answer: B. Protection Proxy** ## 4. Which design pattern is described as allowing an object to alter its behavior when its internal state changes, effectively changing its class? A. State B. Memento C. Command D. Strategy **Answer: A. State** ## 5. What is the main drawback of the Singleton pattern in a multithreaded environment without synchronization? A. It can lead to a large memory footprint. B. It complicates the class inheritance structure. C. It can result in multiple instances being created. D. It increases the coupling between components. **Answer: C. It can result in multiple instances being created.** # Micro Services ## 1. Which of the following is a key principle of microservices architecture? A. Large, monolithic codebase B. Centralized data management C. Loose coupling and high cohesion D. Single deployment for all services **Answer: C. Loose coupling and high cohesion** ## 2. In microservices architecture, what is the purpose of a service registry? A. To store user authentication details B. To provide a central point for managing service configuration C. To enable dynamic discovery and lookup of microservices D. To handle asynchronous messaging between services **Answer: C. To enable dynamic discovery and lookup of microservices** ## 3. Which of the following best describes the role of an API Gateway in microservices architecture? A. It directly communicates with databases for CRUD operations B. It provides a single entry point for clients, routing requests to the appropriate microservice C. It handles the orchestration of distributed transactions D. It manages container orchestration and scaling **Answer: B. It provides a single entry point for clients, routing requests to the appropriate microservice** ## 4. What does the CAP theorem state about distributed systems? A. It is impossible for a distributed system to simultaneously provide more than two out of three guarantees: Consistency, Availability, and Partition Tolerance B. It ensures that a distributed system will always be consistent C. It mandates that all distributed systems must use a single data store D. It is focused on optimizing latency in distributed systems **Answer: A. It is impossible for a distributed system to simultaneously provide more than two out of three guarantees: Consistency, Availability, and Partition Tolerance** ## 5. Which of the following patterns can be used to handle inter-service communication in a microservices architecture to ensure resilience? A. Singleton Pattern B. Observer Pattern C. Circuit Breaker Pattern D. Abstract Factory Pattern **Answer: C. Circuit Breaker Pattern** # Web Design ## 1. What is the output of the following JavaScript code? ```javascript let obj = { a: 1, b: 2, getSum: function() { return this.a + this.b; } }; let sum = obj.getSum; console.log(sum()); ``` A. 3 B. 2 C. undefined D. NaN **Answer: D. NaN** ## 2. In CSS3, which property is used to apply a 3D transformation to an element? A. transform3d B. transform C. transition D. perspective **Answer: B. transform** ## 3. Which of the following HTML5 elements is used to group together a set of options in a drop-down list? A. `<select>` B. `<optgroup>` C. `<option>` D. `<fieldset>` **Answer: B. `<optgroup>`** ## 4. What does the *position: sticky;* property in CSS3 do? A. It positions an element relative to the browser window. B. It positions an element relative to its normal position and then makes it fixed at a specific offset as the user scrolls. C. It positions an element absolutely based on the nearest positioned ancestor. D. It positions an element fixed at the top of the viewport. **Answer: B. It positions an element relative to its normal position and then makes it fixed at a specific offset as the user scrolls.** ## 5. Given the following JavaScript code, what will be the output? ```javascript (function() { })(); console.log(typeof this); ``` A. object B. function C. undefined D. global **Answer: A. object** # React JS ## 1. What will be the output of the following code snippet in React? ```javascript function App() { const [count, setCount] = React.useState(0); React.useEffect(() => { setCount((prevCount) => prevCount + 1); setCount((prevCount) => prevCount + 1); }, []); return <div>{count}</div>; } ``` A. 0 B. 1 C. 2 D. Undefined **Answer: C. 2** ## 2. Which of the following statements is true about the *useMemo* hook in React? A. It is used to memoize functional components to avoid re-rendering. B. It is used to memoize values and prevent expensive calculations on every render. C. It is used to memoize component props to enhance performance. D. IT is used to memoize class component state updates. **Answer: B. It is used to memoize values and prevent expensive calculations on every render.** ## 3. How can you prevent a component from re-rendering in React when its parent re-renders? A. Use *React.memo* B. Use *useState* C. Use *useEffect* D. Use *useRef* **Answer: A. Use *React.memo*** ## 4. What is the output of the following code in React? ```javascript const TestComponent = () => { const [state, setState] = React.useState(0); const updateState = React.useCallback(() => { setState(state + 1); }, [state]); return ( <button onClick={updateState}> {state} </button> ); }; ``` A. The button will not update its text when clicked. B. The button will always display 1 when clicked. C. The button will display the correct incremented value each time it is clicked. D. The button will throw an error on click. **Answer: C. The button will display the correct incremented value each time it is clicked.** ## 5. Which statement about the context API in React is correct? A. Context should be used for passing props deeply, such as a theme or user data, without prop drilling. B. Context replaces all state management libraries such as Redux. C. Context is used to manage component lifecycle methods. D. Context can only be used within class components. **Answer: A. Context should be used for passing props deeply, such as a theme or user data, without prop drilling.** # AWS ## 1. Which AWS service is primarily used for running Docker containers? A. Amazon S3 B. Amazon EC2 C. Amazon ECS D. AWS Lambda **Answer: C. Amazon ECS** ## 2. What is the main purpose of AWS Lambda? A. To provide a managed relational database service B. To run code without provisioning or managing servers C. To store and retrieve objects in the cloud D. To manage DNS configurations **Answer: Β. Τo run code without provisioning or managing servers** ## 3. Which AWS service is used to automate the creation and management of AWS resources using templates? A. AWS CloudFormation B. AWS CodeDeploy C. AWS CodePipeline D. AWS Elastic Beanstalk **Answer: A. AWS CloudFormation** ## 4. What is the primary use of Amazon DynamoDB? A. To run virtual servers in the cloud B. To provide a managed relational database service C. To provide a fully managed NoSQL database service D. To manage Docker containers **Answer: C. To provide a fully managed NoSQL database service** ## 5. Which AWS service is used for continuous integration and continuous delivery (CI/CD)? A. AWS CodeDeploy B. AWS CodePipeline C. AWS CodeCommit D. AWS Cloud9 **Answer: B. AWS CodePipeline** # Introduction to SQL ## 1. Which of the following SQL clauses is used to filter groups of rows based on a specified condition? A. GROUP BY B. WHERE C. HAVING D. ORDER BY **Answer: C. HAVING** ## 2. Consider the following SQL query: ```sql SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000; ``` What does this query do? A. It selects all employees from departments where the average salary is greater than 50,000. B. It groups employees by their department and selects those departments where the average salary is greater than 50,000. C. It calculates the average salary of employees and filters out those with salaries below 50,000. D. It orders employees by their department and average salary. **Answer: B. It groups employees by their department and selects those departments where the average salary is greater than 50,000.** ## 3. What is a correlated subquery in SQL? A. A subquery that is executed once for the entire query. B. A subquery that references columns from the outer query. C. A subquery that contains a join operation. D. A subquery that returns multiple rows to the outer query. **Answer: B. A subquery that references columns from the outer query.** ## 4. Which of the following SQL statements is used to create an index on a table? A. CREATE INDEX B. ADD INDEX C. ALTER INDEX D. INSERT INDEX **Answer: A. CREATE INDEX** ## 5. Given the following SQL table *orders*: ```sql CREATE TABLE orders ( order_id INT, customer_id INT, order_date DATE, amount DECIMAL(10, 2) ); ``` Which query will return the total amount of orders for each customer placed in the year 2023? A. ```sql SELECT customer_id, SUM(amount) FROM orders WHERE YEAR(order_date) = 2023 GROUP BY customer_id;``` B. ```sql SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id HAVING YEAR(order_date) = 2023;``` C. ```sql SELECT customer_id, SUM(amount) FROM orders WHERE order_date LIKE '2023%' GROUP BY order_date;``` D. ```sql SELECT customer_id, TOTAL(amount) FROM orders WHERE order_date LIKE '2023%' GROUP BY customer_id;``` **Answer: A.** ```sql SELECT customer_id, SUM(amount) FROM orders WHERE YEAR(order_date) = 2023 GROUP BY customer_id; ```