0% found this document useful (0 votes)
75 views6 pages

Java MCQs for Beginners

The document contains a series of multiple-choice questions (MCQs) related to Java programming, covering topics such as variable declarations, data types, Swing components, exception handling, and multithreading. Each question is followed by the correct answer, providing a quick reference for Java concepts. This resource is useful for individuals preparing for Java-related assessments or enhancing their knowledge of the language.
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)
75 views6 pages

Java MCQs for Beginners

The document contains a series of multiple-choice questions (MCQs) related to Java programming, covering topics such as variable declarations, data types, Swing components, exception handling, and multithreading. Each question is followed by the correct answer, providing a quick reference for Java concepts. This resource is useful for individuals preparing for Java-related assessments or enhancing their knowledge of the language.
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

Java Multiple Choice Questions (MCQs)

1. Which of the following is a valid variable declaration in Java?

Answer: b) float myFloat = 5.6;

2. Which data type is used to store a single character in Java?

Answer: a) char

3. How many bytes does an int data type occupy in Java?

Answer: c) 4

4. Which of the following is the correct way to declare multiple variables of the same type?

Answer: d) All of the above

5. Which keyword in Java is used for constant variables?

Answer: d) final

6. What will be the default value of an int variable if not initialized in a class?

Answer: b) 0

7. Which of the following is a valid variable name in Java?

Answer: c) my_var

8. The boolean data type in Java can have values:

Answer: b) true and false

9. Which data type can be used to store large decimal numbers in Java?

Answer: c) double

10. Output of the program with post-increment:

Answer: a) 10

11. Output of x % y where x=5, y=2:

Answer: c) 1

12. Boolean OR operation (true || false):

Answer: a) true

13. Conditional operator with x=7, y=3:

Answer: a) x is greater
14. What is an Array in Java?

Answer: b) A collection of elements with the same type

15. What is the index range for an array?

Answer: a) 0 to length 1

16. What does GUI stand for?

Answer: a) Graphical User Interface

17. Which package contains Java Swing classes?

Answer: d) [Link]

18. Base class for all Swing components?

Answer: b) Container

19. Default layout manager for JFrame?

Answer: a) BorderLayout

20. Class used to create a button in Java Swing?

Answer: a) JButton

21. Event listener for button clicks?

Answer: a) ActionListener

22. Purpose of setVisible() method?

Answer: c) To make the frame visible on the screen

23. Method used to add components in Swing?

Answer: a) add()

24. Purpose of setLayout() method?

Answer: c) To set the layout manager for a container

25. Layout manager for grid structure?

Answer: c) GridLayout

26. Purpose of repaint() method?

Answer: d) To redraw a component on the screen

27. Class to display text?


Answer: c) JLabel

28. Listener for keyboard events?

Answer: d) KeyListener

29. Purpose of setResizable() method?

Answer: c) To make the frame resizable or non-resizable

30. Class to display images?

Answer: b) JLabel

31. Method to set text of JTextField?

Answer: a) setText()

32. Purpose of setDefaultCloseOperation()?

Answer: c) To specify the default close operation for the frame

33. Class to display list of selectable items?

Answer: d) JList

34. Listener for mouse events?

Answer: c) MouseListener

35. Purpose of setEnabled() method?

Answer: b) To enable or disable user interaction with a component

36. Class for dropdown list?

Answer: d) JComboBox

37. Listener for JComboBox selection?

Answer: b) ItemListener

38. Purpose of setToolTipText()?

Answer: c) To specify a tooltip text for a component

39. Class for tabbed panes?

Answer: a) JTabbedPane

40. Purpose of setIcon() method?

Answer: c) To specify an image icon for a component


42. Output of box volume program?

Answer: b) 150

43. Output of array output program?

Answer: a) 0 2 4 6 8

44. Output of multidimensional array program?

Answer: a) 11

45. Keyword for abstract class?

Answer: b) abstract

46. Which is not abstract?

Answer: a) Thread

47. Package that contains abstract keyword?

Answer: a) [Link]

48. When do Exceptions arise?

Answer: a) Run Time

49. Not a part of exception handling?

Answer: c) thrown

50. Superclass of all classes?

Answer: b) Object class

51. Method to clone object?

Answer: d) clone()

52. Class depending on subclasses?

Answer: b) abstract class

53. Type of args in main method?

Answer: c) args is an array of String

54. Class for parsing command line args?

Answer: b) JCommander

55. Not a memory segment?


Answer: d) Register Segment

57. Does Code Segment load Java code?

Answer: a) True

58. What is JVM?

Answer: b) Interpreter

59. Which is a class loader?

Answer: a) Bootstrap

60. Class loader loading JDK jars?

Answer: a) Bootstrap

61. Not a Java memory classification?

Answer: d) Temporary

62. Java 8 update of PermGen?

Answer: c) Metaspace

63. Classes and Methods stored in?

Answer: d) Permanent space

64. String Pool is stored in?

Answer: d) Metaspace

65. Can import be used twice?

Answer: a) True

66. Keyword for throwing exception?

Answer: c) throw

67. Class catching uncaught exceptions?

Answer: b) Error

68. Superclass of all exceptions?

Answer: d) Throwable

69. Method to get thread priority?

Answer: c) getPriority()
70. Method to suspend thread?

Answer: a) sleep()

71. Method to check if thread is alive?

Answer: a) isAlive()

72. Output of multithreaded program?

Answer: d) Thread[New Thread,5,main]

73. Thread name in program output?

Answer: c) New Thread

74. isAlive() method output?

Answer: c) true

75. JDBC connection pool advantage?

