0% found this document useful (0 votes)
3 views17 pages

Java Study Guide

The document is a comprehensive study guide for Java Core Programming, covering fundamental concepts, features, and components of the Java programming language. It includes detailed explanations of Java's architecture, variable types, data types, typecasting, operators, control flow structures, and more. The guide is structured as a question and answer format to facilitate concept mastery and technical examination preparation.

Uploaded by

Bikash Sharma
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)
3 views17 pages

Java Study Guide

The document is a comprehensive study guide for Java Core Programming, covering fundamental concepts, features, and components of the Java programming language. It includes detailed explanations of Java's architecture, variable types, data types, typecasting, operators, control flow structures, and more. The guide is structured as a question and answer format to facilitate concept mastery and technical examination preparation.

Uploaded by

Bikash Sharma
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

ACADEMIC STUDY REFERENCE

Java Core Programming


Complete Logical & Technical Handbook

Compiled Comprehensive Question & Answer Guide


Optimized for Concept Mastery & Technical Examination
Preparation

Java Core Programming Study Guide 1


Part 1: Java Fundamentals & Architecture

Q1. Define Java?

Java is a high-level, class-based, object-oriented, general-purpose programming language designed to have


minimal implementation dependencies. It was created with a fundamental guiding philosophy: "Write Once,
Run Anywhere" (WORA). This means that once compiled Java code runs on any platform supporting Java
without requiring recompilation. Architecturally, Java code is compiled down into an intermediate form known
as bytecode, which is then executed and interpreted by a runtime engine called the Java Virtual Machine
(JVM).

Q2. Why do most companies or industries use Java? / Features of Java.

Java remains an industry standard across global enterprise systems, cloud platforms, and mobile
development due to its well-balanced architectural features:

• Object-Oriented (OOP): Everything in Java represents an Object, encapsulating both data state and
behavior. This enforces modular programming structures, clean code reuse, and seamless scalability
across large corporate codebases.

• Platform Independence: Corporate infrastructure often spans mixed environments (Windows developers,
Linux production servers, Mac cloud pipelines). Java executes across all environments natively via
bytecode portability.

• Memory Safety & Robustness: Java eliminates developer-controlled manual pointers, preventing
catastrophic memory management bugs. It features automated runtime error safety through exception
handling and background Garbage Collection.

• Security: Applications execute within a specialized restricted sandbox runtime environment. A built-in
bytecode verifier acts as a protective shield to check code patterns for malicious execution paths before
deployment.

• Multithreading & Concurrency: Java features advanced built-in native support for concurrent execution
tracks, letting high-demand enterprise web applications handle thousands of concurrent transactions
simultaneously.

Q3. What happens when we compile without a main method?

A Java program will compile successfully without a main method. The primary job of the Java compiler
(javac) is purely structural and analytical: it ensures source code adheres perfectly to syntax rules, performs
semantic static validation, and generates structural bytecode. It does not enforce structural entry execution
pathways.

However, the software will throw a severe Runtime Error at the execution layer (NoSuchMethodError:
main) when you attempt to execute it. This happens because the Java Virtual Machine requires a strictly

Java Core Programming Study Guide 2


specified entry point method profile (public static void main(String[] args)) to initiate thread
execution sequences.

Q4. Explain how Java is Platform Independent / What is WORA Architecture?

Java achieves its unique platform independence (Write Once, Run Anywhere) by decoupling compilation from
underlying target hardware instruction sets via an abstract runtime execution layout.

JVM for Windows

Windows OS

→ JVM for Linux


Java Source Code Java Bytecode
(.java file) (.class file)

Compiler
Linux OS
(javac)

JVM for macOS

macOS

When you run code, the source layout transitions through a structured multi-stage compilation flow:

1. The human-authored .java file is parsed by the javac compiler.

2. The compiler generates intermediate .class files containing highly optimized Bytecode, completely
separate from underlying processor design constraints.

