0% found this document useful (0 votes)
2 views13 pages

Java Exam Notes Editable

The document provides comprehensive Java exam notes covering key concepts such as JDK, JRE, JVM, data types, control statements, loops, methods, strings, and problem-solving approaches. It includes theory questions, programming exercises, and explanations of important topics like compilation, execution, and type casting. The content is structured for easy readability and is designed to aid in exam preparation.

Uploaded by

scig29624
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)
2 views13 pages

Java Exam Notes Editable

The document provides comprehensive Java exam notes covering key concepts such as JDK, JRE, JVM, data types, control statements, loops, methods, strings, and problem-solving approaches. It includes theory questions, programming exercises, and explanations of important topics like compilation, execution, and type casting. The content is structured for easy readability and is designed to aid in exam preparation.

Uploaded by

scig29624
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 Exam Notes and Programs

Editable Word File | Topic-wise Questions, Answers, and Programs

Clean, readable, and exam-ready

Note: All code examples below have been checked and the few incomplete or mismatched examples
from the source material have been corrected for consistency and accuracy.

Topic 1: Introduction to Java (JDK, JVM, JRE)


Key Points
• JDK is the development kit. It includes the compiler and tools.
• JRE is the runtime environment used to run Java programs.
• JVM executes bytecode and makes Java platform-independent.
• "Write Once, Run Anywhere" is possible because of the JVM.

Theory Questions and Answers


Explain in your own words the role of JDK, JRE, and JVM.
JDK (Java Development Kit) is the full development package that contains the compiler (javac),
libraries, and tools needed to write and compile Java programs. JRE (Java Runtime Environment) is
the package needed to run already-compiled Java programs; it contains the JVM and required
libraries. JVM (Java Virtual Machine) is the actual engine that loads .class files, converts bytecode into
machine code, and executes the program. It is the reason Java is platform-independent.
Why is Java called platform-independent? Which component makes this possible?
Java is platform-independent because the same .class (bytecode) file can run on Windows, Mac,
Linux, and other platforms. The JVM makes this possible: every operating system has its own version
of the JVM that translates the same bytecode into that OS-specific machine code.
What is bytecode and why does the JVM need it?
Bytecode is the intermediate, platform-independent code produced by the javac compiler from .java
source files. The JVM needs it because bytecode is the form that the JVM understands, and it
converts bytecode into machine-specific code at runtime.
Differentiate between a developer’s machine and an end-user’s machine regarding Java tools
required.
A developer’s machine needs the JDK to write and compile code. An end-user’s machine needs only
the JRE to run the compiled .class file. Both machines need a JVM, but the end-user does not need
the compiler.
Java Exam Notes and Programs
Programming Exercises
Smallest possible complete Java program that prints “Hello, Mid-Term!”

public class HelloMidTerm {


public static void main(String[] args) {
[Link]("Hello, Mid-Term!");
}
}
Expected Output

Hello, Mid-Term!
Program named [Link] that prints name and roll number, plus compile/run commands

public class Welcome {


public static void main(String[] args) {
[Link]("Name: Abdul");
[Link]("Roll Number: Your Roll Number");
}
}

Compile:
javac [Link]

Run:
java Welcome
Journey of a Java program (in words)

Write .java file -> javac compiles it to .class (bytecode) -> java command launches JVM -> JVM
loads .class -> converts bytecode to machine code -> program runs.

Topic 2: Compilation and Execution


Key Points
• .java -> javac -> .class (bytecode) -> java command + JVM.
• Syntax errors stop compilation.
• Bytecode is platform-independent.

Theory Questions and Answers


Exact steps when you type javac [Link] followed by java MyProgram

Java Exam Notes and Programs


javac reads [Link], checks syntax, and produces [Link] (bytecode). The java
command starts the JVM, loads [Link], converts bytecode to machine code, and executes
the main method.
What happens if there is a syntax error in the .java file?
The compiler (javac) stops immediately, shows error messages with line numbers, and does not
create a .class file. The program cannot run.
Difference between source code (.java), bytecode (.class), and machine code
Source code (.java) is human-readable. Bytecode (.class) is intermediate, platform-independent code.
Machine code is the final OS-specific binary that the CPU actually executes.
Correct sequence of the Java program lifecycle
Write (.java) -> Compile (javac -> .class) -> Run (java + JVM).

Programming Exercises
[Link] + commands

public class TestCompilation {


public static void main(String[] args) {
[Link]("Compilation successful!");
}
}

Commands:
javac [Link]
java TestCompilation
What happens if you run java TestCompilation without compiling

Error: "Could not find or load main class TestCompilation" because the .class file does not exist.
Program with intentional syntax error

