0% found this document useful (0 votes)
6 views

Quiz

The document consists of a series of questions and answers related to Java programming, covering topics such as object-oriented principles, exception handling, JDBC, and SOLID principles. Each question tests knowledge on specific concepts, default values, syntax, and best practices in Java. The answers indicate correct responses for each question, highlighting key programming concepts.

Uploaded by

asergalie
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Quiz

The document consists of a series of questions and answers related to Java programming, covering topics such as object-oriented principles, exception handling, JDBC, and SOLID principles. Each question tests knowledge on specific concepts, default values, syntax, and best practices in Java. The answers indicate correct responses for each question, highlighting key programming concepts.

Uploaded by

asergalie
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Question 1

Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following principles is applied when you design a system with
simple, modular components that can easily be extended?

a.
Data hiding

b.
Extensibility

c.
KISS

d.
DRY

e.
Polymorphism

Question 2
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the default value of an instance variable of type boolean in Java?

a.
undefined

b.
false

c.
true

d.
0

e.
null

Question 3
Correct
Mark 1.00 out of 1.00
Flag question

Question text
What is the default value of an array element in a String[] array?

a.
null

b.
false

c.
"" (empty string)

d.
undefined

e.
0

Question 4
Correct
Mark 1.00 out of 1.00

Flag question

Question text
How can you achieve data hiding in a Java class?

a.
By using abstract methods

b.
By using private instance variables and providing public getters and setters

c.
By using multiple inheritance

d.
By making all variables public

e.
By creating complex methods