3. Target environments run custom ecosystem implementations of the Java Virtual Machine (JVM) tailored
specifically to native platform parameters.

4. The internal JVM platform architecture loads the neutral bytecode, translating instructions on-the-fly into
specific local machine code instructions.

Q5. When is the .class file generated?

The .class file is explicitly generated during the Compilation Phase. It represents the successful
completion of static analysis checks. This file generation is triggered manually or through automated build
tools when executing the shell tool command:

Java Core Programming Study Guide 3


javac [Link]

Q6. What is the job of the compiler?

The Java compiler (javac) acts as a high-performance translation firewall. Its primary technical core duties
include:

• Syntax Verification: Evaluates structural source code against language specifications.

• Semantic Type Checking: Ensures type safety constraints are strictly respected during assignments.

• Optimizations: Enhances static expressions, constant fold parameters, and transforms programmatic
code trees into lean bytecode structures.

Q7. What is bytecode?

Bytecode is a highly optimized, intermediate instruction set architecture designed by Java engineers to act as
an abstract machine language. It consists of compact 1-byte operational codes (opcodes) followed by their
arguments. It cannot execute natively on structural physical hardware; instead, it is interpreted by the virtual
processor registers inside the JVM.

Q8. What is an Interpreter?

An interpreter is a runtime subsystem component that evaluates and processes program instructions
sequentially line-by-line. In Java, the interpreter embedded within the JVM processes neutral bytecode
streams, instantly converting them into native hardware instruction calls at runtime. This provides immediate
program initialization before performance-critical segments are optimized by the Just-In-Time (JIT) compiler.

Q9. What is JDK, JRE, and JVM?

These three subsystems form the core pillars of the Java runtime layout. They expand incrementally in scope:

• JVM (Java Virtual Machine): The core execution engine. It loads, verifies, interprets, and executes
intermediate bytecode instructions on top of native OS hardware resources.

• JRE (Java Runtime Environment): The deployment platform layer. It bundles the engine infrastructure
(JVM) with core Java platform base libraries, asset classes, and system dependencies required to run
compiled applications.

• JDK (Java Development Kit): The comprehensive workspace toolset. It includes the execution and
runtime layers (JRE) and adds development tools like compilation tools (javac), debug systems (jdb),
and documentation managers (javadoc) needed to build new software from scratch.

JRE = JVM + Core Class Libraries

JDK = JRE + Development Engineering Tools (javac, jdb, etc.)

Java Core Programming Study Guide 4


Part 2: Variables, Datatypes, & Memory Layout

Q10. What is a variable?

A variable is a fundamentally named memory location allocation slice in physical RAM managed by the
execution layer. It serves as a container storage cell for holding data values during the lifecycle execution of
an active application thread. Each named allocation maps directly to an offset address pointer with explicit
size limits defined by its type constraint.

Q11. What is a datatype?

A datatype is an analytical validation mask that tells the system compiler exactly how much physical memory
space to allocate for a specific variable block. It defines the allowed data range, byte allocations, and
structural operation limits for individual fields.

Q12. What are the default values of all primitive datatypes?

Java automatically applies standard default values to instance-level fields and static class variables if they
aren't explicitly assigned values during declaration. Local variables inside methods do not receive default
values and require explicit initialization before use.

Java Core Programming Study Guide 5


Datatype Primitive Physical Memory Default Initial Value Representable Value
Category Type Size Allocation Assignment Bound Range

byte 1 Byte (8 bits) 0 -128 to 127

short 2 Bytes (16 bits) 0 -32,768 to 32,767


Integer
Values
int 4 Bytes (32 bits) 0 -231 to 231-1

long 8 Bytes (64 bits) 0L -263 to 263-1

Single-precision IEEE
float 4 Bytes (32 bits) 0.0f
754
Floating
Decimal
Double-precision IEEE
double 8 Bytes (64 bits) 0.0d
754