javac output: "Error: ';' expected"

Topic 3: Data Types and Variables


Key Points
• Java has 8 primitive data types.
• Variables must be declared before use.
• Variable names are case-sensitive.

Java Exam Notes and Programs


Theory Questions and Answers
8 primitive data types with examples
int (age), double (marks), char (grade), boolean (passed), byte, short, long, and float.
Why are variable names case-sensitive?
Because Java treats rollNo and rollno as two different variables.
Difference between declaration, initialization, and assignment
Declaration: int x; Initialization: int x = 10; Assignment: x = 20;
Local variables
Variables declared inside a method; they exist only while the method is running.

Programming Exercises
Variables for student data

public class StudentInfo {


public static void main(String[] args) {
int rollNumber = 12345;
double marks = 92.75;
char section = 'A';
boolean passed = true;
[Link]("Roll: " + rollNumber + ", Marks: " + marks + ",
Section: " + section + ", Passed: " + passed);
}
}
Name and age program

public class PersonalInfo {


public static void main(String[] args) {
String name = "Abdul";
int age = 20;
[Link]("My name is " + name + " and I am " + age + "
years old.");
}
}
Swap two integers without third variable

public class SwapWithoutTemp {


public static void main(String[] args) {
int a = 10, b = 20;
[Link]("Before: a=" + a + " b=" + b);
a = a + b;
b = a - b;
a = a - b;
[Link]("After: a=" + a + " b=" + b);
Java Exam Notes and Programs
}
}

Topic 4: Precision and Type Casting


Key Points
• Widening is implicit.
• Narrowing is explicit.
• Narrowing can cause loss of data.
• Mixed expressions automatically widen smaller types.

Theory Questions and Answers


Widening vs Narrowing
Widening (int -> double) is automatic and safe. Narrowing (double -> int) is explicit and can cause loss
of data.
Why int to double is automatic but not the reverse
Widening never loses information. Narrowing can lose the fractional part, so Java forces the
programmer to be explicit.
Storing 7.9 in int without casting
Compilation error: incompatible types: possible lossy conversion from double to int.

Programming Exercises
Explicit casting example

public class CastingDemo {


public static void main(String[] args) {
double price = 99.99;
int rounded = (int) price;
[Link]("Original: " + price);
[Link]("After casting: " + rounded);
}
}
Mixed expression prediction

public class MixedExpression {


public static void main(String[] args) {
double d = 5;
int i = 2;
[Link](d / i); // 2.5
}
}

Java Exam Notes and Programs


Int + double with casting

public class AddWithCasting {


public static void main(String[] args) {
int x = 10;
double y = 5.7;
double sum = x + y;
int intSum = (int)(x + y);
[Link]("Double sum: " + sum);
[Link]("Int sum: " + intSum);
}
}

Topic 5: Control Statements (if, if-else, nested if, switch)


Key Points
• Use if / if-else for conditions.
• Use switch for multiple fixed choices.
• break prevents fall-through in switch.

Theory Questions and Answers


When to use switch vs if-else
Use switch when comparing one variable against many fixed constant values. Use if-else when
conditions involve ranges or complex logical expressions.
Fall-through in switch
If break is missing, execution continues into the next case(s) until a break or the end of the switch is
found.
Nested if
An if inside another if. Example: checking age and then gender inside the adult block.
Condition in if
It must evaluate to boolean true or false.

Programming Exercises
Grade program with if-else

public class GradeCalculator {


public static void main(String[] args) {
int marks = 85;
if (marks >= 90) [Link]("A");
else if (marks >= 80) [Link]("B");
else if (marks >= 70) [Link]("C");
Java Exam Notes and Programs
else if (marks >= 60) [Link]("D");
else [Link]("F");
}
}
Switch day program

public class DayName {


public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day");
}
}
}
Nested if trace

public class NestedIfTrace {


public static void main(String[] args) {
int x = 10;
if (x > 5) {
if (x < 15) [Link]("Middle");
else [Link]("High");
} else [Link]("Low");
}
}

Topic 6: Loops
Key Points
• while is a pre-check loop.
• do-while is a post-check loop.
• for is best when the number of iterations is known.
• break exits completely and continue skips the current iteration.

Theory Questions and Answers


do-while vs while
do-while executes the body at least once even if the condition is false.

Java Exam Notes and Programs


Three parts of for loop
Initialization happens once, condition is checked before each iteration, and update happens after
each iteration.
break vs continue
break exits the loop completely. continue skips the rest of the current iteration and goes to the next.

Programming Exercises
For loop 1 to 10

public class PrintNumbers {


public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
[Link](i + " ");
}
}
}
do-while loop sum until 0

