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

Test Your Java Skills with Our Free Online Quiz!

Ready for the ultimate java online quiz test? Jump in and see how you score!

Difficulty: Moderate
2-5mins
Learning OutcomesCheat Sheet
Paper art illustration for online Java quiz with core questions on OOP, methods, loops on a golden yellow background.

Ready to level up your Java skills? Dive into our free java quiz and challenge yourself with core Java questions on OOP, methods, and loops. This java quiz online is perfect for students, developers, and anyone eager to sharpen their coding prowess. You'll get instant feedback to pinpoint your strengths and growth areas - your personal Java Certification Quiz guiding each step. If you're preparing for interviews or love problem-solving, our java assessment test online has you covered. Join now, take the Java programming quiz , and see your score climb as you master each concept. Ready to prove your expertise? Start the java online quiz test today and showcase your skills.

Which of the following is a primitive data type in Java?
Scanner
ArrayList
int
String
Java defines eight primitive data types such as int, boolean, char, byte, short, long, float, and double. String, ArrayList, and Scanner are reference types (classes) rather than primitives. Primitive types store raw values directly and are not objects. Oracle Java Data Types
What is the correct way to declare a Java class named MyClass?
public MyClass { }
MyClass class { }
class MyClass { }
class = MyClass { }
In Java, classes are declared using the 'class' keyword followed by the class name and braces. The correct syntax is `class MyClass { }`. Omitting the keyword or misplacing parts breaks compilation. Java Classes Tutorial
Which keyword is used to create an object in Java?
new
create
make
instance
The 'new' keyword in Java allocates memory for a new object and returns a reference to it. Other words like 'make' or 'create' have no special meaning in Java. Constructors are invoked along with 'new'. Creating Objects in Java
What is the result of the expression 5 + 3 * 2 in Java?
13
11
16
10
Java follows operator precedence; multiplication is evaluated before addition. So 3 * 2 = 6, then 5 + 6 = 11. Parentheses would be needed to change this order. Java Operators
Which loop will always execute its body at least once?
enhanced for
do-while
while
for
A do-while loop checks its condition after executing the loop body, guaranteeing at least one iteration. For, while, and enhanced for loops evaluate their conditions before the first iteration. Java Loops
Which of these is the correct signature for the main method in Java?
public void main(String[] args)
public static void main(String[] args)
static public void Main(String args)
public static int main(String[] args)
The entry point for a Java application must be `public static void main(String[] args)`. It must be public and static, return void, and accept a String array. Case sensitivity matters; `Main` or wrong return type won't run. Java Application Entry Point
How do you declare an array of integers named nums with length 5?
int[] nums = int[5];
int nums = new int[5];
int[] nums = new int[5];
int nums[] = {5};
In Java, arrays are created with `new` and a size: `new int[5]`. The variable must be an array type, `int[]`. The other options either omit new, use wrong syntax, or initialize to the wrong value. Java Arrays
Which keyword prevents a class from being subclassed?
final
abstract
static
volatile
Applying `final` to a class means it cannot be extended. `static` applies to nested classes but not to top-level classes. `abstract` forces subclassing. `volatile` relates to field visibility. Final Classes in Java
Which access modifier makes a member accessible only within its own class?
default (package-private)
private
protected
public
`private` members are accessible only within the class they are declared in. `public` allows access from anywhere, `protected` within package or subclasses, and default within the same package. Java Access Control
What is output of: System.out.println("Hello" + 5 + 3); ?
Compilation error
Hello8
Hello5 3
Hello53
String concatenation in Java is left to right; "Hello" + 5 yields "Hello5", then + 3 yields "Hello53". There is no arithmetic since the first operand is String. Java String Concatenation
Which of these is a valid if statement in Java?
if x > 0 then { ... }
if (x > 0) { ... }
if [ x > 0 ] { ... }
if (x > 0) then { ... }
Java uses parentheses around the condition and braces for the block: `if (condition) { }`. Keywords like `then` or brackets `[]` are not Java syntax. Java if-else Statements
How do you start a single-line comment in Java?
\ This is a comment
/* This is a comment
# This is a comment
// This is a comment
Java single-line comments begin with `//` and continue to the line's end. `/* ... */` is for block comments. `#` and `\` have no comment meaning. Java Comments
Which of these is the correct syntax for a while loop that runs while i is less than 10?
while i < 10 { }
loop (i < 10) { }
while (i < 10) { }
while [i < 10] { }
Java's while loop syntax requires parentheses around the condition: `while (condition) { }`. Other forms like missing parentheses or using brackets are invalid. Java Loops
What does JVM stand for?
Java Variable Method
Just Virtual Memory
Java Virtual Machine
Java Visual Manager
JVM stands for Java Virtual Machine, which executes Java bytecode on any platform. It provides platform independence by abstracting the underlying hardware. Java Virtual Machine Specification
What is method overloading in Java?
Changing the return type of a method only
A subclass redefining a superclass method
Defining multiple methods with the same name but different parameters
Using methods from an imported package
Method overloading occurs when methods share the same name but differ in parameter type, number, or order. It's resolved at compile time. Overriding is different - it's redefining methods in subclasses. Java Methods Tutorial
Which keyword indicates a method cannot be overridden by subclasses?
static
final
abstract
transient
When a method is declared `final`, subclasses cannot override it. `static` methods can't be overridden but hidden instead. `abstract` requires overriding. `transient` applies to fields. Java Final Methods
What does the instanceof operator check?
If a class implements an interface
Whether an object is an instance of a given class or interface
If two objects are equal
Whether a variable is null
The `instanceof` operator returns true if the left operand is an instance of the right operand type (class or interface). It handles inheritance hierarchies. It does not test null references. instanceof Operator
Which of these is true about abstract classes?
They cannot have member variables
They can have both abstract and concrete methods
They must implement all interface methods
They cannot have constructors
Abstract classes may contain abstract methods (without body) and concrete methods (with body). They can have constructors and fields. Interfaces differ - they are fully abstract (pre-Java 8). Abstract Classes
What is the output of System.out.println(3 + 2 * "5"); ?
7
Compilation error
35
13
You cannot multiply an int by a String in Java, so it's a compilation error. Automatic conversions do not apply to arithmetic with String. Concatenation works only with +. Operators and Conversions
Which collection allows duplicate elements and maintains insertion order?
Map
List
Queue
Set
A List in Java allows duplicates and preserves the order elements were added. A Set disallows duplicates, a Map stores key-value pairs, and Queue follows specific ordering rules. Java List Interface
What does the static keyword indicate when applied to a method?
The method cannot be overridden
The method is final
The method runs on a separate thread
The method belongs to the class rather than instances
Static methods are tied to the class itself, so they can be called without creating an object. They cannot access instance variables directly. They differ from instance methods. Static Methods
Which interface must a Java class implement to allow its instances to be sorted?
Serializable
Comparable
Iterable
Cloneable
Implementing `Comparable` and its `compareTo` method allows objects to be sorted by Collections.sort. `Serializable` is for object serialization, `Cloneable` for cloning, and `Iterable` for iteration. Comparable Interface
What is auto-boxing in Java?
Optimizing loops at runtime
Automatic converting of arrays to lists
In-lining methods during compilation
Automatic conversion between primitives and their wrapper classes
Auto-boxing converts a primitive (like int) to its wrapper class (Integer) automatically. Unboxing reverses the process. This feature was introduced in Java 5. Autoboxing Tutorial
Which exception is thrown when you divide an integer by zero in Java?
NullPointerException
IllegalArgumentException
NumberFormatException
ArithmeticException
Dividing an integer by zero results in an `ArithmeticException` at runtime. Floating-point division by zero yields Infinity or NaN instead. The other exceptions relate to different error conditions. ArithmeticException
What keyword is used to define a constant in Java?
immutable
final
const
static
Java uses the `final` keyword to mark variables whose values cannot be changed once assigned. The word `const` is reserved but not used. `static final` together defines class-level constants. Java Variables
Which collection class is synchronized by default?
HashMap
LinkedList
ArrayList
Vector
Vector and Hashtable are legacy synchronized collections. `ArrayList`, `LinkedList`, and `HashMap` are not synchronized by default. For modern concurrent use, you'd choose classes in `java.util.concurrent`. Vector Class
What is an inner class in Java?
A class without a package
A class that inherits from two classes
A class defined within another class
A class that cannot be instantiated
An inner class is a class declared within another class's body. Inner classes have access to members of the enclosing class. They help group logically related classes. Inner Classes
Which keyword ensures thread safety by allowing only one thread to access a block at a time?
volatile
transient
atomic
synchronized
The `synchronized` keyword locks an object or class so only one thread executes the block at once. `volatile` controls visibility of variables across threads. `atomic` isn't a Java keyword. Concurrency in Java
What does the volatile keyword guarantee?
Mutual exclusion
Thread pooling
Visibility of changes to variables across threads
Atomicity of operations
Marking a variable `volatile` ensures that reads and writes go directly to main memory, making the latest value visible to all threads. It does not provide atomicity or locking. Volatile Variables
Which method must you override when implementing Runnable?
run()
execute()
start()
init()
Implementing `java.lang.Runnable` requires overriding the `run()` method, which contains code executed by a thread. You do not override `start()`, which is part of Thread. Runnable Tutorial
What's the purpose of a static initialization block?
To run code before main method only
To declare static methods
To initialize instance variables
To initialize static variables when the class is loaded
A static block executes once when the class is first loaded, initializing static fields or performing setup. Instance initializers and constructors handle instance data. Static initializers run before any static methods. Class Initialization
Which API introduced lambda expressions to Java?
Java 8 Stream API
JavaFX 2.0
Java EE 6
Java 7 Concurrency API
Lambda expressions and the Stream API were introduced in Java 8 to support functional-style operations. They allow passing behavior as parameters. Earlier Java versions did not include this feature. Stream API
What does Stream.filter() do in Java Streams?
Sorts the elements
Aggregates stream elements into a list
Retains only elements matching a given Predicate
Transforms each element according to a Function
The `filter` method uses a `Predicate` to include only those elements that match the condition. It does not transform or aggregate elements. Other methods like `map` or `collect` handle those tasks. Java Streams
What is a functional interface?
An interface with a single abstract method
An interface with default methods only
An interface extending Runnable
An interface that declares static methods only
A functional interface has exactly one abstract method and may have default or static methods. It's the basis for lambda expressions. The @FunctionalInterface annotation can be used but is optional. FunctionalInterface Annotation
Which mechanism allows classes to be inspected and modified at runtime?
JDBC
JNI
Serialization API
Reflection API
Java's Reflection API (in `java.lang.reflect`) lets code examine classes, methods, fields, and instantiate objects at runtime. Serialization is for object persistence. JNI is native interface. JDBC is database connectivity. Java Reflection
What is the effect of marking a class as Serializable?
It restricts subclassing
It marks the class as immutable
It allows multiple inheritance
It enables its instances to be converted to a byte stream
Implementing `java.io.Serializable` signals that objects can be serialized and later deserialized, preserving state. It does not enforce immutability or inheritance changes. Java Serialization
Which of these best describes garbage collection in Java?
A design pattern for caching
Automatic reclamation of unused object memory
Manual deallocation of objects
Compilation-time memory optimization
Java's garbage collector automatically frees memory used by objects no longer referenced. Programmers cannot explicitly free object memory. It runs at JVM's discretion. Java Memory Management
What role do class loaders play in Java?
They enforce access control at compile time
They manage thread scheduling
They load classes into the JVM at runtime
They compile Java source code to bytecode
Class loaders dynamically load classes into the JVM during execution, supporting features like dynamic modules and custom class paths. They do not compile source code or manage threads. ClassLoader API
Which wildcard in generics allows a method to accept a collection of any subtype of Number?
List
List
List
List
`? extends Number` means any type that is Number or a subclass. `? super Number` means Number or a supertype. `List` only accepts exactly Number. Generics Wildcards
What is the Java Memory Model's happens-before relationship?
A rule for compile-time optimizations
A guarantee about visibility and ordering of memory writes and reads between threads
A garbage collection phase
A mechanism to deallocate memory
The happens-before relationship defines how actions in one thread become visible to another, ensuring a consistent view of memory in concurrent programs. It's central to Java's concurrency guarantees. Java Memory Model
Which class in java.util.concurrent provides a work-stealing thread pool?
ThreadPoolExecutor
ForkJoinPool
ExecutorService
ScheduledThreadPoolExecutor
ForkJoinPool uses a work-stealing algorithm where idle threads steal tasks from busy ones, improving parallel performance. Other executors use different scheduling. ForkJoinPool
What is annotation processing used for in Java?
Generating source code and performing compile-time checks based on annotations
Running tests on annotated methods automatically
Serializing objects annotated with @Serializable
Modifying bytecode at runtime
Annotation processors can read annotation metadata during compilation to generate code, enforce constraints, or produce documentation. They run before bytecode is created. Annotation Processing
In Java modules (JPMS), what directive exposes a package to other modules?
opens
requires
exports
provides
The `exports` directive in module-info.java makes a package accessible to other modules at compile and runtime. `requires` declares dependencies. `opens` allows reflection only at runtime. Java Module System
0
{"name":"Which of the following is a primitive data type in Java?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"Which of the following is a primitive data type in Java?, What is the correct way to declare a Java class named MyClass?, Which keyword is used to create an object in Java?","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Study Outcomes

  1. Understand OOP Fundamentals -

    Grasp the core object-oriented programming principles in Java, including classes, objects, inheritance, and polymorphism to model real-world scenarios.

  2. Apply Control Flow Constructs -

    Use loops, conditional statements, and branching logic effectively to control program execution and solve iterative problems.

  3. Analyze Method Structures -

    Break down method declarations, parameters, return types, and scope rules to compose and invoke reusable code segments.

  4. Identify Java Syntax and Data Types -

    Recognize primitive and reference data types, variable declarations, and common operators to write syntactically correct Java code.

  5. Evaluate Code Snippets for Accuracy -

    Spot errors, predict outputs, and assess best practices in given Java code examples to reinforce debugging skills.

  6. Enhance Java Problem-Solving Skills -

    Build confidence in tackling core Java challenges by testing your knowledge with real-world quiz questions and instant feedback.

Cheat Sheet

  1. Core OOP Principles -

    Java is built on four pillars - Abstraction, Polymorphism, Inheritance, and Encapsulation - remembered by the mnemonic "A PIE." Encapsulation is enforced by private fields and public getters/setters (Oracle Java Tutorials), while polymorphism shines when a superclass reference calls subclass methods at runtime. Try modeling an Animal superclass with Dog and Cat subclasses to see method overriding in action.

  2. Primitive vs Reference Types -

    Java's eight primitive types (like int, double, boolean) store raw values, whereas reference types (classes, arrays) point to objects in the heap (Java Language Specification). Remember "primitive = value, reference = address" to avoid NullPointerExceptions when accessing object methods. For example, int x = 10 stores 10 directly, while String s = "Hi" stores a pointer to its character array.

  3. Control Flow & Loop Constructs -

    Master for, while, and do-while loops to handle repetitive tasks, and use enhanced for-loops when iterating collections (Oracle Java Tutorials). For instance, for(int i = 0; i < 5; i++) prints numbers 0 - 4, while a do-while loop guarantees at least one execution. Employ break and continue strategically to manage flow without deeply nested conditions.

  4. Methods, Overloading & Recursion -

    Understand how methods encapsulate behavior: overload methods by changing parameter lists but not return types, and use recursion for divide-and-conquer problems (e.g., factorial calculation). Static methods belong to the class, while instance methods require an object instance to invoke. A common tip is "same name, different game" to recall overloading rules.

  5. Exception Handling Patterns -

    Java separates checked exceptions (must be declared or caught) from unchecked ones (RuntimeException and its subclasses) in the Java Language Specification. Wrap risky code in try-catch-finally blocks to maintain control flow and resource cleanup - e.g., try parsing Integer.parseInt("abc") and catch NumberFormatException. Finally blocks execute regardless of exceptions, ensuring critical cleanup like closing streams.

Powered by: Quiz Maker