Unsigned Unicode
Textual/Char char 2 Bytes (16 bits) '' (Null Character)
standard bounds

Logical Literal sets: [true,


boolean Virtual Bit Model false
Condition false]

Q13. Difference between Global and Local Variable.

Variables are classified into different categories based on their declaration scope and retention lifecycle:

Java Core Programming Study Guide 6


Comparison Global Variables (Instance / Static
Local Variables (Method Block Scope)
Parameter Scope)

Inside a class block context body, Directly within structural method code
Declaration
completely outside any specific functional definitions, parameter lists, or scoped
Context
method or structural constructor block. local loops.

Stored inside Heap memory spaces (for


Allocation Allocated inside isolated, short-lived
instance fields) or MetaSpace storage
Memory Area Stack Frame execution sectors.
regions (for static contexts).

Accessible across the class based on Highly restricted. Accessible only within
Thread Visibility
access rules. Static variants are shared the local method block where it is
Range
universally across instances. defined.

Automatically receives system-defined No default initialization. Any attempt to


Default Value
default assignments (e.g., 0, false, null) use an uninitialized local variable triggers
Initialization
upon instance creation. a compilation error.

Created when the object instantiates or the Instantiated dynamically when execution
Lifecycle
class loads; persists until reclaimed by enters the enclosing block and destroyed
Duration
Garbage Collection. when control exits the block.

Java Core Programming Study Guide 7


Part 3: Typecasting, Logic, & Mathematical Operators

Q14. What is typecasting & explain Primitive Typecasting?

Typecasting is an explicit or implicit data transformation pipeline that converts a variable from one specific
datatype to another compatible type format. Primitive Typecasting applies strictly to Java's eight core
primitive types and behaves according to fundamental directional memory mechanics: Widening conversions
and Narrowing conversions.

Q15. Explain what is Widening with the example program.

Widening conversion (Implicit Casting) automatically expands a smaller data type into a larger data type
container without losing data. Because the destination type provides broader memory capacity, the system
handles the conversion implicitly without requiring special code instructions.

byte → short → char → int → long → float → double

public class WideningDemo {


public static void main(String[] args) {
int coreValue = 4520;
// Automatic runtime widening promotion from int (4-bytes) to double (8-
bytes)
double widenedResult = coreValue;

[Link]("Original integer storage value = " + coreValue); //


Output: 4520
[Link]("Implicitly converted double value = " +
widenedResult); // Output: 4520.0
}
}

Q16. Explain what is narrowing with the Java program.

Narrowing conversion (Explicit Casting) compresses a data value from a larger memory layout into a smaller
destination type container. This requires an explicit manual assignment using parentheses, like
(target_type). Because truncation can occur if the source value exceeds the smaller type's bounds,
developers must confirm they accept potential data or precision loss.

Java Core Programming Study Guide 8


public class NarrowingDemo {
public static void main(String[] args) {
double exactPrecisionVal = 987.6543;
// Explicit structural narrowing cast coercion directive
int narrowedIntVal = (int) exactPrecisionVal;

[Link]("Original precise source value = " +


exactPrecisionVal); // Output: 987.6543
[Link]("Manually truncated integer result = " +
narrowedIntVal); // Output: 987
}
}

Q17. What is typecast operator?

The typecast operator is a cast directive written as a type name wrapped inside parentheses, such as (int),
(char), or (float). Placed directly before an expression, it forces the compiler to convert the data value to
the requested target type.

Q18. What is Compound Assignment Operator? Explain the advantage with an


example program.
A compound assignment operator combines an arithmetic or bitwise operator with the standard assignment
symbol (e.g., +=, -=, *=, /=, %=). This shorthand streamlines assignments by updating the target variable in
place.

Key Architectural Advantage: Compound operators automatically perform an implicit cast


transformation on the underlying expressions. This prevents compile errors when working with mismatched
variable types, removing the need for manual casting code.