Question 5
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What will be the output of the following code? class Test { static int a = 10;
Test() { a += 5; } public static void main(String[] args) { Test t1 = new Test();
Test t2 = new Test(); System.out.println(a); }

a.
10

b.
20

c.
None of the above

d.
Compile error

e.
15

Question 6
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the key benefit of the KISS (Keep It Simple, Stupid) principle?

a.
Making the code modular

b.
Keeping the code simple and easier to maintain

c.
Making the code difficult to understand

d.
Writing long and complex methods

e.
Reducing the system’s performance

Question 7
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which keyword is used to refer to the current instance of a class?
a.
current

b.
object

c.
this

d.
super

e.
instance

Question 8
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the default value of a boolean in Java?

a.
null

b.
true

c.
false

d.
1

e.
0

Question 9
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What will the following code output? int x = 5; x = x > 3 ? x + 1 : x - 1;
System.out.println(x);

a.
Compile error

b.
7

c.
6

d.
5

e.
4

Question 10
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the correct syntax to initialize a 1D array in Java?

a.
int[] arr = new int[3];

b.
int[] arr = new int[]{1,2,3};

c.
int[] arr; arr = {1,2,3};

d.
int[] arr = {1,2,3};

e.
All of the above

Question 11
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following is a benefit of using method overriding?

a.
It makes the code more complex

b.
It allows private methods to be accessed by subclasses

c.
It prevents a method from being called in a subclass
d.
It allows subclasses to inherit methods from the superclass

e.
It enables a subclass to change the behavior of an inherited method

Question 12
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What does System.out.println(true ? "A" : "B"); print?

a.
B

b.
True

c.
None of the above

d.
False

e.
A

Question 13
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the result of System.out.println("Java".charAt(2));?

a.
J

b.
v

c.
Compile error

d.
None of the above

e.
a
Question 14
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following is true about method overriding in Java?

a.
The overriding method can have a different return type than the method in the
superclass

b.
The overriding method can only be private

c.
The overriding method must be static

d.
The overriding method must have a different name from the superclass method

e.
The overriding method must have the same signature as the method in the
superclass

Question 15
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of these is NOT a valid primitive data type?

a.
long

b.
byte

c.
double

d.
short

e.
integer

Question 16
Correct
Mark 1.00 out of 1.00
Flag question

Question text
Which statement is true about an instance variable in Java?

a.
It can be accessed from static methods without an object reference.

b.
It must be initialized before it can be used.

c.
It must always be declared as public.

d.
It is shared among all instances of a class.

e.
It is automatically initialized to null for non-object types.

Question 17
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the output of the following code? int[] arr = {1, 2, 3};
System.out.println(arr.length == 3 ? "Correct" : "Incorrect");

a.
Correct

b.
False

c.
Compile error

d.
True

e.
Incorrect

Question 18
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following access modifiers ensures that a class member is
accessible only within the package?

a.
protected

b.
default

c.
static

d.
public

e.
private

Question 19
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What does data abstraction in OOP allow you to do?

a.
Make code more complex

b.
Remove the need for classes

c.
Hide implementation details while showing only the necessary functionality

d.
Expose all implementation details to the user

e.
Combine all methods in one class

Question 20
Incorrect
Mark 0.00 out of 1.00

Flag question

Question text
What will the following code output?
a.
25

b.
35

c.
20

d.
30

e.
15

Question 21
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following best defines composition in Java?

a.
A class inherits methods from multiple classes

b.
A class contains only static fields and methods

c.
A relationship where a class contains instances of another class

d.
A relationship where classes are independent of each other

e.
A relationship where a class extends another class

Question 22
Correct
Mark 1.00 out of 1.00
Flag question

Question text
What is the primary use of a setter method?

a.
To delete a field.

b.
To return an object.

c.
To return the value of a field.

d.
To create a new field.

e.
To set the value of a field.

Question 23
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which method is used to find the length of a string in Java?

a.
str.getLength();

b.
str.capacity();

c.
str.size();

d.
str.len();

e.
str.length();

Question 24
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which operator is used to compare two values in Java?
a.
==

b.
>

c.
!=

d.
=

e.
<

Question 25
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of the following is a valid switch case statement for a char type?

a.
switch("A") { case 'A': break; }

b.
switch('A') { case 'A': break; }

c.
switch('A') { case 65: break; }

d.
switch('A') { case A: break; }

e.
switch(A) { case 'A': break; }

Question 26
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What will the following code output?

a.
10 5 2 0

b.
10 5 2 1

c.
10 5 3 1

d.
5210

e.
521

Question 27
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which of these is not a valid loop in Java?

a.
Switch loop

b.
While loop

c.
Do-while loop

d.
For loop

e.
For-each loop

Question 28
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What is the output of the following code? System.out.println(3 != 2 ? "Not
equal" : "Equal");

a.
True

b.
False
c.
Compile error

d.
Not equal

e.
Equal

Question 29
Correct
Mark 1.00 out of 1.00

Flag question

Question text
What will the following code print? int n = 5; System.out.println(n % 3 == 0 ?
"Divisible" : "Not Divisible");

a.
Not Divisible

b.
Compile error

c.
0

d.
5

e.
Divisible

Question 30
Correct
Mark 1.00 out of 1.00

Flag question

Question text
Which loop is used to iterate over elements in an array?

a.
While loop

b.
For-each loop

c.
Do-while loop
d.
For loop

e.
Switch loo

Test for Lecture 5: Exception Handling, JDBC, Database Connection

1. What is an exception in Java? a) A type of variable


b) An error that occurs during compilation
c) A problem that arises during program execution
d) A type of Java class
2. Which block is always executed after a try block, even if no exception occurs?
a) catch
b) throw
c) finally
d) None of the above
3. What is the purpose of the throw keyword in Java?
a) To catch an exception
b) To manually throw an exception
c) To define a method
d) To create a variable
4. What does JDBC stand for?
a) Java Database Code
b) Java Database Connectivity
c) Java Driver Connection
d) None of the above
5. What is the first step in establishing a database connection in JDBC?
a) Process the result
b) Close the connection
c) Define the connection URL
d) Execute a query
6. Which of the following manages different types of JDBC drivers?
a) Statement
b) DriverManager
c) Connection
d) SQLException
7. What is a PreparedStatement used for in JDBC?
a) To prepare SQL queries without parameters
b) To create a static database
c) To execute SQL with parameters
d) To manage database connections
8. How can you add JDBC drivers to your project in IntelliJ IDEA?
a) Through Project settings under Libraries
b) By importing java.util package
c) By using a try-catch block
d) None of the above
9. Which JDBC class is used to execute a query?
a) Statement
b) SQLException
c) DriverManager
d) None of the above
10. What type of exceptions does a PreparedStatement help prevent?
a) Arithmetic exceptions
b) SQL injection
c) ArrayIndexOutOfBounds exceptions
d) NullPointer exceptions
11. What is contained in the "java.sql" package?
a) Java Swing classes
b) JDBC API
c) Networking classes
d) File handling utilities
12. What happens if an exception is not handled in Java?
a) The program continues to run normally
b) The program terminates abnormally
c) A warning is generated
d) The exception is ignored
13. Which block is used to handle exceptions in Java?
a) try
b) catch
c) finally
d) All of the above
14. What is a connection URL in JDBC?
a) A URL used to connect to the internet
b) A URL to establish a connection with a database
c) A file path
d) None of the above
15. Which method is used to close a database connection?
a) stop()
b) endConnection()
c) close()
d) terminate()
16. What is the main advantage of using JDBC?
a) To enable networking
b) To connect Java applications to databases
c) To enhance UI design
d) None of the above
17. How are exceptions classified in Java?
a) Checked and unchecked
b) Local and global
c) Synchronous and asynchronous
d) Static and dynamic
18. What is the purpose of the DriverManager class?
a) To manage SQL exceptions
b) To load and manage database drivers
c) To create database schemas
d) To compile SQL queries
19. Which clause is used to declare exceptions in a method?
a) throws
b) catch
c) finally
d) throw
20. What is the role of a "finally" block in Java?
a) To declare exceptions
b) To contain code executed regardless of exceptions
c) To stop exception propagation
d) To handle runtime errors