Answer: d) Better performance

Common questions

Powered by AI

A JDBC connection pool in Java manages a pool of database connections that can be reused across client requests, thus reducing the overhead of creating and destroying connections. Instead of opening and closing connections multiple times, which is both resource-intensive and time-consuming, the connection pool holds open a set number of connections and provides them to the requesting client when needed. This reuse of connections drastically cuts down on the time it takes to establish a connection during a transaction, leading to better performance, reduced latency, and improved resource utilization. Connection pools are particularly beneficial for applications with high transaction volumes, as they enable more efficient management of database connection resources.

The 'boolean' data type in Java is distinct from other primitive data types because it can only hold two values: true and false. This makes it ideal for use in conditional statements such as if-else, loops, and logical operations, helping control the flow of a program based on certain conditions. While other data types such as int or double represent numeric values, 'boolean' is primarily used for decision-making processes and evaluating logical conditions.

The 'getPriority()' method in Java is a part of the Thread class that returns the priority of a thread, which can be adjusted using the 'setPriority()' method. Thread priorities are integers ranging from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) being the default priority assigned to threads. The priority level of a thread can influence thread scheduling, as higher priority threads are generally granted more CPU time compared to lower priority threads. However, the impact of thread priority is implementation-dependent and varies across JVMs, as the scheduling algorithms used by the underlying operating system or JVM might treat priorities differently. Thus, while priority can serve as an input in scheduling decisions, it should not be relied upon solely to control execution order where precise timing requirements are critical. Proper synchronization and thread management mechanisms should be employed alongside priority settings to regulate thread interactions effectively.

Class loaders in Java are integral to security and efficient resource management within the JVM. They are responsible for loading classes into memory when needed, ensuring that classes are only loaded once, which helps optimize resource utilization. Since different class loaders can be employed at various levels (such as the bootstrap class loader for core libraries and custom class loaders for applications), it’s possible to isolate different parts of an application or even multiple applications running within the same JVM, enhancing security by enforcing access restrictions. Moreover, class loaders verify classes with the ByteCode Verifier before loading, ensuring that imported code adheres to the Java language's safety and access control features. This layered and controlled class loading mechanism not only prevents unauthorized access but also mitigates issues such as class conflicts or memory bloat due to redundantly loaded classes.

The 'final' keyword in Java is used to declare constants. When applied to a variable, it ensures that the variable cannot be reassigned once initialized. This means that the variable's value is fixed, and any attempt to change it will result in a compile-time error. This is crucial when you need a constant value that should not change throughout the execution of an application. In Java, constants are usually declared as 'final' variables in capital letters to differentiate them from regular variables.

Java's String Pool is a special storage area in memory (prior to Java 8 it was part of the Permanent Generation; from Java 8 onwards, it is part of the Metaspace) that stores a single instance of unique String literals. When a String literal is created, the JVM checks the String Pool to see if the literal already exists. If it does, the reference to the String is returned instead of allocating new memory, which saves memory and increases performance when dealing with many identical String objects. The trade-off, however, involves the initial computational cost of checking the String Pool. Additionally, in memory-constrained environments, the pooled Strings can contribute to memory pressure, requiring careful application design to avoid too many Strings being retained unnecessarily.

The transition from PermGen to Metaspace in Java 8 introduces significant changes to Java's memory management. PermGen was a fixed-size memory area that stored the metadata of classes, which led to issues such as OutOfMemoryError when new classes could no longer be loaded due to memory restrictions. In contrast, Metaspace is dynamically resized and is housed within native memory, not the heap, thus relieving the JVM from static memory constraints tied to PermGen. This change allows applications to load more classes without hitting a predetermined limit, potentially improving performance and stability, especially for applications running numerous dynamically loaded classes. However, because Metaspace grows as needed, improperly sized Metaspace or unchecked growth can lead to consumption of all available native memory, requiring careful tuning and monitoring.

In Java, multidimensional arrays are essentially arrays of arrays. Each dimension of a multidimensional array can be thought of as an array, where the first index specifies the array within the outer array, the second index specifies the array within that inner array, and so on. The index ranges for any array, including multidimensional arrays, start at 0 and end at the array's length minus one. Therefore, for a two-dimensional array, 'array[i][j]', 'i' must be within the bounds of the outer array's length, and 'j' must be within the bounds of the inner array's length. This structure allows for complex data representation and manipulation.

The 'throw' keyword in Java is crucial for exception handling as it enables the program to explicitly generate an exception, allowing control to move from the point of error to an exception handler (try-catch block). This keyword is used when a method has detected an issue it cannot handle itself and wants a calling method to deal with the exception. By using 'throw', a method can propagate the issue to an appropriate layer or object handling procedure, maintaining clear separation of concerns. It facilitates robust error processing by letting developers define precise and context-specific reactions to exceptional conditions, contributing to a program's resilience and reliability.

Abstract classes and interfaces serve different purposes in Java. An abstract class allows you to define methods that must be implemented by subclasses while also providing implemented methods that can be shared among subclasses. This makes abstract classes suitable for a hierarchical relationship where subclasses share a common behavior. However, it limits classes to not extending more than one abstract class due to Java's single inheritance model. In contrast, interfaces are purely a contract that defines methods that implementing classes must include. Interfaces support multiple inheritance, allowing a class to implement multiple interfaces, thereby promoting a form of polymorphism not possible with abstract classes. However, interfaces lack the ability to provide shared code (except through default methods added in Java 8), which abstract classes can provide. Each has its strengths and uses depending on the specific requirement of flexibility versus shared functionality.

You might also like