public class CompoundAssignmentDemo {


public static void main(String[] args) {
// Demonstration of standard operations
int aggregateVal = 10;
aggregateVal += 5; // Evaluates exactly as: aggregateVal = aggregateVal + 5
[Link]("Value = " + aggregateVal); // Output: 15

// Architectural Typecasting Advantage Example:


byte smallByte = 8;
// smallByte = smallByte + 4; // CRASH! Compiler rejects because '4' promotes
evaluation to 'int'
smallByte += 4; // SUCCESS! Automatically compiles using
internal calculation: (byte)(smallByte + 4)
[Link]("Byte state = " + smallByte); // Output: 12
}
}

Java Core Programming Study Guide 9


Q19. Explain the working of AND, OR, NOT?

These are Conditional Logical Operators used to connect boolean expressions, evaluating conditions based
on standard truth logic rules:

• Conditional AND (&&): Returns true only if both expressions evaluate to true. It uses short-circuit
optimization: if the left-hand condition evaluates to false, the evaluation instantly aborts, skipping the
right-hand condition since the overall outcome can never be true.

• Conditional OR (||): Returns true if at least one of the expressions evaluates to true. It also short-
circuits: if the left condition evaluates to true, the runtime skips evaluating the right condition, as the
result is already guaranteed to be true.

• Logical NOT (!): A unary operator that reverses a boolean value, changing true states to false and
vice versa.

Q20. What is Increment & Decrement Operator?

These unary operators increase or decrease an integer variable's value by exactly 1. They behave differently
depending on where the operator is placed:

• Pre-Increment (++x) / Pre-Decrement (--x): Modifies the variable's value first, and then returns the
newly updated value to the surrounding expression.

• Post-Increment (x++) / Post-Decrement (x--): Evaluates the expression using the variable's current
value first, and then modifies the underlying value in memory once the statement completes.

Q21. What is Ternary Operator? Write the Syntax.

The ternary operator (?:) is a clean, inline alternative to simple if-else conditional statements. It is the only
operator in Java that works with three distinct operands.

Syntax Definition:

variableName = (conditionalExpression) ? valueIfTrue : valueIfFalse;

Java Core Programming Study Guide 10


Part 4: Control Flow Structures & Iteration Loops

Q22. What are decision making statements?

Decision-making statements guide execution flow by evaluating expressions at runtime to selectively run
specific code blocks. Java's decision-making toolkit includes if branches, if-else structures, nested
else-if ladders, and switch blocks.

Q23. Which datatype cannot be passed inside Switch?

The datatypes that cannot be passed inside a switch expression are:

long, float, double, and boolean

This limitation exists because switch structures require exact matching. Floating-point numbers are prone to
rounding variances, long integers cover too large a range for efficient jump-table indexing, and boolean
flags are better suited for simple if-else statements. A switch statement only accepts types convertible to
a 32-bit integer (byte, `short`, `char`, `int`), along with `String` literals and `enum` values.

Q24. Explain what is break?

The break keyword is a control-jump statement that instantly stops the execution of the loop (for, while,
do-while) or switch block containing it. When hit, execution exits the block immediately and resumes at
the next line of code directly following that structure.

Q25. Write the syntax for switch case?

switch (evaluatingExpression) {
case targetValue1:
// Operational code segment executed when expression == targetValue1
break; // Crucial break boundary to prevent falling through to the next case
case targetValue2:
// Operational code segment executed when expression == targetValue2
break;
default:
// Fallback execution path run if no matching case is found
}

Q26. What is loop & what is diff b/w while & Do-while loop?

A loop is a control structure that repeatedly executes a block of code as long as its guiding conditional
expression remains true. While both loops handle repetition, they verify conditions differently:

Java Core Programming Study Guide 11


Comparison
The while Loop Structure The do-while Loop Structure
Attribute

Entry-Controlled Loop. The conditional Exit-Controlled Loop. The loop body