Test for Lecture 6: SOLID Principles

1. What does "SOLID" stand for in object-oriented design?


a) Simple, Organized, Layered, Integrated, Design
b) Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation,
Dependency Inversion
c) Strong, Open, Lightweight, Independent, Dependable
d) None of the above
2. What is the main goal of the Single Responsibility Principle?
a) To reduce class size
b) To ensure a class has only one reason to change
c) To enforce class inheritance
d) To make classes reusable
3. The Open-Closed Principle states that classes should be:
a) Closed for extension and modification
b) Open for modification and closed for extension
c) Open for extension but closed for modification
d) None of the above
4. What issue does the Liskov Substitution Principle address?
a) Classes should be extensible
b) Derived classes must be substitutable for their base classes
c) Objects should be immutable
d) All methods must be overridden
5. Which principle focuses on creating small, specific interfaces?
a) Single Responsibility Principle
b) Interface Segregation Principle
c) Dependency Inversion Principle
d) Open-Closed Principle
6. What does "dependency inversion" mean in the context of SOLID?
a) High-level modules should depend on low-level modules
b) Modules should depend on abstractions, not concretions
c) Classes should always inherit from a superclass
d) None of the above
7. What does "high cohesion" mean in software design?
a) A module performs many unrelated tasks
b) A module is focused and performs a single task effectively
c) Modules depend heavily on each other
d) None of the above
8. Which SOLID principle helps reduce "fat" interfaces?
a) Single Responsibility Principle
b) Interface Segregation Principle
c) Dependency Inversion Principle
d) Open-Closed Principle
9. Why should classes be closed for modification according to the Open-Closed Principle?
a) To prevent bugs in unrelated parts of the application
b) To make testing easier
c) To ensure all subclasses inherit correctly
d) To simplify the structure of the application
10. What is a key benefit of following the SOLID principles?
a) Faster execution time
b) Better maintainability and extensibility
c) Reduced need for version control
d) Complete elimination of bugs

Test for Lecture 7: Language Features

1. What does the "instanceof" operator do in Java?


a) Checks if an object is of a certain type
b) Converts an object to another type
c) Compares two objects
d) None of the above
2. What is "reflection" in Java used for?
a) Debugging purposes only
b) Examining or modifying program behavior at runtime
c) Improving code readability
d) Handling database connections
3. How can you obtain a reference to a Class object in Java?
a) By calling getClass() on an object
b) By using the "class" keyword
c) Both a and b
d) None of the above
4. What is the primary purpose of Java generics?
a) To simplify method overloading
b) To enable type-safe operations
c) To replace polymorphism
d) To reduce runtime errors
5. What is a lambda expression in Java?
a) A named method
b) An anonymous method
c) A subclass of Object
d) None of the above
6. Which symbol is used in lambda expressions to separate parameters and the body?
a) ->
b) =>
c) ::
d) None of the above
7. What are default methods in interfaces?
a) Methods with static implementation
b) Methods with a predefined body
c) Methods that must be overridden
d) None of the above
8. What problem can occur when using default methods in multiple interfaces?
a) NullPointerException
b) Diamond problem
c) Compilation errors
d) None of the above
9. How are static methods in interfaces different from default methods?
a) Static methods can be overridden
b) Static methods are inherited by subclasses
c) Static methods cannot be overridden
d) Static methods cannot have a body
10. What is a benefit of using lambda expressions?
a) Simplifies code by removing unnecessary boilerplate
b) Forces strict typing
c) Eliminates runtime errors
d) All of the above

