Unlock hundreds more features
Save your Quiz to the Dashboard
View and Export Results
Use AI to Create Quizzes and Analyse Results

Sign inSign in with Facebook
Sign inSign in with Google

Java Fundamentals Quiz: Test Your Basics

Sharpen Your Core Java Skills with Quiz

Difficulty: Moderate
Questions: 20
Learning OutcomesStudy Material
Colorful paper art displaying a trivia quiz on Java Fundamentals.

Ready to assess your Java fundamentals? This practice quiz covers core Java concepts and is perfect for students and aspiring developers seeking a quick self-check. Jump into the Java Programming Fundamentals Quiz or the Java Developer Assessment Quiz to deepen your understanding. Each question can be freely customized in our editor, so you can tailor the quiz to your learning needs. Explore more quizzes and sharpen your coding skills today.

Which of the following is NOT a primitive type in Java?
int
boolean
String
double
In Java, primitive types are built-in types like int, boolean, and double. String is a class in the java.lang package and not a primitive type.
What is the default value of an uninitialized boolean field in a Java class?
0
null
false
true
Instance fields of primitive types receive default values if not initialized explicitly. For boolean, the default value is false in Java classes.
How many times will the loop body execute? for(int i = 0; i < 5; i++) { /* body */ }
Infinite times
4
6
5
The loop starts with i = 0 and continues while i < 5, incrementing i by 1 each time. This results in five iterations with i values of 0 through 4.
Which of the following correctly declares an array of integers with length 5?
int arr = new int[5];
int[] arr = new int();
int[] arr = new int[5];
int arr[] = new int{5};
int[] arr = new int[5] correctly declares an array of integers with length 5. The brackets indicate array type and the new operator allocates space for five elements.
What is the output of this Java statement? System.out.println(5 + "5");
Compile-time error
10
55
105
When an int is concatenated with a string, Java converts the int to a string before concatenation. Therefore, 5 + "5" produces the string "55".
What keyword is used in Java to inherit from a superclass?
extends
super
this
implements
The extends keyword is used in Java to create a subclass that inherits from a superclass. It indicates that one class derives from another, inheriting its fields and methods.
Which definition best describes method overloading in Java?
Same method name with the same parameter list in a subclass
Different method name with the same parameters
Same return type with a different method name
Same method name with different parameter lists in the same class
Method overloading occurs when multiple methods in the same class share the same name but have different parameter lists. The compiler distinguishes them based on the number or types of parameters.
What will be printed by the following code? try { throw new Exception("Err"); } catch(Exception e) { System.out.print("Caught"); } finally { System.out.print("Done"); }
CaughtDone
Runtime error
ErrDone
DoneCaught
The throw statement raises an Exception which is immediately caught by the catch block, printing "Caught". After the catch block executes, the finally block always runs and prints "Done".
Which Java Collection allows duplicate elements and preserves insertion order?
List
Map
Set
Queue
A List in Java allows duplicate elements and preserves the order in which elements are added. Other collections like Set disallow duplicates or Map store key-value pairs.
Which code correctly iterates over a List named items using an Iterator?
for (String s : items) { /* ... */ }
Iterator it = items.iterator(); while(it.hasNext()){ String s = it.next(); }
for (int i = 0; i < items.size(); i++) { /* ... */ }
Iterator it = items.iterator(); while(it.hasNext()){ Object o = it.next(); }
Using Iterator ensures type safety when retrieving elements from a List. The iterator() method returns an Iterator whose next() method returns String instances safely.
Which statement about String immutability in Java is true?
Strings can be changed via charAt
Calling replace returns a new String instance
Strings are stored on the heap and can be mutated
Calling replace on a String modifies the original instance
Strings in Java are immutable, so methods like replace do not change the original string instance. Instead, they return a new String object containing the modified content.
What does the "throws IOException" clause in a method signature indicate?
IOException is unchecked so no need to catch
It suppresses the exception at compile time
The method handles IOException internally
Callers must handle or declare the exception
A throws clause in the method signature declares that the method may throw a checked exception like IOException. Any caller of this method must either catch the exception or declare it in its own throws clause.
Which statement correctly describes differences between abstract classes and interfaces in Java?
Abstract classes support multiple inheritance but interfaces do not
An interface can have instance fields while an abstract class cannot
Abstract classes can have constructors and state but interfaces cannot hold instance state
Interfaces can contain private methods but abstract classes cannot
Abstract classes in Java can define constructors and maintain instance state through fields. Interfaces, on the other hand, cannot hold instance state and are meant to declare method signatures only.
Which Map implementation preserves insertion order of its entries?
Hashtable
HashMap
LinkedHashMap
TreeMap
LinkedHashMap maintains a doubly-linked list of its entries, preserving the order in which keys were inserted. Other Map implementations like HashMap do not guarantee insertion order.
Which exception is thrown when an integer division by zero occurs in Java?
ArithmeticException
NumberFormatException
NullPointerException
IllegalArgumentException
Dividing an integer by zero at runtime in Java causes the JVM to throw an ArithmeticException. This is a subclass of RuntimeException and indicates an illegal arithmetic operation.
Which of the following correctly uses try-with-resources to auto-close a BufferedReader?
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { /* use br */ } catch (IOException e) { }
BufferedReader br = new BufferedReader(new FileReader("file.txt")); br.close();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))); { /* use br */ }
try { BufferedReader br = new BufferedReader(new FileReader("file.txt")); /* use br */ } catch (IOException e) { }
Try-with-resources requires that the resource be declared within parentheses immediately after the try keyword. The resource must implement AutoCloseable, and it is automatically closed at the end of the try block.
What is true about a List in Java?
You can add Integer elements to it safely
You can add any type of Number to it
You can only read elements as Number or its supertypes
It is equivalent to List
A List is a list of some unknown subtype of Number and acts as a producer of Number instances. You cannot add specific subtypes because of type safety restrictions, but reading returns Number.
Which rule applies to varargs (variable-length argument lists) in a Java method signature?
Varargs parameter must be the last parameter in the method signature
Varargs parameter must be the first in the list
A method can have multiple varargs parameters
Varargs and array parameters cannot coexist
Java requires the varargs parameter to be the last in the method signature so that the compiler can correctly bundle the remaining arguments into an array. Only one varargs parameter is permitted per method.
Given the following code, what is the output? Map> map = new HashMap<>(); map.computeIfAbsent("key", k -> new ArrayList<>()).add("value"); System.out.println(map.get("key").size());
0
1
null
Compilation error
computeIfAbsent checks if the key is present; if not, it uses the provided function to create a new ArrayList for that key. Then add("value") inserts into the new list, making its size 1.
Which of the following Stream operations is a terminal operation?
peek(System.out::println)
filter(x -> x > 0)
map(x -> x * 2)
forEach(System.out::println)
forEach is a terminal operation that triggers the evaluation of the stream pipeline and consumes the elements. Intermediate operations like filter, map, and peek return a new stream and do not execute until a terminal operation is invoked.
0
{"name":"Which of the following is NOT a primitive type in Java?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"Which of the following is NOT a primitive type in Java?, What is the default value of an uninitialized boolean field in a Java class?, How many times will the loop body execute? for(int i = 0; i < 5; i++) { \/* body *\/ }","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Learning Outcomes

  1. Identify core Java data types and variables
  2. Demonstrate understanding of control structures and loops
  3. Apply object-oriented principles in Java scenarios
  4. Analyse method signatures and parameter usage
  5. Evaluate exception handling strategies in Java applications
  6. Master use of Java collections and basic APIs

Cheat Sheet

  1. Understand Java's Primitive Data Types - Java has eight primitive building blocks (byte, short, int, long, float, double, char, boolean) each with its own size and range. Choosing the right type keeps your code efficient and bug-free - no need to overkill with a double when an int will do! Dive into the essentials here: Primitive Data Types
  2. Master Variable Declaration and Initialization - Declaring and initializing variables is like giving your program the ingredients it needs before cooking up results. Whether you split it into two steps ('int age;' then 'age = 25;') or combine them ('int age = 25;'), starting with the right values saves you from pesky runtime errors. Stir up your coding skills here: Variables Tutorial
  3. Grasp Control Structures: if, else, and switch - Control structures let your code make decisions and take different paths like a choose-your-own-adventure. 'if' and 'else' handle simple tests, while 'switch' shines when you have many branches to juggle. Navigate the flow of your program here: Control Flow Statements
  4. Learn Loop Constructs: for, while, and do-while - Loops let you repeat actions until a goal is met, so you can focus on the fun stuff instead of writing the same code over and over. Use 'for' when you know how many iterations you need, or 'while' and 'do-while' when the end condition depends on real-time data. Get looping: Loops Tutorial
  5. Embrace Object-Oriented Principles: Classes and Objects - Objects are LEGO bricks in Java, and classes are the blueprints that define them - build cars, games, or anything you imagine by snapping data and methods together. Understanding how to encapsulate properties and behaviors in classes is key to creating clean, reusable code. Start constructing here: Classes and Objects
  6. Analyze Method Signatures and Parameters - A method signature (name and parameter list) tells Java how to call your code, like 'public int add(int a, int b)' defining an adder that returns a sum. Passing the right parameters keeps your methods flexible and reusable, so you can crank out neat code blocks without rewriting logic. Peek under the hood here: Defining Methods
  7. Evaluate Exception Handling Strategies - Exceptions are Java's way of waving a flag when things go off-track, and 'try', 'catch', and 'finally' blocks help you tame these unexpected events without crashing your program. By handling errors like 'FileNotFoundException', your code can recover gracefully or alert users in style. Catch the details here: Exception Handling
  8. Utilize Java Collections Framework - Collections turn static arrays into dynamic teams - ArrayList, HashSet, HashMap, and more let you store, search, and organize data with ease. Whether you need a resizable list, a unique-item set, or a key-value map, the Java Collections Framework has your back. Explore the toolbox here: Collections Framework
  9. Explore Basic Java APIs - Java's built-in APIs are like superpowers for everyday tasks - 'java.util' for tools, 'java.io' for input/output, and much more so you don't have to reinvent the wheel. From scanning user input with Scanner to formatting dates with DateTimeFormatter, these libraries make your life easier. Unlock the power: Java Packages Overview
  10. Practice Writing and Debugging Java Code - The more you code, the more confident you become - build small programs, tackle challenges, and squish bugs using your IDE's debug tools. Each error you fix is a lesson learned, and every feature you add is a win. Ready, set, code! Check out exercises here: Getting Started
Powered by: Quiz Maker