import [Link];
public class SumUntilZero {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int sum = 0, num;
do {
[Link]("Enter number (0 to stop): ");
num = [Link]();
sum += num;
} while (num != 0);
[Link]("Total sum: " + sum);
[Link]();
}
}
Nested loop pattern

public class StarPattern {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}
}
}

Java Exam Notes and Programs


Topic 7: Functions and Methods
Key Points
• Methods are reusable blocks.
• Overloading means same name, different parameters.
• main() is the entry point.

Theory Questions and Answers


Method overloading
Same method name but different number, type, or order of parameters. It is useful for flexibility.
Local vs class-level variables
Local variables are declared inside a method and visible only inside that method. Class-level variables
are declared outside methods and visible to all methods in the class.
void keyword
It means the method does not return any value.

Programming Exercises
addNumbers method

public class AddNumbers {


public static int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
[Link](addNumbers(10, 20));
}
}
Overloaded add methods

public class OverloadDemo {


public static int add(int a, int b) { return a + b; }
public static int add(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
[Link](add(5, 10));
[Link](add(5, 10, 15));
}
}
Recursive factorial

Java Exam Notes and Programs


public class Factorial {
public static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
[Link](factorial(5));
}
}

Topic 8: Strings and StringBuffer


Key Points
• String is immutable.
• StringBuffer is mutable and is useful when content changes often.
• Common methods include length(), substring(), append(), and toUpperCase().

Theory Questions and Answers


Why String is immutable
Once created, a String object cannot be changed. This makes String thread-safe and secure.
When to use StringBuffer
When you need to frequently modify the string by appending, inserting, or deleting content.
substring(2,5) on “Computer”
It returns characters from index 2 to 4 because the end index is exclusive. The result is "mpu".

Programming Exercises
String info program

import [Link];
public class StringInfo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
[Link]("Length: " + [Link]());
[Link]("First char: " + [Link](0));
[Link]("Last char: " + [Link]([Link]()-1));
[Link]();
}
}
StringBuffer example

Java Exam Notes and Programs


public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Abdul");
[Link](" Karim");
String result = [Link]().toUpperCase();
[Link](result);
}
}
Immutable String prediction

public class ImmutableDemo {


public static void main(String[] args) {
String s1 = "Java";
String s2 = s1;
s1 = s1 + " is fun";
[Link](s2);
}
}

Topic 9: Problem Solving Approaches


Key Points
• Algorithm levels: high-level, pseudo-code, and actual code.
• Trace tables help verify logic before coding.
• The first step is always to understand the problem.

Theory Questions and Answers


Three levels of algorithm
High-level is an English summary. Pseudo-code is a detailed step-by-step outline in English-like
language. Actual code is the final Java syntax.
Trace table
A table that manually tracks variable values step by step to verify logic before writing code.
Problem-solving process
Understand the problem, design the algorithm, write code, test and debug using a trace table, and
then refine.

Programming Exercises
Pseudo-code for even/odd

Input number
If number % 2 == 0 then print “Even” else print “Odd”
Java Exam Notes and Programs
Trace table for perfect number check (N = 6)

SUM = 0
COUNT = 1 -> 6 % 1 == 0 -> SUM = 1
COUNT = 2 -> 6 % 2 == 0 -> SUM = 3
COUNT = 3 -> 6 % 3 == 0 -> SUM = 6
If SUM == N, the number is perfect.
Actual Java code for perfect number check

public class PerfectNumber {


public static void main(String[] args) {
int n = 6, sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) sum += i;
}
if (sum == n) [Link]("Perfect");
else [Link]("Not Perfect");
}
}

Topic 10: Operators and Algorithms


Key Points
• = is assignment, while == is equality.
• Logical operators include &&, ||, and !.
• +=, ++, and % are shorthand operators.

Theory Questions and Answers


= vs ==
= assigns a value. == compares two values for equality.
a += 5
It is shorthand for a = a + 5.
Logical operators
&& means both true, || means at least one true, and ! reverses true/false.

Programming Exercises
Divisible by 3 and 5

Java Exam Notes and Programs


public class Divisible {
public static void main(String[] args) {
int num = 15;
if (num % 3 == 0 && num % 5 == 0) {
[Link]("Divisible by both");
} else {
[Link]("Not divisible by both");
}
}
}
Even numbers using ++ and %

public class EvenNumbers {


public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) [Link](i + " ");
}
}
}
Increment prediction

public class IncrementDemo {


public static void main(String[] args) {
int x = 5;
int y = x++ + ++x;
[Link](y);
}
}

Java Exam Notes and Programs

You might also like