Test for Lecture 5: Exception Handling, JDBC, Database Connection

1. What is an exception in Java?


Answer: c) A problem that arises during program execution
2. Which block is always executed after a try block, even if no exception occurs?
Answer: c) finally
3. What is the purpose of the throw keyword in Java?
Answer: b) To manually throw an exception
4. What does JDBC stand for?
Answer: b) Java Database Connectivity
5. What is the first step in establishing a database connection in JDBC?
Answer: c) Define the connection URL
6. Which of the following manages different types of JDBC drivers?
Answer: b) DriverManager
7. What is a PreparedStatement used for in JDBC?
Answer: c) To execute SQL with parameters
8. How can you add JDBC drivers to your project in IntelliJ IDEA?
Answer: a) Through Project settings under Libraries
9. Which JDBC class is used to execute a query?
Answer: a) Statement
10. What type of exceptions does a PreparedStatement help prevent?
Answer: b) SQL injection
11. What is contained in the "java.sql" package?
Answer: b) JDBC API
12. What happens if an exception is not handled in Java?
Answer: b) The program terminates abnormally
13. Which block is used to handle exceptions in Java?
Answer: d) All of the above
14. What is a connection URL in JDBC?
Answer: b) A URL to establish a connection with a database
15. Which method is used to close a database connection?
Answer: c) close()
16. What is the main advantage of using JDBC?
Answer: b) To connect Java applications to databases
17. How are exceptions classified in Java?
Answer: a) Checked and unchecked
18. What is the purpose of the DriverManager class?
Answer: b) To load and manage database drivers
19. Which clause is used to declare exceptions in a method?
Answer: a) throws
20. What is the role of a "finally" block in Java?
Answer: b) To contain code executed regardless of exceptions

Test for Lecture 6: SOLID Principles

1. What does "SOLID" stand for in object-oriented design?


Answer: b) Single Responsibility, Open-Closed, Liskov Substitution, Interface
Segregation, Dependency Inversion
2. What is the main goal of the Single Responsibility Principle?
Answer: b) To ensure a class has only one reason to change
3. The Open-Closed Principle states that classes should be:
Answer: c) Open for extension but closed for modification
4. What issue does the Liskov Substitution Principle address?
Answer: b) Derived classes must be substitutable for their base classes
5. Which principle focuses on creating small, specific interfaces?
Answer: b) Interface Segregation Principle
6. What does "dependency inversion" mean in the context of SOLID?
Answer: b) Modules should depend on abstractions, not concretions
7. What does "high cohesion" mean in software design?
Answer: b) A module is focused and performs a single task effectively
8. Which SOLID principle helps reduce "fat" interfaces?
Answer: b) Interface Segregation Principle
9. Why should classes be closed for modification according to the Open-Closed
Principle?
Answer: a) To prevent bugs in unrelated parts of the application
10. What is a key benefit of following the SOLID principles?
Answer: b) Better maintainability and extensibility

Test for Lecture 7: Language Features

1. What does the "instanceof" operator do in Java?


Answer: a) Checks if an object is of a certain type
2. What is "reflection" in Java used for?
Answer: b) Examining or modifying program behavior at runtime
3. How can you obtain a reference to a Class object in Java?
Answer: c) Both a and b
4. What is the primary purpose of Java generics?
Answer: b) To enable type-safe operations
5. What is a lambda expression in Java?
Answer: b) An anonymous method
6. Which symbol is used in lambda expressions to separate parameters and the body?
Answer: a) ->
7. What are default methods in interfaces?
Answer: b) Methods with a predefined body
8. What problem can occur when using default methods in multiple interfaces?
Answer: b) Diamond problem
9. How are static methods in interfaces different from default methods?
Answer: c) Static methods cannot be overridden
10. What is a benefit of using lambda expressions?
Answer: a) Simplifies code by removing unnecessary boilerplate
Тест по Лекции 5: Обработка Исключений, JDBC, Подключение к Базе
Данных

1. Что такое исключение в Java?