Evaluation
check happens before execution access is executes first, and the condition is
Category
granted to the loop body. evaluated at the end of the block.

At least 1 time. The loop body always


Minimum 0 times. If the initial condition is false, the
runs at least once, even if the condition is
Iteration Runs loop body is skipped entirely.
false from the start.

Body block opens first; condition


Condition statement sits at the top; body
Syntax Layout expression terminates the block at the
block follows.
bottom with a required semicolon.

Q27. Write the syntax for for, for-loop, while loop, do-while loop?

1. Standard for Loop: (Best for fixed-count iteration paths)

for (initializationStatement; continuationCondition; updateExpression) {


// Loop processing body code
}

2. Standard while Loop: (Best for condition-driven dynamic loops)

while (continuationCondition) {
// Loop processing body code
}

3. Standard do-while Loop: (Guarantees at least one execution run)

do {
// Loop processing body code
} while (continuationCondition);

Java Core Programming Study Guide 12


Part 5: Functional Methods & Thread Execution Mechanics

Q28. What is a Method?

A method is a structured collection of code statements grouped together under a unique name to perform a
specific action. Methods encourage modularity, making code more readable and reusable across an
application while eliminating duplication.

Q29. Write a syntax for method?

accessModifier nonAccessModifier returnType methodName(parameterDataType


parameterName) {
// Structural internal method execution body
return targetedValue; // Conditional matching returnType requirement
}

Q30. Explain what is access modifier, Modifier & return type.

These components define how a method can be accessed and used across an application:

• Access Modifier: Defines the visibility scope and access rights for other classes (e.g., public allows
universal access, private restricts access to the defining class, and protected limits visibility to
subclasses and package extensions).

• Non-Access Modifier: Customizes a method's behavior within the application framework (e.g., static
links the method directly to the class rather than an object instance, and final prevents subclasses from
overriding it).

• Return Type: Specifies the data type of the value the method passes back to its caller. If the method
performs an action without passing back a value, it uses the void keyword.

Q31. Who is responsible for calling the main method?

The Java Virtual Machine (JVM) is responsible for calling the main method. When you launch a Java
application, the JVM initializes its runtime environment and searches for the required entry point (public
static void main(String[] args)) to start the main thread of execution.

Q32. Explain what is NO Argument method & parameterized method.

• No-Argument Method: A method defined with an empty parameter list. It executes its internal logic
independently without requiring external input data from the caller.

void printSystemStatus() { [Link]("Online"); }

Java Core Programming Study Guide 13


• Parameterized Method: A method defined with specific input variables in its signature. This design allows
it to accept dynamic data values from the caller, making the method more versatile.

void displayCustomScore(int operationalScore) { [Link]("Score: " +


operationalScore); }

Q33. What is formal argument & actual argument?

• Formal Argument (Parameter): The placeholder variables defined in a method's signature. They set the
required data type and name for inputs the method expects to receive.

void evaluateRatio(int lengthValue) // 'lengthValue' is a formal argument


placeholder

• Actual Argument (Argument): The actual, concrete data values passed into the method when it is called
during program execution.

evaluateRatio(45); // '45' represents the concrete actual argument injected

Q34. What is return keyword?

The return keyword explicitly stops execution inside a method and passes control back to the statement
that called it. If the method defines a return type, the return keyword also passes the calculated value back
to the calling context.

Q35. What happens if we write any statement after the return keyword?

Adding statements directly after a return keyword within the same execution path triggers a compilation
error labeled "Unreachable code". The compiler identifies that these trailing lines can never execute, treating
them as structural design errors and blocking compilation.

Java Core Programming Study Guide 14


Part 6: Polymorphic Method Overloading & System
Recursion

Q36. What is method Overloading & explain the rules of method Overloading?

Method Overloading is a compile-time polymorphic feature that lets a class define multiple methods with the
exact same name but different input parameters. This makes the API cleaner by using a single intuitive name
for variations of an action.