Ответ: c) Проблема, возникающая во время выполнения программы
2. Какой блок всегда выполняется после блока try, даже если исключение не
возникает?
Ответ: c) finally
3. Какова цель ключевого слова throw в Java?
Ответ: b) Для ручного выброса исключения
4. Что означает аббревиатура JDBC?
Ответ: b) Java Database Connectivity
5. Каков первый шаг при установлении подключения к базе данных в JDBC?
Ответ: c) Определить URL подключения
6. Что управляет различными типами драйверов JDBC?
Ответ: b) DriverManager
7. Для чего используется PreparedStatement в JDBC?
Ответ: c) Для выполнения SQL с параметрами
8. Как можно добавить драйверы JDBC в проект IntelliJ IDEA?
Ответ: a) Через настройки проекта в разделе Libraries
9. Какой класс JDBC используется для выполнения запроса?
Ответ: a) Statement
10. Какие типы исключений помогает предотвратить PreparedStatement?
Ответ: b) SQL-инъекции
11. Что содержится в пакете "java.sql"?
Ответ: b) API JDBC
12. Что произойдет, если исключение не обработать в Java?
Ответ: b) Программа завершится ненормально
13. Какой блок используется для обработки исключений в Java?
Ответ: d) Все вышеперечисленные
14. Что такое URL подключения в JDBC?
Ответ: b) URL для подключения к базе данных
15. Какой метод используется для закрытия подключения к базе данных?
Ответ: c) close()
16. Каково основное преимущество использования JDBC?
Ответ: b) Подключение Java приложений к базам данных
17. Как классифицируются исключения в Java?
Ответ: a) Проверяемые и непроверяемые
18. Какова цель класса DriverManager?
Ответ: b) Для загрузки и управления драйверами базы данных
19. Какая конструкция используется для объявления исключений в методе?
Ответ: a) throws
20. Какова роль блока "finally" в Java?
Ответ: b) Содержит код, который выполняется независимо от исключений

Тест по Лекции 6: Принципы SOLID

1. Что означает "SOLID" в объектно-ориентированном дизайне?


Ответ: b) Single Responsibility, Open-Closed, Liskov Substitution, Interface
Segregation, Dependency Inversion
2. Какова основная цель Принципа Единственной Ответственности (SRP)?
Ответ: b) Обеспечить, чтобы у класса была только одна причина для изменения
3. Принцип Открытости-Закрытости (OCP) утверждает, что классы должны
быть:
Ответ: c) Открыты для расширения, но закрыты для модификации
4. Какую проблему решает Принцип Подстановки Лисков (LSP)?
Ответ: b) Производные классы должны быть взаимозаменяемы с их базовыми
классами
5. Какой принцип направлен на создание мелких, специфических интерфейсов?
Ответ: b) Принцип Разделения Интерфейсов (ISP)
6. Что означает "инверсия зависимости" в контексте SOLID?
Ответ: b) Модули должны зависеть от абстракций, а не от конкретных реализаций
7. Что означает "высокая связность" в проектировании программного
обеспечения?
Ответ: b) Модуль сфокусирован и эффективно выполняет одну задачу
8. Какой принцип SOLID помогает уменьшить "жирные" интерфейсы?
Ответ: b) Принцип Разделения Интерфейсов (ISP)
9. Почему классы должны быть закрыты для модификации согласно Принципу
Открытости-Закрытости?
Ответ: a) Чтобы предотвратить ошибки в несвязанных частях приложения
10. Какое ключевое преимущество следования принципам SOLID?
Ответ: b) Лучшая поддерживаемость и расширяемость

Тест по Лекции 7: Особенности Языка

1. Что делает оператор "instanceof" в Java?


Ответ: a) Проверяет, является ли объект определенного типа
2. Для чего используется "reflection" в Java?
Ответ: b) Для изучения или изменения поведения программы во время выполнения
3. Как можно получить ссылку на объект класса (Class) в Java?
Ответ: c) И a), и b)
4. Какова основная цель дженериков в Java?
Ответ: b) Обеспечение операций с безопасностью типов
5. Что такое лямбда-выражение в Java?
Ответ: b) Анонимный метод
6. Какой символ используется в лямбда-выражениях для разделения параметров
и тела?
Ответ: a) ->
7. Что такое методы по умолчанию в интерфейсах?
Ответ: b) Методы с предопределенным телом
8. Какая проблема может возникнуть при использовании методов по умолчанию
в нескольких интерфейсах?
Ответ: b) Проблема ромба
9. Чем статические методы в интерфейсах отличаются от методов по
умолчанию?
Ответ: c) Статические методы не могут быть переопределены
10. Каково преимущество использования лямбда-выражений?
Ответ: a) Упрощает код, устраняя ненужные шаблоны

You might also like