Strict Validation Overloading Rules:

1. Overloaded methods must change their parameter signatures. They must differ in the total number of
arguments, the datatypes of the arguments, or the order in which those types are listed.

2. Changing only the return type or access modifiers does not satisfy the rules for overloading. If the
parameters match exactly, modifying these other properties triggers a duplicate method compilation error.

Q37. Can we overload the main method? If yes, which main method gets
executed first?
Yes, you can overload the main method by defining variations with different parameter lists. However, the
JVM will always look for and automatically run the standard entry point method signature first:

public static void main(String[] args)

Any other overloaded versions of the main method will not run automatically; you must call them manually
from within the primary main method.

Q38. Return type of the overloaded methods should be same or can it be


different?
The return types of overloaded methods can be completely different. However, a difference in return type
alone is not enough to overload a method. The input parameters must be modified first to successfully
overload the method signature.

Q39. Explain method Overloading with the real time example.

Consider a real-world enterprise **Payment Gateway Processing System**. Customers expect a single,
intuitive interface to make payments, but the system must handle different payment methods internally.
Method overloading elegantly solves this scenario:

• processPayment(double cashAmount) → Processes quick point-of-sale transactions.

Java Core Programming Study Guide 15


• processPayment(String creditCardNo, int securityPin) → Routes transactions through
credit card clearance pipelines.

• processPayment(String upiTargetId) → Connects directly to instant digital wallet architectures.

Q40. Write the program for method overloading?

public class ShapeComputationEngine {


// Version A: Overloaded signature taking 1 parameter for circle calculations
public double computeArea(double radiusValue) {
return 3.14159 * radiusValue * radiusValue;
}

// Version B: Overloaded signature taking 2 parameters for rectangle calculations


public double computeArea(double widthValue, double heightValue) {
return widthValue * heightValue;
}

public static void main(String[] args) {


ShapeComputationEngine engine = new ShapeComputationEngine();
[Link]([Link](5.0)); // Executes Version A
(Output: 78.53975)
[Link]([Link](10.0, 4.0)); // Executes Version B
(Output: 40.0)
}
}

Q41. What is method recursion?

Method recursion is a programmatic technique where a method calls itself to break down a problem into
smaller, manageable parts. Each recursive call reduces the problem's complexity until execution hits a
defined base condition that stops the cycle.

Q42. What is Stack Overflow error?

A StackOverflowError is a severe runtime exception thrown when the JVM's call stack runs out of
memory space. Every time a method is called, a new execution frame is pushed onto the stack to track its
variables and state. If recursive calls continue indefinitely without stopping, these stack frames pile up until
they exceed the call stack's memory limits, crashing the application.

Q43. Can we avoid Stackoverflow error?

Yes, you can avoid a StackOverflowError by designing recursive methods with clean control safety
features:

• A Definitive Base Case: A clear conditional statement that stops the recursion immediately once met,
preventing infinite loops.

Java Core Programming Study Guide 16


• Progressive Traversal States: Ensure the arguments passed into each recursive call change predictably,
moving closer toward meeting the base case with every step.

Q44. Write the program on method recursion?

The following example uses recursive logic to compute the factorial of a target number, safely guarded by a
base case condition:

public class MathematicalRecursionEngine {


// Recursive method designed to calculate mathematical factorials
public static int computeFactorial(int targetNumber) {
// Essential Base Case: stops execution once the calculation hits 0 or 1
if (targetNumber <= 1) {
return 1;
}
// Recursive Call: reduces the target value step-by-step toward the base case
return targetNumber * computeFactorial(targetNumber - 1);
}

public static void main(String[] args) {


int calculationInput = 5;
int outputFactorialResult = computeFactorial(calculationInput);
[Link]("The calculated factorial of " + calculationInput + " is =
" + outputFactorialResult);
// Correct Expected Processing Output: 120
}
}

Java Core Programming Study Guide 17

You might also like