Object Oriented Programming through Java exam preparation.
Practice questions for every unit in the style of the R23 end exam, a model answer for each, and a one-page revision summary. Built on the official syllabus units.
- Practice questions in the exam's style
- Drafted with AI and checked by a second AI pass. Doubtful points were verified against public sources. Report a mistake
- Units
- 5
- Questions
- 60
- 2-mark
- 30
- 10-mark
- 30
- Done
- Checked on
Exam guide
Paper pattern
Semester-end theory paper, 70 marks, from the JNTUK B.Tech R23 Regulations, end-examination pattern for theory subjects.
- Question 1 · 20 marksTen compulsory short-answer questions of 2 marks each (two from every unit).
- Questions 2 to 6 · 50 marksFive either/or questions of 10 marks each, one per unit. You answer one of the two in each.
- The semester-end examination carries 70 marks; internal assessment carries 30.
- Mid-semester examinations are separate: a 20-minute objective paper (10 marks) and a 90-minute subjective paper with three either/or questions of 10 marks (condensed to 15 marks).
- The regulations text does not state the length of the end examination. Use the duration printed on your hall ticket or question paper.
How to split your time
This plan assumes a 3-hour paper. If yours is different, keep the same proportions. Marks per minute stay roughly even across Question 1 and the 10-mark answers.
- 10 minRead the paper and choose one option in each either/or question
- 30 minQuestion 1: ten short answers (about 3 minutes each)
- 130 minQuestions 2 to 6: one 10-mark answer per unit (about 26 minutes each)
- 10 minFinal check of numbering, calculations and diagrams
Study tips for Object Oriented Programming through Java
- Practise writing complete Java programs by hand on paper, including the class declaration, main method, imports and proper indentation, because a written exam gives you no compiler to catch missing semicolons, braces or wrong method signatures.
- For every program you write, trace its output manually by tracking variable values, object references and the order of constructor, static block and method calls, especially for inheritance, method overriding and exception handling with try, catch and finally.
- Prepare clear labelled diagrams for concepts such as the thread life cycle, the exception class hierarchy, the JDBC architecture and inheritance types, and practise describing each arrow or link so the diagram supports your written explanation.
- When answering descriptive questions, pair each definition with a short code snippet that demonstrates it, for example an interface with an implementing class or an overloaded and an overridden method side by side, so the examiner can see you understand both the concept and its syntax.
OOP Basics, Data Types, Operators and Control Statements
Syllabus: Basic concepts and principles of object-oriented programming; Program structure in Java and writing simple Java programs; Tokens in Java programs; Java statements; Command-line arguments and user input to programs; Escape sequences, comments and programming style; Data types in Java and declaration of variables; Type casting; Scope of variable identifiers; Literal constants and symbolic constants; Formatted output with the printf() method; Static variables and methods; The final attribute; Precedence and associativity of operators; Arithmetic, increment and decrement, and ternary operators; Relational, boolean logical and bitwise logical operators; if, nested if and if-else statements; The switch statement; while, do-while, for, nested for and for-each loops; break and continue statements
One-page revision summary
- OOP builds programs from objects that bundle data and methods; its pillars are encapsulation, abstraction, inheritance and polymorphism.
- Execution of a Java program starts at public static void main(String[] args); javac produces bytecode, which the JVM runs on any platform.
- Java tokens are keywords, identifiers, literals, operators and separators; comments and white space are not tokens.
- Java statements include declaration, expression, block, control (if, switch, loops), jump (break, continue, return) and empty statements, and simple statements end with a semicolon.
- Command-line arguments arrive as Strings in args and are converted with Integer.parseInt or Double.parseDouble, while new Scanner(System.in) reads keyboard input.
- Escape sequences such as \n, \t, \\ and \" represent special characters, and comments come in //, /* */ and /** */ forms.
- Good programming style uses PascalCase for classes, camelCase for variables and methods, CAPITALS for constants, consistent indentation and meaningful comments.
- Java has eight primitive types (byte, short, int, long, float, double, char, boolean), and char is a 2-byte Unicode type.
- Widening conversion is automatic, whereas narrowing needs an explicit cast and may lose data, as in (int) 9.78 = 9.
- A variable is visible only inside the block in which it is declared, and local variables must be initialised before use.
- Literals are fixed values such as 25L, 3.5f and 'A', while symbolic constants are named final values such as static final double PI = 3.14159;.
- printf() uses format specifiers such as %d, %f, %s, %c, %b, %e and %n, with optional width, precision and the - flag for left justification.
- Static variables have one copy per class, static methods are called through the class name, and a static block runs once when the class is loaded.
- A blank final instance variable must be assigned exactly once, normally in the constructor; final methods cannot be overridden and final classes cannot be extended.
- Precedence decides which operator is applied first and associativity breaks ties; assignment, unary and ?: operators associate right to left.
- && and || short-circuit, but & and | always evaluate both operands.
- A switch expression may be byte, short, char, int, their wrappers, an enum or a String, and a missing break causes fall-through.
- A labelled break or continue (for example break outer;) controls an outer loop from inside a nested loop.
Learn these by heart
- Widening order: byte → short → int → long → float → double (and char → int); any reverse conversion needs an explicit cast.
- Operator precedence (high to low): postfix > unary/cast > * / % > + - > shifts > relational > == != > & > ^ > | > && > || > ?: > assignment.
- x++ uses the value and then increments it; ++x increments first and then uses the value.
- Symbolic constant syntax: static final type NAME = value; for example static final int MAX = 100;.
- main method signature: public static void main(String[] args).
- printf format pattern: %[flags][width][.precision]conversion; for example %8.2f prints a double in 8 columns with 2 decimals.
- do-while executes its body at least once; while and for may execute zero times.
2-mark questions
1 List any four escape sequences used in Java and name the three kinds of comments. 2 marks
Escape sequences are backslash codes for special characters: \n (new line), \t (horizontal tab), \\ (backslash), \" (double quote), \' (single quote) and \r (carriage return).
Java has three kinds of comments:
- single-line // ...
- multi-line /* ... */
- documentation /** ... */, which the javadoc tool reads.
2 What is a static method? State two restrictions on it. 2 marks
A static method belongs to the class, not to any object. It is called using the class name, for example Math.sqrt(16).
Restrictions:
- It can directly access only static variables and other static methods.
- It cannot use the keywords this or super.
A static variable also belongs to the class, so one copy is shared by all objects. If a constructor executes count++ on a static int count, every new object updates the same counter, which is read as ClassName.count.
3 State the effect of the final keyword on a variable, a method and a class. 2 marks
- A final variable can be assigned only once, so it behaves as a constant, for example final int MAX = 100;.
- A final method cannot be overridden in a subclass.
- A final class cannot be extended. For example, String is a final class.
4 Write a printf() statement that prints double pi = 3.14159 in a field of width 8 with 2 decimal places, and show the output. 2 marks
System.out.printf("%8.2f%n", pi);
Here 8 is the field width, .2 is the precision, f is the floating-point conversion and %n prints a new line. The value is rounded to 3.14 and right-justified. The output is four spaces followed by 3.14, which is 8 characters in total.
5 If int x = 5; int y = x++ + ++x; find the final values of x and y. 2 marks
Operands are evaluated left to right.
- x++ gives 5 and then makes x = 6.
- ++x makes x = 7 and gives 7.
- y = 5 + 7 = 12.
Final values: x = 7, y = 12.
6 What value is stored in b by byte b = (byte) 130; ? Explain briefly. 2 marks
130 is outside the byte range -128 to 127. The narrowing cast therefore keeps only the lowest 8 bits, which are 10000010. Read as a signed two's-complement byte, this is 130 - 256 = -126. Hence b = -126.
10-mark questions
1 Explain the basic concepts and principles of object-oriented programming with suitable examples. How does OOP differ from procedure-oriented programming? 10 marks
Object-oriented programming (OOP) organises a program around objects. Each object combines data with the operations on that data, instead of keeping functions and data apart. Java is built on this model, so every Java program is written as one or more classes.
1. Class: A class is a user-defined blueprint. It describes the data (fields) and behaviour (methods) common to a group of objects. Example: class Account with the field balance and the methods deposit() and withdraw().
2. Object: An object is a runtime instance of a class with its own state. Account a1 = new Account(); creates one object in heap memory.
3. Encapsulation: Data and methods are wrapped together in a class. Fields are usually declared private, so they can be changed only through public methods. This data hiding protects the data from accidental misuse.
4. Abstraction: Only the essential features are shown to the user and the implementation details are hidden. A driver uses the brake pedal without knowing the hydraulic details. In Java, abstract classes and interfaces support abstraction.
5. Inheritance: A new class (subclass) acquires the fields and methods of an existing class (superclass) using extends. This gives code reuse and a natural hierarchy.
6. Polymorphism: One name, many forms.
- Compile-time polymorphism is method overloading: the same method name with different parameter lists.
- Run-time polymorphism is method overriding: a subclass redefines a superclass method.
7. Dynamic binding: For an overridden call, the method body to be executed is chosen at run time, based on the actual object.
8. Message passing: Objects communicate by calling each other's methods, for example a1.deposit(500).
Difference from procedure-oriented programming (POP):
- POP divides a program into functions; OOP divides it into objects.
- POP follows a top-down approach; OOP follows a bottom-up approach.
- In POP, data moves freely between functions and is often global; in OOP, data is hidden inside objects.
- POP offers little reuse; OOP supports reuse through inheritance and polymorphism.
Conclusion: Encapsulation, abstraction, inheritance and polymorphism make Java programs modular, secure and reusable. They also make programs easier to maintain and extend.
2 Describe the general structure of a Java program. Write a Java program that adds two integers passed as command-line arguments and then reads the user's name using Scanner. Also identify the tokens and kinds of statements used. 10 marks
A Java program is a collection of classes stored in a .java file. The compiler javac translates it into platform-independent bytecode (a .class file), which the Java Virtual Machine executes.
The sections of a program, from top to bottom, are: 1. Documentation section: comments giving the program name, author and purpose (optional). 2. Package statement: for example package mypack; (optional, at most one, and it must come first). 3. Import statements: for example import java.util.Scanner; (optional). 4. Interface statements: interface declarations (optional). 5. Class definitions: other classes the program needs (optional). 6. Main method class: the class containing public static void main(String[] args), where execution starts (essential).
Program:
import java.util.Scanner;
public class AddDemo {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("Sum = " + (a + b));
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Welcome, " + name);
sc.close();
}
}Compile and run:
javac AddDemo.java
java AddDemo 10 20Command-line arguments are stored as strings in args, so args[0] = "10" and args[1] = "20". Integer.parseInt converts them to int, and the program prints Sum = 30. If fewer than two arguments are given, an ArrayIndexOutOfBoundsException occurs. The Scanner object reads keyboard input from System.in; its methods nextInt(), nextDouble() and nextLine() read an int, a double and a whole line.
Tokens are the smallest meaningful units of the program:
- Keywords: public, class, static, void, int
- Identifiers: AddDemo, main, a, b, sc, name
- Literals: 0, 1, "Sum = "
- Operators: =, +
- Separators: ( ) { } [ ] ; , .
Comments and white space are discarded by the compiler and are not tokens.
Statements used:
- Declaration statements: int a = ...;
- Expression statements: method calls such as System.out.println(...);
- Block statements: statements enclosed in { }
Other kinds of statement are control statements (if, switch, loops), jump statements (break, continue, return) and the empty statement ;. Some textbooks also list labelled statements (for example outer: for (...)), synchronization statements (synchronized blocks) and guarding statements (try-catch blocks).
Programming style: a Java program should be easy to read. Common conventions are:
- Class names start with a capital letter (AddDemo), variables and methods use camelCase (sum, readName), and constants use capitals (MAX).
- Use meaningful names, one statement per line and the same indentation inside every block.
- Put the opening brace at the end of the line that starts the block and align the closing brace with that line.
- Add a comment for the purpose of the program and for any step that is not obvious.
Conclusion: A Java program follows a fixed layout that ends in the main class. It can receive data at launch time through command-line arguments, or interactively through Scanner.
3 Explain the primitive data types of Java with their sizes and ranges. Discuss declaration of variables, type casting, scope of variables, and literal and symbolic constants with examples. 10 marks
Java is a strongly typed language. Every variable must be declared with a type before use, and the compiler checks every assignment.
1. Primitive data types:
- byte: 1 byte, -128 to 127
- short: 2 bytes, -32768 to 32767
- int: 4 bytes, -2^31 to 2^31 - 1
- long: 8 bytes, -2^63 to 2^63 - 1
- float: 4 bytes, about 6 to 7 significant digits
- double: 8 bytes, about 15 significant digits
- char: 2 bytes, Unicode values 0 to 65535
- boolean: only true or false
Non-primitive (reference) types include classes, arrays, interfaces and String.
2. Declaration of variables: the form is type name [= value];. Examples: int count = 0; double rate = 7.5, tax; char grade = 'A';. Instance and static fields get default values (0, 0.0, false, '\u0000', null). Local variables get no default and must be initialised before use.
3. Type casting:
- Widening (implicit): a smaller type converts automatically to a larger one, in the order byte → short → int → long → float → double, and char → int. Example: int i = 100; double d = i; gives d = 100.0.
- Narrowing (explicit): a larger type converts to a smaller one only with a cast operator, and data may be lost. Example: double x = 9.78; int n = (int) x; gives n = 9, because the fraction is truncated.
- In expressions, byte, short and char are promoted to int. So byte p = 10, q = 20; byte r = p * q; is a compile error and must be written byte r = (byte)(p * q);.
4. Scope of variables:
- Instance variables are declared inside a class but outside methods; they exist as long as the object exists.
- Static (class) variables have one copy shared by all objects.
- Local variables are declared inside a method and are visible only in that method.
- Block variables are declared inside { } and are visible only within that block.
int x = 10;
{
int y = 20;
System.out.println(x + y); // 30
}
// y is not accessible hereJava does not allow an inner block to redeclare a local variable such as x of the enclosing method.
5. Literal constants are fixed values written directly in code:
- 25 (int), 25L (long), 0x1F (hexadecimal int, value 31)
- 3.5 (double), 3.5f (float)
- 'A' (char), "Java" (String), true (boolean)
6. Symbolic constants are named constants declared with final, usually also static and written in capital letters: static final double PI = 3.14159;. They improve readability, and one change updates every use.
Conclusion: Choosing the right data type, controlling conversions with casting and limiting variable scope make Java programs correct and memory-efficient.
4 Explain arithmetic, increment/decrement, relational, logical, bitwise and ternary operators in Java. Discuss precedence and associativity, and evaluate int r = 10 + 4 * 3 - 8 / 2 % 3; step by step. 10 marks
An operator is a symbol that performs an operation on one, two or three operands. Java's operators fall into the following groups.
1. Arithmetic operators: + - * / %. Integer division drops the fraction: 7 / 2 = 3 and 7 % 2 = 1. Also -7 % 2 = -1, because the remainder takes the sign of the dividend.
2. Increment and decrement: ++ and --.
- Prefix (++x) changes the value first and then uses it.
- Postfix (x++) uses the old value and then changes it.
If x = 5, then y = x++ gives y = 5 and x = 6. Next, z = ++x gives x = 7 and z = 7.
3. Relational operators: < <= > >= == !=. They return a boolean, so (8 > 3) is true.
4. Boolean logical operators: && (AND), || (OR) and ! (NOT), plus the non-short-circuit &, | and ^ on booleans. && and || short-circuit. In (n != 0 && 10 / n > 1), the division is skipped when n is 0, which avoids an exception.
5. Bitwise operators: & | ^ ~ << >> >>> work on the bits of integers. With a = 12 (1100) and b = 10 (1010):
- a & b = 1000 = 8
- a | b = 1110 = 14
- a ^ b = 0110 = 6
- ~a = -13
- a << 2 = 48 and a >> 1 = 6
- -16 >> 2 = -4, because the sign bit is kept; >>> fills with zeros instead
6. Ternary operator: condition ? value1 : value2. For example, int max = (a > b) ? a : b; gives 12.
7. Precedence, from highest to lowest:
- postfix x++ x--
- unary ++x --x + - ! ~ and cast
- * / %
- + -
- << >> >>>
- < <= > >= instanceof
- == !=
- &, then ^, then |
- &&, then ||
- ?:
- = += -= *= /= and the other assignments
Associativity decides the order when operators of equal precedence meet. Most binary operators work left to right: 100 / 10 / 5 = (100 / 10) / 5 = 2. Unary, ternary and assignment operators work right to left: a = b = c = 7 assigns 7 to c, then to b, then to a.
8. Evaluation of int r = 10 + 4 * 3 - 8 / 2 % 3;
- Step 1: * / % have higher precedence and are left-associative, so 4 * 3 = 12.
- Step 2: 8 / 2 = 4.
- Step 3: 4 % 3 = 1.
- Step 4: the expression is now 10 + 12 - 1. Working left to right, 10 + 12 = 22.
- Step 5: 22 - 1 = 21.
Result: r = 21.
Conclusion: Knowing what each operator does, together with its precedence and associativity, lets a programmer predict the value of any expression. Parentheses should be added wherever the intent needs to be made clear.
5 Explain the if, if-else, nested if and else-if ladder statements with syntax and examples. Write a Java program using a switch statement to print a remark for a grade character, and explain fall-through. 10 marks
Selection (decision) statements let a program choose between paths depending on a condition. In Java, the condition must be a boolean expression.
1. Simple if: the statement runs only when the condition is true.
if (marks >= 40) System.out.println("Pass");2. if-else: exactly one of two blocks runs.
if (n % 2 == 0) System.out.println("Even");
else System.out.println("Odd");3. Nested if: an if placed inside another if. An else always pairs with the nearest unmatched if. Largest of three numbers:
if (a > b) {
if (a > c) big = a; else big = c;
} else {
if (b > c) big = b; else big = c;
}For a = 4, b = 9, c = 6: a > b is false and b > c is true, so big = 9.
4. else-if ladder: the conditions are tested from top to bottom, and the first true one is executed.
if (m >= 90) g = 'A';
else if (m >= 75) g = 'B';
else if (m >= 60) g = 'C';
else g = 'F';For m = 78, the result is 'B'.
5. switch statement: selects one of many cases by matching the value of an expression.
public class GradeRemark {
public static void main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A': System.out.println("Excellent"); break;
case 'B': System.out.println("Good"); break;
case 'C': System.out.println("Average"); break;
default: System.out.println("Invalid grade");
}
}
}Output: Good
Rules of switch:
- The expression may be byte, short, char, int, their wrapper classes, an enum or a String. long, float, double and boolean are not allowed.
- Case labels must be compile-time constants and must not repeat.
- default is optional and runs when no case matches.
Fall-through: break transfers control out of the switch. If break is omitted, execution continues into the following cases without checking their labels. For example, if the break after case 'B' were removed, grade 'B' would print both Good and Average. Fall-through can be used deliberately to group cases, such as case 'a': case 'e': ... for vowels.
Conclusion: if-else forms suit range checks and compound conditions. switch is cleaner when one variable is compared with many fixed values.
6 Explain the while, do-while, for, nested for and for-each loops of Java with examples. Explain break and continue, and trace a program that uses both. 10 marks
Loops (iteration statements) repeat a block while a condition remains true. Every loop needs an initialisation, a test and an update.
1. while loop (entry-controlled): the condition is tested before each pass, so the body may run zero times.
int i = 1;
while (i <= 5) { System.out.print(i + " "); i++; } // 1 2 3 4 52. do-while loop (exit-controlled): the body runs first and the condition is tested afterwards, so the body executes at least once.
int n = 10;
do { System.out.println(n); } while (n < 5); // prints 10 once3. for loop: initialisation, condition and update are written in one line.
int sum = 0;
for (int k = 1; k <= 10; k++) sum += k; // sum = 554. Nested for: one loop inside another. The inner loop completes fully for each pass of the outer loop.
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= r; c++) System.out.print("* ");
System.out.println();
}Output: three lines containing 1, 2 and 3 stars.
5. for-each loop: visits every element of an array or collection without using an index.
int[] m = {4, 8, 6};
int total = 0;
for (int v : m) total += v; // total = 186. break and continue:
- break ends the nearest enclosing loop (or switch) immediately.
- continue skips the rest of the current pass and moves to the next iteration; in a for loop it jumps to the update part.
- A labelled break, such as break outer;, leaves an outer loop from inside an inner one.
Trace program:
int sum = 0;
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0) continue;
sum += i;
if (sum > 50) break;
}
System.out.println(sum);- i = 1, 2: sum = 1, then 3
- i = 3: multiple of 3, skipped
- i = 4, 5: sum = 7, then 12
- i = 6: skipped
- i = 7, 8: sum = 19, then 27
- i = 9: skipped
- i = 10, 11: sum = 37, then 48
- i = 12: skipped
- i = 13: sum = 61, which is greater than 50, so break
Output: 61. The loop stops at i = 13 even though its limit was 20.
Conclusion: while and do-while suit loops whose count is unknown, and for suits counted loops. for-each simplifies array traversal, while break and continue give fine control over the flow of a loop.
Classes, Objects and Methods
Syllabus: Class declaration and modifiers; Class members; Declaration of class objects; Assigning one object to another; Access control for class members; Accessing private members of a class; Constructor methods and overloaded constructors; Nested classes; Final classes and methods; Passing arguments by value and by reference; The keyword this; Defining methods; Overloaded methods; Class objects as parameters in methods; Recursive methods; Nesting of methods; Overriding methods; The final and static attributes
One-page revision summary
- A class is declared as [modifiers] class Name { members }, and a top-level class may only be public or default, optionally abstract or final.
- Class members are instance variables, static variables, methods and nested classes; constructors and initializer blocks sit in the class body, and textbooks often list them with the members, although strictly they are not members.
- An object is created in two steps: declare a reference variable, then allocate the object with new, which calls a constructor.
- Assigning one object reference to another copies only the reference, so both variables share one object.
- Access levels from most open to most restricted are public, protected, default (package) and private.
- Private members are reached from outside only through public getter and setter methods, which can validate the data.
- A constructor has the class name and no return type, and the compiler supplies a default constructor only when none is written.
- Overloaded constructors differ in parameter lists, and this(...) chains them but must be the first statement.
- Nested classes can be static nested, inner (member), local or anonymous, and inner classes can access private outer members.
- A final class cannot be extended and a final method cannot be overridden.
- Java passes every argument by value, and for objects the value passed is a copy of the reference.
- The keyword this refers to the current object and resolves clashes between field and parameter names.
- A method definition has modifiers, a return type, a name, a parameter list and a body, and the name plus parameter list form the signature.
- Overloaded methods share a name but differ in parameters and are resolved at compile time.
- Objects passed as parameters let a method read or modify another object's state, for example in a comparison method.
- A recursive method calls itself and must have a base case to stop the recursion.
- Nesting of methods means one method of a class calling another method of the same class directly by name.
- An overriding method has the same signature in a subclass and is chosen at run time through dynamic method dispatch.
- A static member belongs to the class and is shared by all objects, while a final variable can be assigned only once.
- A static final field is a class-wide constant, and static methods cannot use this or non-static members directly.
Learn these by heart
- Java is strictly pass-by-value: primitives copy the value, objects copy the reference.
- A constructor has the same name as the class, has no return type, and this(...) or super(...) must be its first statement.
- Overloading means the same name with a different parameter list and compile-time binding; overriding means the same signature in a subclass and run-time binding.
- Access order is public > protected > default > private, and private means visible only within the same class.
- final variable means a constant, final method means it cannot be overridden, and final class means it cannot be inherited.
- static means one copy per class, accessed as ClassName.member, and a static method has no this reference.
- A recursive method needs a base case, for example fact(n) = 1 if n ≤ 1, else n × fact(n − 1).
2-mark questions
1 What happens when one object reference variable is assigned to another in Java? 2 marks
The statement s2 = s1 copies only the reference, not the object. Both variables then point to the same object on the heap, so a change made through s2 (for example s2.marks = 90) is also seen through s1. No new object is created. A separate copy needs a constructor or clone().
2 What is the use of the keyword this in Java? 2 marks
this is a reference to the current object, the one on which a method or constructor is running. It has three main uses:
- It separates an instance variable from a parameter with the same name, as in this.x = x.
- this(...) calls another constructor of the same class.
- It passes the current object as an argument.
3 What is a final class and a final method? Give an example. 2 marks
A final class cannot be extended. An example is final class Config { }, and java.lang.String is also final. A final method cannot be overridden in a subclass, although it is inherited and may still be overloaded. Both are used to lock behaviour that must not change, for security and design safety.
4 Differentiate between a static variable and a final variable. 2 marks
A static variable belongs to the class, not to any object. One copy is shared by all objects, and it is accessed as ClassName.variable. A final variable can be assigned only once, so it acts as a constant. Together, static final double PI = 3.14159; gives one shared constant.
5 What is a recursive method? Write a recursive method for factorial. 2 marks
A recursive method calls itself. It needs a base case that stops the calls.
static int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}fact(4) = 4 × 3 × 2 × 1 = 24.
6 What is meant by nesting of methods? 2 marks
Nesting of methods means that one method of a class calls another method of the same class directly by its name, without an object and dot operator. For example, in class Rect, area() returns length * width, and display() calls area() inside its body to print the result.
10-mark questions
1 Explain the declaration of a class in Java along with class modifiers and class members. How are methods defined and how are objects of a class declared? Illustrate with a program. 10 marks
A class is a user-defined data type that acts as a blueprint. It groups data (fields) together with the methods that work on that data. Objects are instances created from this blueprint.
1. Class declaration and modifiers. The general form is:
[modifiers] class ClassName [extends Super] [implements Iface] {
// fields, constructors, methods, nested classes
}- public: the class is visible from every package, and the file name must match the class name.
- No modifier (default): the class is visible only inside its own package.
- abstract: the class cannot be instantiated and may contain abstract methods.
- final: the class cannot be subclassed.
- A top-level class cannot be private or protected. These modifiers are allowed only for nested classes.
2. Class members.
- Instance variables: every object gets its own copy.
- Static variables: a single copy is shared by all objects.
- Methods: they define the behaviour of objects.
- Nested classes and interfaces are also members.
Constructors (which initialise new objects) and initializer blocks are also written in the class body, and many textbooks list them with the members. Strictly, the Java language does not count them as members, because they are not inherited.
3. Defining methods. The general form is:
[modifiers] returnType methodName(parameterList) {
// body
return value; // not needed when returnType is void
}The method name together with its parameter list is called the signature.
4. Declaring objects. Creating an object takes two steps. First a reference variable is declared. Then new allocates memory on the heap, runs the constructor and returns the reference.
Student s1; // reference only, no object yet
s1 = new Student(); // object created
Student s2 = new Student(); // both steps in one line5. Program:
class Student {
int rollNo;
String name;
static int count = 0;
void setData(int r, String n) {
rollNo = r;
name = n;
count++;
}
void display() {
System.out.println(rollNo + " " + name);
}
}
public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.setData(101, "Ravi");
s2.setData(102, "Sita");
s1.display();
s2.display();
System.out.println("Objects: " + Student.count);
}
}Output:
101 Ravi 102 Sita Objects: 2
Here rollNo and name are instance members, so each object has its own values. count is static, so both objects update the same copy.
Conclusion: a class declares the data and the methods. Modifiers control its visibility and whether it can be extended. Objects are created with new and accessed through reference variables using the dot operator.
2 What is access control in Java? Explain the access levels available for class members and show how private members of a class can be accessed from outside the class with a suitable program. 10 marks
Access control decides which parts of a program may use a field, method or constructor. It supports encapsulation: the internal data stays hidden and only a safe interface is exposed.
1. The four access levels for members:
- private: accessible only inside the same class.
- default (no keyword): accessible inside the same class and from any class in the same package.
- protected: accessible in the same package, and also in subclasses in other packages through inheritance.
- public: accessible from everywhere.
2. Comparison, from most open to most restricted:
- Same class: public yes, protected yes, default yes, private yes.
- Same package, other class: public yes, protected yes, default yes, private no.
- Subclass in another package: public yes, protected yes, default no, private no.
- Non-subclass in another package: public yes, protected no, default no, private no.
3. Accessing private members. A private field cannot be named outside its class. The class therefore provides public methods that read it (getters) and change it (setters or other operations). These methods can also validate the data before changing it.
class BankAccount {
private String holder;
private double balance;
public BankAccount(String holder, double balance) {
this.holder = holder;
this.balance = balance;
}
public double getBalance() { return balance; }
public String getHolder() { return holder; }
public void deposit(double amt) {
if (amt > 0) balance += amt;
else System.out.println("Invalid amount");
}
public boolean withdraw(double amt) {
if (amt > 0 && amt <= balance) {
balance -= amt;
return true;
}
return false;
}
}
public class AccessDemo {
public static void main(String[] args) {
BankAccount a = new BankAccount("Kiran", 5000);
// a.balance = 100000; // error: balance has private access
a.deposit(2000);
a.withdraw(1500);
System.out.println(a.getHolder() + " : " + a.getBalance());
}
}4. Working:
- Step 1: the balance starts at 5000.
- Step 2: after deposit(2000), it is 5000 + 2000 = 7000.
- Step 3: after withdraw(1500), it is 7000 - 1500 = 5500.
- Output: Kiran : 5500.0
The commented line would not compile, because balance is private. All outside access must go through the public methods, and these methods reject negative deposits and overdrafts.
Conclusion: access modifiers let a class hide its data. Private fields with public getter and setter methods keep objects in a valid state.
3 What is a constructor? Explain default, parameterised and overloaded constructors in Java, and the use of the this keyword inside constructors, with a program. 10 marks
A constructor is a special member that initialises an object at the moment it is created with new.
1. Properties of a constructor:
- Its name is the same as the class name.
- It has no return type, not even void.
- It is called automatically by new, and only once per object.
- It may have access modifiers, but it cannot be static, final or abstract.
2. Default constructor. If a class declares no constructor at all, the compiler adds a no-argument constructor with the same access level as the class. Its body is empty except for an implicit call super() to the superclass's no-argument constructor. It does not set the fields itself. Instance variables already hold their default values (0, 0.0, false, null) as soon as new allocates the object, before any constructor body runs. With the default constructor they simply stay at those values. Once the programmer writes any constructor, the compiler no longer supplies one. A call such as new Box() then fails unless a no-argument constructor is written explicitly.
3. Parameterised constructor. It takes arguments, so each object can start with its own values.
4. Overloaded constructors. A class may have several constructors that differ in the number, type or order of parameters. The compiler picks the one whose parameter list matches the arguments.
5. this in constructors:
- this.field = field separates an instance variable from a parameter with the same name.
- this(...) calls another constructor of the same class. This is constructor chaining, and it must be the first statement in the constructor.
class Box {
double length, width, height;
Box() { // no-argument
this(1, 1, 1);
}
Box(double side) { // cube
this(side, side, side);
}
Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
double volume() {
return length * width * height;
}
}
public class BoxDemo {
public static void main(String[] args) {
Box b1 = new Box();
Box b2 = new Box(3);
Box b3 = new Box(2, 4, 5);
System.out.println(b1.volume());
System.out.println(b2.volume());
System.out.println(b3.volume());
}
}6. Working:
- b1: Box() calls this(1,1,1), so the volume is 1 × 1 × 1 = 1.0.
- b2: Box(3) calls this(3,3,3), so the volume is 3 × 3 × 3 = 27.0.
- b3: the volume is 2 × 4 × 5 = 40.0.
Output: 1.0, 27.0 and 40.0, each on its own line.
Conclusion: overloaded constructors give flexible ways to create objects. Chaining with this(...) keeps all the initialisation code in one place and avoids repeating it.
4 Distinguish between method overloading and method overriding. Write Java programs to illustrate both and explain how the method to be executed is decided in each case. 10 marks
Overloading and overriding both let one method name have several versions. They differ in where the versions are written and in when the call is resolved.
1. Method overloading. Two or more methods in the same class share a name but have different parameter lists (number, type or order). A difference in return type alone is not enough.
class Calc {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
double add(double a, double b) { return a + b; }
}For an object c of Calc:
- c.add(2, 3) gives 5.
- c.add(2, 3, 4) gives 9.
- c.add(2.5, 3.5) gives 6.0.
The compiler chooses the version from the argument types. This is compile-time (static) polymorphism.
2. Method overriding. A subclass gives its own body for a method it inherits, keeping the same name and parameter list.
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override
double area() { return 3.14 * r * r; }
}
class Square extends Shape {
double s;
Square(double s) { this.s = s; }
@Override
double area() { return s * s; }
}
public class OverrideDemo {
public static void main(String[] args) {
Shape sh = new Circle(2);
System.out.println(sh.area()); // 3.14*2*2 = 12.56
sh = new Square(3);
System.out.println(sh.area()); // 3*3 = 9.0
}
}The reference type is Shape, but the JVM runs the version that belongs to the actual object at run time. This is dynamic method dispatch, or run-time polymorphism.
3. Rules for overriding:
- The name and the parameter list must be identical.
- The return type must be the same, or a subtype (covariant return).
- The access level cannot be more restrictive. For example, public cannot become default.
- final methods cannot be overridden. static methods are hidden, not overridden. private methods are not inherited.
- super.area() calls the parent's version from inside the subclass.
4. Differences:
- Place: overloading happens in one class (or is inherited into it). Overriding needs a superclass and a subclass.
- Parameters: in overloading they must differ. In overriding they must be the same.
- Binding: overloading is resolved at compile time. Overriding is resolved at run time.
- Return type: in overloading it may differ freely. In overriding it must be the same or covariant.
- Purpose: overloading offers convenience for similar operations. Overriding lets a subclass specialise inherited behaviour.
Conclusion: overloading increases readability within a class. Overriding, together with superclass references, makes run-time polymorphism possible.
5 Explain how arguments are passed to methods in Java. With a program, show the effect of passing primitive values and class objects as parameters, and explain what happens when one object is assigned to another. 10 marks
Some languages offer both call by value and call by reference. Java uses only call by value: a method always receives a copy of each argument. What is copied depends on the type of the argument.
1. Primitive arguments (int, double, char and so on). The value itself is copied into the parameter. Changing the parameter has no effect on the caller's variable.
2. Object arguments. The variable holds a reference, and that reference value is copied. The caller and the method then refer to the same object:
- If the method changes the object's fields through the parameter, the caller sees the change. This looks like call by reference.
- If the method makes the parameter point to a new object, the caller's variable is unaffected.
3. Assigning objects. b = a copies the reference. a and b then name the same object.
class Num {
int v;
Num(int v) { this.v = v; }
boolean sameAs(Num other) { // object as parameter
return this.v == other.v;
}
}
public class PassDemo {
static void change(int x) { x = 50; }
static void modify(Num n) { n.v = 50; }
static void reassign(Num n) { n = new Num(99); }
public static void main(String[] args) {
int p = 10;
change(p);
System.out.println("p = " + p);
Num a = new Num(10);
modify(a);
System.out.println("a.v = " + a.v);
reassign(a);
System.out.println("a.v = " + a.v);
Num b = a;
b.v = 75;
System.out.println("a.v = " + a.v);
System.out.println(a.sameAs(new Num(75)));
}
}4. Tracing the program:
- change(p): x gets a copy of 10 and becomes 50. p stays 10, so it prints p = 10.
- modify(a): n holds a copy of a's reference, so n.v = 50 changes the shared object. It prints a.v = 50.
- reassign(a): n is pointed at a new Num(99), but a still refers to the old object. It prints a.v = 50.
- b = a; b.v = 75: both references denote one object. It prints a.v = 75.
- sameAs compares 75 with 75 and prints true.
Conclusion: Java always passes by value. For objects the value passed is a reference, so methods can change an object's state but cannot replace the caller's object.
6 What are nested classes? Explain static nested classes, inner (member) classes, local classes and anonymous classes in Java with a single program, and state their advantages. 10 marks
A nested class is a class declared inside another class. It groups classes that are used only in one place, which improves encapsulation and readability.
1. Kinds of nested classes:
- Static nested class: declared with static. It is not tied to any outer object, so it can use only the static members of the outer class directly. It is created as new Outer.Nested().
- Inner (member) class: a non-static class at member level. Every inner object is bound to an outer object and can use all the outer members, including private ones. It is created as outerRef.new Inner().
- Local class: declared inside a method body and visible only in that method. It can use local variables that are final or effectively final.
- Anonymous class: a local class without a name, declared and instantiated in one expression. It is usually used to implement an interface or extend a class for one-time use.
2. Program:
interface Greeting { void greet(); }
class Outer {
private int x = 10;
private static int y = 20;
static class StaticNested {
void show() { System.out.println("y = " + y); }
}
class Inner {
void show() { System.out.println("x = " + x); }
}
void localDemo() {
int z = 30; // effectively final
class Local {
void show() { System.out.println("z = " + z + ", x = " + x); }
}
new Local().show();
}
}
public class NestedDemo {
public static void main(String[] args) {
Outer.StaticNested sn = new Outer.StaticNested();
sn.show();
Outer o = new Outer();
Outer.Inner in = o.new Inner();
in.show();
o.localDemo();
Greeting g = new Greeting() {
public void greet() { System.out.println("Hello from anonymous class"); }
};
g.greet();
}
}Output:
y = 20 x = 10 z = 30, x = 10 Hello from anonymous class
3. Observations:
- StaticNested reads the private static y, but it could not read x, because no Outer object exists for it.
- Inner reads the private x of the object o that created it.
- Local exists only inside localDemo().
- The anonymous class supplies greet() without ever declaring a class name.
- The compiler produces separate class files such as Outer$StaticNested.class, Outer$Inner.class, Outer$1Local.class and NestedDemo$1.class.
4. Advantages:
- Helper classes are grouped logically with the class they serve.
- Inner classes get direct access to private data, which strengthens encapsulation.
- The code is shorter for event handlers and one-time implementations.
Conclusion: nested classes let Java place a class exactly where it is needed. The choice between static, member, local and anonymous depends on whether access to an outer object is required and how widely the class is used.
Arrays, Inheritance and Interfaces
Syllabus: Declaration and initialisation of arrays; Storage of arrays in memory and accessing elements; Operations on array elements and assigning one array to another; Dynamic change of array size; Sorting arrays and searching for values; Class Arrays; Two-dimensional, varying-length and three-dimensional arrays; Arrays as vectors; Process and types of inheritance; The universal superclass Object; Inhibiting inheritance with final; Access control and inheritance; Multilevel inheritance; The keyword super; Constructors and inheritance; Method overriding and dynamic method dispatch; Abstract classes; Declaring and implementing interfaces; Multiple and nested interfaces; Inheritance of interfaces; Default and static methods in interfaces; Functional interfaces; Annotations
One-page revision summary
- A Java array is a heap object with a fixed length field; new fills it with default values (0, false or null), and an initialiser list such as {1, 2, 3} sets both the values and the length.
- Elements are accessed as a[i] for i from 0 to a.length - 1; any other index throws ArrayIndexOutOfBoundsException.
- Assigning b = a copies only the reference, and an array's size never changes after creation, so a real copy or a resized array is made with clone(), System.arraycopy or a = Arrays.copyOf(a, newLength).
- java.util.Arrays provides static methods sort, binarySearch, fill, equals, toString, copyOf, copyOfRange and asList.
- Bubble sort repeatedly swaps adjacent out-of-order pairs in O(n²) time; binary search halves a sorted range each step in O(log n) time.
- A 2-D array is an array of row arrays, so rows may have different lengths (jagged arrays); a 3-D array int[x][y][z] holds x × y × z elements.
- A 1-D numeric array can model a mathematical vector with one loop per operation: c[i] = a[i] + b[i] for addition, k × a[i] for scaling and sum += a[i] × b[i] for the dot product, so {1, 2, 3}·{4, 5, 6} = 4 + 10 + 18 = 32.
- java.util.Vector is a growable, synchronised list of objects whose legacy methods are addElement(x) to append, insertElementAt(x, i) to insert, elementAt(i) to read, removeElement(x) to delete, size() for the element count and capacity() for the allocated slots.
- A Vector built with new Vector<>() starts with capacity 10 and doubles when full, so the 11th addElement raises capacity to 20, whereas new Vector<>(5, 3) grows by its increment of 3, giving capacities 5, 8, 11.
- Inheritance uses extends; Java classes support single, multilevel and hierarchical inheritance, while multiple and hybrid inheritance are achieved through interfaces.
- Every class implicitly extends java.lang.Object, which supplies toString, equals, hashCode, getClass and clone.
- A final class cannot be extended, a final method cannot be overridden, and a final variable is a constant.
- private members are not accessible in a subclass, default members are accessible only within the same package, and protected members are also accessible in subclasses in other packages.
- super(...) must be the first statement in a constructor; if it is omitted, the compiler inserts super(), and constructors run from the top superclass down.
- Dynamic method dispatch chooses the overridden method from the actual object's type at run time, not from the reference type.
- An abstract class cannot be instantiated, may mix abstract and concrete methods, and may have constructors and fields.
- Interface variables are public static final, abstract interface methods are public, an interface may extend several interfaces, and a nested interface declared inside a class or another interface is referred to as Outer.Inner.
- Default methods give interfaces inherited method bodies; static interface methods are called only through the interface name.
- A functional interface has exactly one abstract method and is the target of a lambda; java.util.function provides Predicate, Function, Consumer and Supplier.
- Annotations such as @Override, @Deprecated, @SuppressWarnings and @FunctionalInterface are metadata; custom annotations are declared with @interface and configured with @Retention and @Target.
Learn these by heart
- Valid array indices: 0 to a.length - 1 (length is a field for arrays, but length() is a method for String).
- Binary search: mid = (low + high) / 2; it needs a sorted array and runs in O(log n); bubble sort is O(n²).
- Constructor chaining: super(...) or this(...) must be the first statement, and superclass constructors always execute first.
- Overriding rules: same signature, same or covariant return type, no weaker access, and final, static or private methods cannot be overridden.
- Interface members: fields are public static final, and abstract methods are public; a class implements many interfaces, and an interface extends many interfaces.
- Functional interface = exactly one abstract method (default and static methods allowed), and it can be implemented by a lambda.
- Array as vector: both arrays must have equal length; addition is c[i] = a[i] + b[i] and the dot product is Σ a[i] × b[i], each computed in a single loop.
- Vector vs array: an array has fixed length and can hold primitives, whereas a Vector resizes itself, holds only objects (int values are autoboxed to Integer), and size() ≤ capacity() always holds.
- Vector growth: default capacity 10 with doubling (10 → 20 → 40); with a capacityIncrement k, as in new Vector<>(5, 3), the capacity grows by k (5 → 8 → 11).
2-mark questions
1 How is a one-dimensional array declared, created and initialised in Java? Give an example. 2 marks
A declaration gives the element type followed by brackets, for example int[] marks; and creates only a reference. The new operator creates the array, fixes its length and fills it with default values: marks = new int[5]; Declaration and initialisation can be combined with a list: int[] marks = {70, 85, 90}; which has length 3.
2 What happens when one array variable is assigned to another in Java? 2 marks
The statement b = a copies only the reference. Both names then point to the same array object in the heap, so a change made through b is also seen through a. An independent copy needs a new array, made with a.clone(), Arrays.copyOf(a, a.length) or System.arraycopy(a, 0, b, 0, a.length).
3 How does the keyword final inhibit inheritance? 2 marks
A class declared final cannot be extended. For example, final class Config { } cannot have subclasses, and String is a final class in the library. A method declared final cannot be overridden in any subclass, which protects its behaviour and allows early binding. A final variable becomes a constant.
4 Why is Object called the universal superclass in Java? 2 marks
java.lang.Object is the root of every class hierarchy. A class that does not extend another class implicitly extends Object. Every object therefore inherits methods such as toString(), equals(Object), hashCode(), getClass(), clone(), wait() and notify(). A reference of type Object can refer to an object of any class.
5 What is a functional interface? Give an example. 2 marks
A functional interface has exactly one abstract method, although it may also have default and static methods. A lambda expression can implement it. Example: @FunctionalInterface interface Square { int find(int x); } followed by Square s = x -> x * x; Here s.find(4) returns 16. Runnable and Comparator are standard examples.
6 What are annotations? Name any three built-in annotations. 2 marks
Annotations are metadata attached to declarations with the @ symbol. They do not change the program's logic, but they give information to the compiler, to tools or to the runtime. Built-in examples: @Override checks that a method really overrides, @Deprecated marks an outdated element, and @SuppressWarnings("unchecked") hides chosen compiler warnings.
10-mark questions
1 Explain how arrays are declared, initialised and stored in memory in Java, and how their elements are accessed. Write a program that illustrates two-dimensional, varying-length (jagged) and three-dimensional arrays. 10 marks
An array in Java is an object that holds a fixed number of values of one type. All the values share one name and each is reached through an integer index. Because arrays are objects, they are created and stored differently from arrays in C.
1. Declaration: int[] a; or int a[]; creates only a reference variable. No size is written here, and no memory is given to the elements yet.
2. Creation: a = new int[4]; allocates four int slots in the heap. Each slot gets a default value: 0 for numbers, false for boolean and null for references.
3. Initialisation: elements can be assigned one at a time (a[0] = 5;) or through an initialiser list, int[] a = {5, 10, 15, 20}; where the compiler counts the length.
4. Storage and access: a local reference variable lives on the stack. The array object, with its length field and its contiguous elements, lives in the heap. Element a[i] is valid for i from 0 to a.length - 1. Any other index throws ArrayIndexOutOfBoundsException at run time.
5. Two-dimensional arrays: Java builds a 2-D array as an array of arrays, for example int[][] m = new int[2][3]; Here m.length gives the number of rows and m[i].length gives the number of columns in row i.
6. Varying-length (jagged) arrays: only the first dimension is given at first. Each row is then created separately with its own length.
7. Three-dimensional arrays: int[][][] c = new int[2][2][2]; holds 2 × 2 × 2 = 8 elements, accessed as c[i][j][k].
public class ArrayDemo {
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}};
int[][] jag = new int[3][];
jag[0] = new int[1];
jag[1] = new int[2];
jag[2] = new int[3];
int[][][] cube = new int[2][2][2];
int sum = 0;
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
sum += m[i][j];
System.out.println("Sum of m = " + sum);
for (int i = 0; i < jag.length; i++)
System.out.println("Row " + i + " length = " + jag[i].length);
cube[1][0][1] = 9;
System.out.println("cube[1][0][1] = " + cube[1][0][1]);
}
}Output:
- Sum of m = 21 (because 1+2+3+4+5+6 = 21)
- Row 0 length = 1
- Row 1 length = 2
- Row 2 length = 3
- cube[1][0][1] = 9
Conclusion: Java arrays are heap objects that are reached through references and carry their own length. A multidimensional array is simply an array of references to other arrays, which is why jagged arrays are possible.
2 Write a Java program to sort an integer array using bubble sort and then search for a value using binary search. Trace both on the data {42, 17, 8, 23, 4}. Also explain the important methods of the class java.util.Arrays and how the size of an array can be changed dynamically. 10 marks
Sorting puts the elements in order. Searching finds the position of a key. Binary search needs a sorted array.
1. Bubble sort: adjacent pairs are compared and swapped when they are out of order. After each pass the largest remaining element settles at the end.
2. Trace on {42, 17, 8, 23, 4}:
- Pass 1: 17 8 23 4 42
- Pass 2: 8 17 4 23 42
- Pass 3: 8 4 17 23 42
- Pass 4: 4 8 17 23 42
3. Binary search for key 23 in {4, 8, 17, 23, 42}:
- low = 0, high = 4, mid = 2. a[2] = 17 < 23, so low = 3.
- mid = (3+4)/2 = 3. a[3] = 23, so the key is found at index 3.
import java.util.Arrays;
public class SortSearch {
static void bubbleSort(int[] a) {
for (int p = 0; p < a.length - 1; p++)
for (int j = 0; j < a.length - 1 - p; j++)
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
static int binarySearch(int[] a, int key) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] a = {42, 17, 8, 23, 4};
bubbleSort(a);
System.out.println(Arrays.toString(a));
System.out.println("23 found at index " + binarySearch(a, 23));
a = Arrays.copyOf(a, 8);
System.out.println(Arrays.toString(a));
}
}Output:
- [4, 8, 17, 23, 42]
- 23 found at index 3
- [4, 8, 17, 23, 42, 0, 0, 0]
4. Class Arrays (java.util) offers static utility methods:
- sort(a): sorts the whole array in ascending order.
- binarySearch(a, key): returns the index of key in a sorted array. If the key is absent it returns -(insertion point) - 1.
- fill(a, v): stores v in every element.
- equals(a, b): true if both arrays have the same length and equal elements.
- toString(a): returns a readable string form of the array.
- copyOf(a, n) and copyOfRange(a, from, to): return new arrays.
- asList(...): gives a fixed-size List view.
5. Dynamic change of size: an array's length is fixed once it is created. To grow or shrink it, create a new array of the required length, copy the old elements into it, and assign the new reference to the old variable. The statement a = Arrays.copyOf(a, 8) does all three steps, and the extra slots receive default values. The old array becomes garbage. System.arraycopy can do the same copying by hand.
Conclusion: Bubble sort takes O(n²) comparisons and binary search takes only O(log n). The Arrays class supplies tested versions of these operations.
3 What is inheritance? Explain the types of inheritance in Java and how access specifiers control what a subclass inherits. Illustrate multilevel inheritance with a program. 10 marks
Inheritance is the process by which a new class (the subclass) acquires the fields and methods of an existing class (the superclass) through the keyword extends. It supports code reuse, extension of behaviour and an is-a relationship.
1. Process: class B extends A { } makes B inherit every accessible member of A. B can add new members and can override methods it inherits.
2. Types of inheritance:
- Single: one subclass extends one superclass.
- Multilevel: a chain in which C extends B and B extends A.
- Hierarchical: several subclasses extend the same superclass.
- Multiple: one class has two direct parents. Java does not allow this with classes, to avoid diamond ambiguity, but a class may implement several interfaces.
- Hybrid: a mixture of the above types, achieved in Java with interfaces.
3. Access control and inheritance:
- private: never accessible in a subclass. The member exists in the object but can be reached only through the superclass's own methods.
- default (no specifier): accessible in a subclass only if the subclass is in the same package.
- protected: accessible in the same package and in subclasses in any package.
- public: accessible everywhere.
4. Program showing multilevel inheritance:
class Person {
protected String name = "Ravi";
private String pan = "XXXX"; // hidden from subclasses
}
class Employee extends Person {
protected double basic = 30000;
}
class Manager extends Employee {
double hra = 6000;
void show() {
double pay = basic + hra;
System.out.println(name + " earns " + pay);
// System.out.println(pan); compile-time error: private
}
}
public class MultiLevel {
public static void main(String[] args) {
new Manager().show();
}
}Output: Ravi earns 36000.0
5. Explanation: Manager uses name from Person (two levels up) and basic from Employee (one level up), because both are protected. The private field pan cannot be referred to in Manager.
Conclusion: Java supports single, multilevel and hierarchical inheritance through classes, and multiple and hybrid inheritance through interfaces. The access specifiers decide which inherited members a subclass may actually use.
4 Explain the uses of the keyword super. Describe the order in which constructors are executed in a multilevel hierarchy, with a suitable program and its output. 10 marks
When a subclass object is created, the superclass part of that object must be initialised first. The keyword super lets the subclass refer to its immediate superclass, both to call its constructor and to reach members that the subclass has hidden.
1. Uses of super:
- super(arguments): calls a constructor of the immediate superclass. It must be the first statement in the subclass constructor.
- super.field: reaches a superclass field that is hidden by a subclass field of the same name.
- super.method(): calls the superclass version of a method that the subclass has overridden.
2. Constructors and inheritance:
- Constructors are not inherited, but every constructor calls a superclass constructor.
- If the programmer writes no super(...) call, the compiler inserts super() automatically.
- If the superclass has no no-argument constructor, the subclass must call super(arguments) explicitly; otherwise compilation fails.
- this(...) and super(...) cannot both appear in the same constructor, because each must be the first statement.
3. Order of execution: constructors run from the topmost superclass down to the class being instantiated (Object, then A, then B, then C), because each constructor first calls the one above it.
class A {
int x = 10;
A() { System.out.println("Constructor of A"); }
void show() { System.out.println("show() of A"); }
}
class B extends A {
int x = 20; // hides A's x
B(int v) {
super();
x = v;
System.out.println("Constructor of B");
}
void show() {
super.show();
System.out.println("show() of B, x = " + x + ", super.x = " + super.x);
}
}
class C extends B {
C() {
super(30);
System.out.println("Constructor of C");
}
}
public class SuperDemo {
public static void main(String[] args) {
C obj = new C();
obj.show();
}
}Output:
- Constructor of A
- Constructor of B
- Constructor of C
- show() of A
- show() of B, x = 30, super.x = 10
4. Explanation: new C() calls super(30), which runs B's constructor. B's constructor calls super(), which runs A's constructor first. B then sets its own x to 30. Inside B's show(), super.show() runs A's version, and super.x reads A's hidden field, which is 10.
Conclusion: super connects a subclass to its parent for construction, for hidden fields and for overridden methods. Constructor chaining guarantees that an object is always built from the top of the hierarchy down.
5 What is method overriding? Explain dynamic method dispatch and abstract classes with a suitable program. 10 marks
Polymorphism lets one interface stand for many forms. In Java, run-time polymorphism is achieved through method overriding together with dynamic method dispatch. Abstract classes are often used to define the common methods that subclasses must override.
1. Method overriding: a subclass supplies a new body for an inherited method with the same name and the same parameter list. The rules are:
- The return type must be the same or a subtype (a covariant return).
- The access level cannot be more restrictive, for example public cannot become protected.
- final, static and private methods cannot be overridden.
- The overriding method cannot throw broader checked exceptions.
- @Override is used so that the compiler checks the rules.
2. Dynamic method dispatch: a superclass reference variable can refer to a subclass object. When an overridden method is called through such a reference, the JVM decides at run time which version to execute. It uses the type of the object, not the type of the reference. Overloading, by contrast, is resolved at compile time.
3. Abstract class: a class declared abstract cannot be instantiated. It may contain abstract methods (declared without a body) as well as concrete methods, fields and constructors. A subclass must override every abstract method, or else be declared abstract itself. References of an abstract type are allowed.
abstract class Shape {
String name;
Shape(String n) { name = n; }
abstract double area();
void display() { System.out.println(name + " area = " + area()); }
}
class Circle extends Shape {
double r;
Circle(double r) { super("Circle"); this.r = r; }
@Override double area() { return 3.14 * r * r; }
}
class Rectangle extends Shape {
double l, b;
Rectangle(double l, double b) { super("Rectangle"); this.l = l; this.b = b; }
@Override double area() { return l * b; }
}
public class Dispatch {
public static void main(String[] args) {
Shape s; // Shape s = new Shape("x"); is illegal
s = new Circle(2);
s.display();
s = new Rectangle(4, 5);
s.display();
}
}Output:
- Circle area = 12.56 (3.14 × 2 × 2)
- Rectangle area = 20.0 (4 × 5)
4. Explanation: display() is written once, in Shape. When it calls area(), the call is dispatched at run time to Circle's version first and to Rectangle's version afterwards, even though the reference s is of type Shape.
Conclusion: Overriding provides class-specific behaviour, and dynamic dispatch chooses that behaviour at run time. Abstract classes force subclasses to provide it, which keeps code general and extensible.
6 Explain how interfaces are declared and implemented in Java. Discuss multiple interfaces, nested interfaces, inheritance of interfaces, and default and static methods, with a program. 10 marks
An interface is a reference type that states what a class must do without saying how. It is Java's way of giving a class several parent types without the problems of multiple class inheritance.
1. Declaring: an interface is declared with the keyword interface. Its abstract methods are implicitly public abstract, and its variables are implicitly public static final (constants). An interface has no constructors and cannot be instantiated.
2. Implementing: class X implements I must give public bodies to all the abstract methods of I; otherwise X must be declared abstract. A reference of type I can hold an X object.
3. Multiple interfaces: a class may implement several interfaces, as in class X implements I1, I2. There is no ambiguity, because abstract methods carry no bodies.
4. Inheritance of interfaces: an interface can extend one or more interfaces. A class that implements the child interface must implement the methods of the whole chain.
5. Nested interfaces: an interface declared inside a class or another interface is referred to as Outer.Inner. An interface nested in an interface is implicitly public and static.
6. Default methods (Java 8): they have a body, are inherited, and may be overridden. They let new methods be added to an interface without breaking existing classes. If two interfaces provide the same default method, the class must override it, and it may call I1.super.m().
7. Static methods: they belong to the interface itself, are called as InterfaceName.method(), and are not inherited by implementing classes.
interface Printable {
void print();
default void header() { System.out.println("--- Report ---"); }
static String version() { return "v1"; }
}
interface Storable { void save(); }
interface Document extends Printable, Storable { int MAX_PAGES = 100; }
class Account {
interface Validator { boolean check(double amt); }
}
class Invoice implements Document, Account.Validator {
public void print() { System.out.println("Printing invoice"); }
public void save() { System.out.println("Saving invoice"); }
public boolean check(double amt) { return amt > 0; }
}
public class InterfaceDemo {
public static void main(String[] args) {
Invoice inv = new Invoice();
inv.header();
inv.print();
inv.save();
System.out.println(Printable.version() + " " + Document.MAX_PAGES + " " + inv.check(500));
}
}Output:
- --- Report ---
- Printing invoice
- Saving invoice
- v1 100 true
Conclusion: Interfaces give Java multiple inheritance of type through implements and extends. Nesting groups related contracts together, and default and static methods let an interface evolve while staying compatible with existing classes.
Packages, Java Library, Exception Handling and I/O
Syllabus: Defining packages and importing packages and classes; Path and class path; Access control with packages; Packages in Java SE; The java.lang package and class Object; Enumeration; Class Math; Wrapper classes, auto-boxing and auto-unboxing; java.util classes and interfaces; The Formatter and Random classes; The time package and class Instant; Formatting dates and times; The TemporalAdjusters class; Hierarchy of standard exception classes; The keywords throw and throws; try, catch and finally blocks; Multiple catch clauses; Class Throwable; Checked and unchecked exceptions; The Java I/O API and standard I/O streams; Byte streams and character streams; The Scanner class; Files in Java
One-page revision summary
- A package statement must be the first statement of a source file (only comments may come before it), the folder structure must match the package name, and javac -d . creates those folders.
- Classes are imported singly (import p.C;), on demand (import p.*;) or statically (import static p.C.member;), and java.lang is imported automatically.
- PATH locates the JDK tools, while CLASSPATH or the -cp option locates user classes and JAR files.
- Important Java SE packages include java.lang, java.util, java.io, java.nio.file, java.time, java.net, java.sql, java.awt and javax.swing.
- Object is the root class and supplies equals, hashCode, toString, getClass, clone, wait, notify and notifyAll to every class.
- An enum is a type-safe set of constants that implicitly extends java.lang.Enum and provides values(), valueOf() and ordinal().
- Math is a final class of static methods such as sqrt, pow, abs, max, min, ceil, floor, round and random, plus the constants PI and E.
- Every primitive has a wrapper class, and the compiler boxes and unboxes automatically when primitives and wrappers are mixed.
- java.util provides the collection interfaces (List, Set, Queue, Map) and classes (ArrayList, HashSet, HashMap, TreeMap) plus utilities such as Scanner, Random and Formatter.
- Formatter writes formatted text using specifiers of the form %[flags][width][.precision]conversion, and Random produces pseudo-random values that repeat when the same seed is used.
- The java.time classes are immutable, so methods such as plusDays or minusMonths return new objects; LocalDate, LocalTime and LocalDateTime hold values without a time zone, ZonedDateTime adds a zone, and Instant is a machine timestamp.
- Duration measures time-based amounts in seconds and nanoseconds, as in Duration.between(t1, t2), while Period measures date-based amounts in years, months and days, as in Period.between(d1, d2).
- DateTimeFormatter.ofPattern builds a formatter from case-sensitive letters such as dd (day), MM (month), yyyy (year), HH (hour 0-23), mm (minute) and ss (second), and ready-made constants such as DateTimeFormatter.ISO_LOCAL_DATE and ISO_LOCAL_DATE_TIME are also provided.
- A pattern may use only fields the object holds, so a LocalDateTime is formatted with dt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")) and read back with LocalDateTime.parse(text, f), whereas a LocalDate needs a date-only pattern such as "dd-MM-yyyy" with LocalDate.parse(text, f), since a time letter on a LocalDate throws UnsupportedTemporalTypeException.
- TemporalAdjusters (in java.time.temporal) supplies adjusters applied with date.with(...): if d is a Wednesday, d.with(TemporalAdjusters.next(DayOfWeek.MONDAY)) gives the Monday five days later, nextOrSame returns d itself when d already is the requested day, and d.with(TemporalAdjusters.lastDayOfMonth()) gives the last date of d's month.
- Throwable has two branches: Error for serious JVM problems and Exception for recoverable conditions, with RuntimeException as the unchecked sub-branch of Exception.
- Catch clauses are tried in order, so subclasses must come before superclasses, and multi-catch with | handles unrelated types in one block.
- Byte streams (InputStream/OutputStream) carry raw bytes, while character streams (Reader/Writer) carry Unicode text, and InputStreamReader converts between the two.
- Scanner(System.in) reads tokens with nextInt, nextDouble, next and nextLine, while the File class handles path names, existence checks, size, creation and deletion.
Learn these by heart
- Access visibility: private = same class only; default = same package; protected = same package + subclasses elsewhere; public = everywhere.
- Checked exceptions = Exception and its subclasses except RuntimeException (they must be caught or declared). Unchecked = RuntimeException + Error.
- finally always executes after try/catch; only System.exit() or a JVM crash stops it.
- Random integer in the range a..b: r.nextInt(b - a + 1) + a; nextDouble() returns a value in [0.0, 1.0).
- Source file order: package statement → import statements → class/interface declarations.
- Stream roots: InputStream/OutputStream (bytes) and Reader/Writer (characters); read() returns -1 at end of stream.
- Pattern letters are case-sensitive: MM = month but mm = minute, HH = hour 0-23 but hh = hour 1-12 (used with a for AM/PM).
- next(DayOfWeek) always moves forward to a later date, while nextOrSame(DayOfWeek) keeps the same date if it already falls on that day.
2-mark questions
1 What is a package in Java? How is a class placed in a package and used from another file? 2 marks
A package is a named group of related classes and interfaces. It acts as a namespace and as an access boundary. A class is placed in a package by writing package mypack; as the first statement of its source file. Another file uses it with import mypack.ClassName; or import mypack.*;
2 Distinguish between PATH and CLASSPATH. 2 marks
PATH is an operating-system variable that lists the folders searched for executable programs such as javac and java. CLASSPATH tells the compiler and the JVM where to look for user .class files, packages and JAR files, for example set CLASSPATH=.;D:\work. The -cp option overrides it for a single command.
3 What are auto-boxing and auto-unboxing? Give an example. 2 marks
Auto-boxing is the compiler's automatic conversion of a primitive value into its wrapper object, for example Integer i = 10;. Auto-unboxing is the reverse conversion, for example int n = i + 5; which gives 15. These conversions let primitives be stored in collections such as ArrayList<Integer> without calling valueOf() or intValue().
4 Differentiate between throw and throws. 2 marks
throw is a statement written inside a method body. It raises one exception object explicitly, for example throw new ArithmeticException("bad input");. throws is a clause written in a method header. It declares the checked exceptions the method may pass on to its caller, for example void read() throws IOException.
5 Distinguish between checked and unchecked exceptions with one example each. 2 marks
Checked exceptions are subclasses of Exception other than RuntimeException, for example IOException. The compiler verifies them, so they must be caught or declared with throws. Unchecked exceptions are RuntimeException, Error and their subclasses, for example NullPointerException. The compiler does not check them, and they usually signal programming bugs.
6 What does the class Instant in java.time represent? How is the current instant obtained? 2 marks
Instant represents a single moment on the UTC timeline. It is stored as seconds plus nanoseconds counted from the epoch 1970-01-01T00:00:00Z. Instant.now() returns the current moment. Methods such as plusSeconds() and Duration.between(i1, i2) are used to shift instants or measure the time between them. Instant objects are immutable. The other main java.time classes are LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration and Period, and they are immutable too.
10-mark questions
1 Explain how packages are defined and imported in Java. Discuss path and class path, access control with packages and the main packages of Java SE. 10 marks
A package groups related classes and interfaces under one name. Packages prevent name clashes, organise large programs and add a level of access control.
1. Defining a package The package statement must be the first statement of the file. The folder structure must match the package name.
// File: mypack/shapes/Circle.java
package mypack.shapes;
public class Circle {
private double r;
public Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}Compile it with javac -d . Circle.java. The -d option creates the folders mypack/shapes and stores Circle.class there.
2. Importing packages and classes
- Single-type import: import mypack.shapes.Circle;
- On-demand import: import mypack.shapes.*; (this imports classes only, not sub-packages)
- Fully qualified name without any import: new mypack.shapes.Circle(2)
- Static import of members: import static java.lang.Math.PI;
- The package java.lang is imported automatically.
import mypack.shapes.Circle;
public class Test {
public static void main(String[] args) {
System.out.println(new Circle(1).area()); // 3.141592653589793
}
}3. Path and class path PATH lets the operating system find the tools javac and java. CLASSPATH lists the folders and JAR files where the compiler and the JVM search for classes, for example set CLASSPATH=.;D:\work. The option java -cp D:\work Test overrides it for one run. For each class path entry, the JVM turns the package name mypack.shapes into the relative folder mypack/shapes.
4. Access control with packages
- private: visible only inside the same class.
- default (no modifier): visible in the same class and in every class of the same package.
- protected: visible in the same package, and also in subclasses in other packages through inheritance.
- public: visible everywhere.
A class meant for use outside its package must therefore be public, and so must its constructors and methods, as Circle is above.
5. Packages in Java SE
- java.lang: Object, String, Math, wrapper classes, Thread
- java.util: collections, Scanner, Random, Formatter
- java.io and java.nio.file: streams and files
- java.time: dates, times and Instant
- java.net, java.sql, java.awt and javax.swing
Conclusion: Packages give unique names, a matching folder structure and controlled visibility. CLASSPATH lets the compiler and the JVM locate them, and the standard Java SE packages are used through the same import mechanism.
2 Describe the java.lang package with emphasis on class Object, enumerations, class Math and wrapper classes with auto-boxing. Illustrate with a program. 10 marks
java.lang holds the classes that every Java program needs. It is imported automatically into every source file.
1. Class Object Object is the root of the class hierarchy, so every class inherits its methods:
- equals(Object o): checks logical equality (by default it compares references).
- hashCode(): returns an int hash; it must agree with equals.
- toString(): returns a text form (by default the class name, @ and the hash in hex).
- getClass(): returns the runtime Class object.
- clone(): a protected method that copies the object (the class must implement Cloneable).
- wait(), notify(), notifyAll(): used for thread coordination.
2. Enumeration An enum is a special class with a fixed set of named constants, for example enum Level { LOW, MEDIUM, HIGH }. Every enum implicitly extends java.lang.Enum. It provides values(), valueOf(String) and ordinal(). An enum can have fields, constructors and methods, and it can be used in switch statements.
3. Class Math Math is a final class whose members are all static. Examples:
- sqrt(x)
- pow(a, b)
- abs(x)
- max(a, b) and min(a, b)
- ceil(x), floor(x) and round(x)
- random() and the trigonometric functions
- the constants PI and E
4. Wrapper classes Each primitive type has a wrapper class:
- byte–Byte, short–Short, int–Integer, long–Long
- float–Float, double–Double, char–Character, boolean–Boolean
Wrappers provide parsing (Integer.parseInt("25")), conversion (Integer.toBinaryString(5)) and constants (Integer.MAX_VALUE). Auto-boxing converts a primitive to its wrapper automatically, and auto-unboxing converts it back.
enum Level { LOW, MEDIUM, HIGH }
public class LangDemo {
public static void main(String[] args) {
Integer boxed = 25; // auto-boxing
int sum = boxed + 5; // auto-unboxing, sum = 30
System.out.println(Math.sqrt(sum - 5));
System.out.println(Math.max(4, 9) + " " + Math.pow(2, 3));
for (Level l : Level.values())
System.out.println(l + " " + l.ordinal());
Object o = "hello";
System.out.println(o.getClass().getName());
}
}5. Output, step by step
- sum - 5 = 25, and sqrt(25) = 5.0, so the first line is 5.0.
- max(4, 9) = 9 and pow(2, 3) = 8.0, so the second line is 9 8.0.
- The loop prints LOW 0, MEDIUM 1 and HIGH 2 on separate lines.
- The last line is java.lang.String, because getClass() reports the runtime type of the object, not the declared type Object.
Conclusion: java.lang supplies the common root class Object, type-safe enums, ready-made mathematical functions and wrapper classes. Boxing and unboxing let primitives and objects work together.
3 Explain the hierarchy of standard exception classes in Java. Describe class Throwable and its methods, and distinguish checked from unchecked exceptions. 10 marks
An exception is an abnormal event that breaks the normal flow of a program. In Java every exception is an object of a class derived from Throwable. The class hierarchy decides how each exception must be handled.
1. The hierarchy
Diagram in words: a tree with Object at the top. Throwable has an arrow labelled extends pointing up to Object. Two boxes, Error and Exception, each have an extends arrow up to Throwable. Under Error: VirtualMachineError (with OutOfMemoryError and StackOverflowError below it) and AssertionError. Under Exception: IOException (with FileNotFoundException and EOFException below it), ClassNotFoundException, InterruptedException, SQLException and RuntimeException. Under RuntimeException: ArithmeticException, NullPointerException, ClassCastException, IllegalArgumentException (with NumberFormatException below it) and IndexOutOfBoundsException (with ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException below it). The Error subtree and the RuntimeException subtree are labelled unchecked. All other Exception subclasses are labelled checked.
2. Error and Exception
- Error describes serious problems inside the JVM, such as running out of memory. Programs normally do not catch these.
- Exception describes conditions that a program can reasonably catch and recover from.
3. Class Throwable Throwable is the superclass of everything that can be used with throw or catch.
Constructors:
- Throwable()
- Throwable(String message)
- Throwable(String message, Throwable cause)
- Throwable(Throwable cause)
Important methods:
- getMessage(): returns the detail message.
- toString(): returns the class name followed by the message.
- printStackTrace(): prints the exception and the chain of method calls to System.err.
- getStackTrace(): returns the stack frames as an array.
- getCause() and initCause(): read or set the underlying cause (exception chaining).
- addSuppressed() and getSuppressed(): record exceptions suppressed in try-with-resources.
try {
Object s = "abc";
Integer n = (Integer) s;
} catch (ClassCastException e) {
System.out.println(e.getClass().getName()); // java.lang.ClassCastException
e.printStackTrace();
}4. Checked versus unchecked
- Checked exceptions are found at compile time. The compiler forces the programmer to catch them or declare them with throws. Example: new FileReader("a.txt") without handling gives the error unreported exception FileNotFoundException; must be caught or declared to be thrown.
- Unchecked exceptions are RuntimeException, Error and their subclasses. They are not checked by the compiler and usually come from logic bugs, such as dividing by zero or using a null reference.
- Checked exceptions model external failures (files, network, database). Unchecked exceptions model programming mistakes.
Conclusion: The single root Throwable gives every exception a message, a cause and a stack trace. The split into checked and unchecked tells the programmer which failures the compiler will insist on handling.
4 Explain try, catch and finally blocks, multiple catch clauses and the keywords throw and throws with a complete Java program, including a user-defined exception. 10 marks
Exception handling separates error-handling code from normal code. Java provides five keywords for this: try, catch, finally, throw and throws.
1. The roles of the blocks
- try: encloses statements that may raise an exception. Once an exception occurs, the remaining statements in the try block are skipped.
- catch(Type e): handles an exception of the given type or any of its subclasses.
- finally: always runs, whether or not an exception occurred and even if the try block returns. Only System.exit() or a JVM crash prevents it. It is used to release resources.
- A try must be followed by at least one catch or a finally block, unless it is a try-with-resources.
2. Multiple catch clauses The catch clauses are examined from top to bottom, and only the first matching one runs. A subclass must be caught before its superclass; otherwise the compiler reports that the exception has already been caught. Since Java 7, one clause can catch unrelated types with a multi-catch: catch (ArithmeticException | NullPointerException e).
3. throw and throws
- throw new X(...) raises an exception explicitly.
- throws in a method header declares checked exceptions that callers must handle.
class LowBalanceException extends Exception {
LowBalanceException(String msg) { super(msg); }
}
public class Bank {
static void withdraw(int bal, int amt) throws LowBalanceException {
if (amt > bal)
throw new LowBalanceException("Need " + (amt - bal) + " more");
System.out.println("Withdrawn " + amt);
}
public static void main(String[] args) {
int[] a = {10, 20, 30};
int d = 0;
try {
System.out.println(a[1] / d);
System.out.println(a[5]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index");
} catch (Exception e) {
System.out.println("Other: " + e);
} finally {
System.out.println("finally runs");
}
try {
withdraw(500, 800);
} catch (LowBalanceException e) {
System.out.println(e.getMessage());
}
}
}4. Tracing the execution
- a[1] / d is 20 / 0, which raises ArithmeticException. The line a[5] is never reached.
- The first catch matches and prints Arithmetic: / by zero.
- The finally block prints finally runs.
- withdraw(500, 800) finds 800 > 500 and throws the custom checked exception with the message Need 300 more. That message is printed in main.
Final output: Arithmetic: / by zero finally runs Need 300 more
Conclusion: try marks the risky code, the ordered catch clauses deal with specific failures, and finally guarantees clean-up. throw and throws let methods report their own error conditions, including user-defined checked exceptions.
5 Describe the important classes and interfaces of java.util. Explain the Formatter and Random classes in detail with a program and its output. 10 marks
The java.util package contains utility classes and the Collections Framework. Almost every non-trivial Java program uses something from it.
1. Important interfaces
- Collection: the root interface for groups of objects.
- List: an ordered collection that allows duplicates.
- Set: a collection without duplicates; SortedSet keeps its elements sorted.
- Queue and Deque: FIFO and double-ended access.
- Map: key–value pairs.
- Iterator and ListIterator: step through a collection.
- Comparator: defines a custom ordering.
2. Important classes
- ArrayList and LinkedList implement List.
- HashSet and TreeSet implement Set.
- HashMap and TreeMap implement Map.
- PriorityQueue and ArrayDeque implement queues.
- Collections and Arrays provide static helpers such as sort and binarySearch.
- Objects, Optional, Scanner, StringTokenizer, Date, Calendar, Formatter, Random and UUID are further utility classes.
3. Class Formatter Formatter builds formatted text, much like printf, into a destination such as a StringBuilder, a file or a stream. Its general specifier is %[flags][width][.precision]conversion.
- Conversions: %d (integer), %f (decimal), %e (scientific), %s (string), %c (character), %b (boolean), %x (hexadecimal), %n (newline), %% (a percent sign).
- Flags: - (left-justify), 0 (pad with zeros), + (always show the sign), , (group digits).
A Formatter should be closed after use. String.format and System.out.printf use the same rules.
4. Class Random Random generates pseudo-random numbers using a linear congruential algorithm that the Java API fixes exactly, so a given seed produces the same sequence on every JVM.
- new Random() uses a seed derived from the current time.
- new Random(seed) gives the same sequence on every run, which is useful for testing.
- Methods: nextInt() returns any int; nextInt(n) returns 0 to n-1; nextDouble() returns a value in [0.0, 1.0); nextBoolean(); nextLong(); nextGaussian() (mean 0, standard deviation 1).
- A value in the range a..b is obtained with r.nextInt(b - a + 1) + a.
import java.util.*;
public class UtilDemo {
public static void main(String[] args) {
Formatter f = new Formatter();
f.format("%-6s|%4d|%7.2f", "Ravi", 21, 87.456);
System.out.println(f);
f.close();
Random r = new Random(42);
List<Integer> dice = new ArrayList<>();
for (int i = 0; i < 5; i++)
dice.add(r.nextInt(6) + 1);
Collections.sort(dice);
System.out.println(dice);
}
}5. Working out the output
- %-6s pads Ravi (4 characters) with 2 spaces on the right, giving "Ravi ".
- %4d puts 2 spaces before 21, giving " 21".
- %7.2f rounds 87.456 to 87.46 (5 characters) and puts 2 spaces before it.
- The first line is therefore: Ravi | 21| 87.46
- nextInt(6) + 1 gives values from 1 to 6. With seed 42 the five values generated, in order, are 3, 4, 1, 3, 1.
- Collections.sort arranges them in ascending order, so the second line is [1, 1, 3, 3, 4], and it is exactly the same on every run because the seed is fixed.
Output:
Ravi | 21| 87.46
[1, 1, 3, 3, 4]Conclusion: java.util supplies the collection interfaces and classes. Formatter gives precise control over text layout, and Random provides repeatable or time-seeded random data.
6 Explain the Java I/O API: standard I/O streams, byte streams versus character streams, the Scanner class and file handling with class File. Write a program that reads input from the keyboard, writes it to a file, reads it back and copies the file. 10 marks
Java performs input and output through streams. A stream is an ordered sequence of data flowing from a source to a destination. The classes are in java.io, with newer file utilities in java.nio.file.
1. Standard I/O streams The class System provides three streams that are open when the program starts:
- System.in: an InputStream connected to the keyboard.
- System.out: a PrintStream connected to the console.
- System.err: a PrintStream for error messages.
2. Byte streams and character streams
- Byte streams handle raw 8-bit data such as images and class files. Their abstract roots are InputStream and OutputStream.
- Character streams handle 16-bit Unicode text and take care of character encoding. Their abstract roots are Reader and Writer.
The figure shows the main classes only. Other byte streams are ObjectInputStream and ObjectOutputStream, which extend InputStream and OutputStream, and DataInputStream, BufferedOutputStream and DataOutputStream, which extend the Filter streams. BufferedWriter and PrintWriter are separate classes and each extends Writer.
3. Scanner class java.util.Scanner splits its input into tokens. Its methods include nextInt(), nextDouble(), next(), nextLine() and hasNextInt(). Note: after nextInt(), the next call to nextLine() returns the rest of the current line, which may be empty.
4. Class File A File object represents a path name, not the contents of the file. Useful methods:
- exists(), getName(), length()
- createNewFile(), delete(), mkdir()
- isDirectory(), list()
import java.io.*;
import java.util.Scanner;
public class FileDemo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a line: ");
String line = sc.nextLine();
File f = new File("notes.txt");
try (FileWriter fw = new FileWriter(f)) { // character output
fw.write(line + "\n");
}
System.out.println(f.getName() + " size: " + f.length());
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String s;
while ((s = br.readLine()) != null)
System.out.println("Read back: " + s);
}
try (FileInputStream in = new FileInputStream(f); // byte copy
FileOutputStream out = new FileOutputStream("copy.txt")) {
int b;
while ((b = in.read()) != -1) out.write(b);
}
}
}5. Sample run Suppose the user types hello.
- The file then holds hello plus a newline, which is 6 bytes in an ASCII-compatible encoding, so the program prints notes.txt size: 6.
- The second line printed is Read back: hello.
- copy.txt then holds the same 6 bytes, copied one by one until read() returns -1.
- try-with-resources closes every stream automatically.
Conclusion: Byte streams handle binary data and character streams handle text. Scanner makes reading input simple, and File together with the stream classes provides complete file input and output.
Strings, Multithreading, JDBC and JavaFX
Syllabus: Interface CharSequence and class String; Extracting characters from strings; Comparing, modifying and searching strings; Class StringBuffer; Need for multiple threads and multithreading on multi-core processors; The Thread class and the main thread; Creating new threads; Thread states; Thread priority; Synchronization; Deadlock and race situations; Inter-thread communication; Suspending, resuming and stopping threads; JDBC architecture; Installing MySQL and MySQL Connector/J and setting up JDBC; Establishing JDBC database connections; The ResultSet interface; JavaFX Scene Builder and app window structure; Displaying text and images in JavaFX; Event handling and mouse events; Laying out nodes in the scene graph
One-page revision summary
- CharSequence is implemented by String, StringBuffer and StringBuilder and declares length(), charAt(), subSequence() and toString().
- String objects are immutable and literals share the string constant pool; equals() compares contents while == compares references.
- StringBuffer is a mutable, synchronized character sequence with append, insert, delete, replace and reverse, while StringBuilder is its faster unsynchronized counterpart.
- Multithreading keeps programs responsive, overlaps computation with I/O, and on multi-core processors lets threads run truly in parallel on separate cores instead of being time-sliced.
- The JVM creates the main thread to run main(), and Thread.currentThread() returns a reference to the thread that is currently executing.
- Threads are created by extending Thread or by implementing Runnable (preferred), and they always begin with start(), not run().
- Thread.State defines six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.
- Thread priorities range from 1 to 10 (default 5), are only scheduling hints, and are set with setPriority().
- synchronized methods and blocks lock an object's monitor so that only one thread at a time runs a critical section, which prevents race conditions.
- Deadlock is a cycle of threads each holding a lock that another needs, and it is avoided by acquiring locks in a fixed order.
- wait(), notify() and notifyAll() let threads cooperate, as in a producer–consumer buffer, and must be called while holding the object's lock.
- suspend() is deprecated because a suspended thread keeps every lock it holds, causing deadlock if the resuming thread needs one; resume() exists only to pair with it; stop() abruptly releases all locks, leaving shared objects half-updated.
- The safe replacement uses volatile boolean flags checked in run(): a suspend request sets a flag so run() calls wait() in a synchronized block, resume clears it and calls notify(), and stop sets a stop flag (plus interrupt()) so run() returns normally.
- JDBC setup for MySQL means installing MySQL Server, adding the Connector/J jar to the classpath, and using driver class com.mysql.cj.jdbc.Driver with a URL like jdbc:mysql://localhost:3306/dbname.
- A connection is obtained with DriverManager.getConnection(url, user, password), and PreparedStatement with ? placeholders is used for parameterised, injection-safe queries.
- A ResultSet cursor starts before the first row, next() moves it forward, and scrollable result sets support previous(), first(), last() and absolute(n).
- JavaFX Scene Builder designs interfaces visually and saves them as FXML, which FXMLLoader loads into a scene and links to a controller through @FXML fields.
- Text is shown with Label or Text nodes and images with Image plus ImageView.
- Events are handled by registering handlers such as setOnAction, setOnMouseClicked, setOnMouseEntered and setOnMouseDragged, and the MouseEvent gives coordinates and button details.
- Layout panes such as HBox, VBox, BorderPane, GridPane, FlowPane and StackPane position the nodes of the scene graph automatically.
Learn these by heart
- StringBuffer capacity: default 16; new StringBuffer(s) has capacity 16 + s.length(); when full it normally grows to (old × 2) + 2.
- compareTo returns 0 if the strings are equal, a negative value if the invoking string comes first, and a positive value if it comes later: the Unicode difference of the first differing characters, or the length difference when one string is a prefix of the other.
- Thread priority: MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10.
- start() creates a new thread that calls run(); calling run() directly runs it in the current thread.
- wait(), notify() and notifyAll() must be called inside synchronized code on the same object, otherwise IllegalMonitorStateException is thrown.
- Safe control pattern: mySuspend() sets volatile suspended = true; myResume() sets it false and calls notify() in synchronized code; myStop() sets volatile stopped = true and calls interrupt(); run() checks both flags in its loop.
- JDBC steps: load driver → getConnection → createStatement or prepareStatement → executeQuery or executeUpdate → process the ResultSet → close.
- JavaFX skeleton: extend Application → override start(Stage) → new Scene(root, w, h) → stage.setScene(scene) → stage.show(); main calls launch(args).
2-mark questions
1 What is the CharSequence interface? How is it related to the String class? 2 marks
CharSequence is an interface in java.lang that represents a readable sequence of char values. It declares length(), charAt(int index), subSequence(int start, int end) and toString(). String, StringBuffer and StringBuilder all implement it, so a method that accepts a CharSequence parameter can work with any of these classes.
2 Explain the charAt() and getChars() methods of the String class with an example. 2 marks
charAt(int index) returns the character at a zero-based index, so "Java".charAt(2) gives 'v'. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) copies the characters from srcBegin to srcEnd−1 into the array dst, starting at dstBegin. An invalid index throws StringIndexOutOfBoundsException.
3 What is thread priority? State the priority constants defined in the Thread class. 2 marks
Thread priority is an integer from 1 to 10 that the scheduler uses as a hint when choosing which runnable thread to run. The constants are Thread.MIN_PRIORITY = 1, Thread.NORM_PRIORITY = 5 and Thread.MAX_PRIORITY = 10. You set it with setPriority(int) and read it with getPriority(). A new thread takes the priority of the thread that created it.
4 Distinguish between a race condition and a deadlock. 2 marks
A race condition occurs when two or more threads use shared data at the same time and the result depends on the unpredictable order in which they run. An example is lost updates when two threads execute count++ together. A deadlock occurs when two or more threads wait forever, because each holds a lock that another one needs.
5 What is a ResultSet in JDBC? How is it traversed? 2 marks
ResultSet is a java.sql interface whose object holds the rows returned by executeQuery(). It keeps a cursor that starts before the first row. next() moves the cursor forward and returns false after the last row. Column values are read with getInt(), getString(), getDouble() and similar methods, using a 1-based column index or the column name.
6 Define Stage, Scene and scene graph in JavaFX. 2 marks
The Stage is the top-level window that the runtime passes to start(Stage). A Scene holds all the visible content and is attached to the window with stage.setScene(scene). Inside the scene, nodes form a tree called the scene graph. It has exactly one root node, usually a layout pane, and all controls, text and images are its descendants.
10-mark questions
1 Explain the String class in Java. With a suitable program, illustrate the methods used for extracting characters, comparing, modifying and searching strings. 10 marks
In Java a string is an object of the final class java.lang.String, which implements CharSequence and Comparable<String>. A String object is immutable: once created, its characters never change, so every method that seems to modify a string actually returns a new String. Identical string literals share one object in the string constant pool.
1. Extracting characters: charAt(i) returns the character at index i. getChars(start, end, dst, dstBegin) copies a range of characters into a char array. toCharArray() returns all characters as a new array.
2. Comparing strings:
- equals(obj) compares contents and is case-sensitive; equalsIgnoreCase(s) ignores case.
- compareTo(s) returns 0 if the strings are equal, a negative value if the invoking string comes first in dictionary order, and a positive value otherwise. If the strings differ at some index, the value is the Unicode difference of the first characters that differ. If no character differs but the lengths differ (one string is a prefix of the other), the value is the difference of the lengths, this.length() − s.length().
- startsWith(prefix) and endsWith(suffix) test the beginning and the end of a string.
- The == operator compares only references, not contents.
3. Modifying strings (each returns a new object): substring(begin) and substring(begin, end), concat(s), replace(old, new), trim(), toUpperCase() and toLowerCase().
4. Searching strings: indexOf(ch or str) returns the first position and lastIndexOf returns the last position. Both return -1 if the text is not found. contains(seq) returns a boolean.
Program:
public class StringDemo {
public static void main(String[] args) {
String a = "Hello";
String b = new String("Hello");
String c = "hello";
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.equalsIgnoreCase(c)); // true
System.out.println(a.compareTo(c)); // -32
System.out.println("Hi".compareTo("Hit")); // -1
String s = " object oriented ";
String t = s.trim(); // "object oriented"
System.out.println(t.toUpperCase()); // OBJECT ORIENTED
System.out.println(t.replace('o', '0')); // 0bject 0riented
System.out.println(t.substring(7)); // oriented
System.out.println(t.indexOf('e')); // 3
System.out.println(t.lastIndexOf("e")); // 13
System.out.println(t.contains("ient")); // true
}
}Explanation of the output:
- a == b is false because new String creates a separate heap object. equals compares the characters, so it gives true.
- a.compareTo(c): the first characters already differ. 'H' = 72 and 'h' = 104, so the result is 72 − 104 = −32.
- "Hi".compareTo("Hit"): the characters 'H' and 'i' match, and "Hi" then runs out, so no character differs. "Hi" is a prefix of "Hit", so the result is the length difference 2 − 3 = −1, meaning "Hi" comes first.
- After trim, t = "object oriented", with indices 0 to 14. The first 'e' is at index 3 and the last 'e' is at index 13. substring(7) starts at the 'o' of "oriented".
- s itself is unchanged after trim(), which shows that strings are immutable.
Conclusion: The String class gives a rich set of methods for reading, comparing, transforming and searching text. Because strings are immutable, code that changes text repeatedly should use StringBuffer or StringBuilder instead.
2 Explain the StringBuffer class with its constructors and important methods. Write a program to demonstrate them and compare String, StringBuffer and StringBuilder. 10 marks
StringBuffer, in java.lang, represents a mutable sequence of characters. Unlike String, its contents can be changed in place without creating new objects. It implements CharSequence, and its methods are synchronized, so it is safe to use from several threads.
1. Constructors:
- StringBuffer(): empty buffer with a default capacity of 16 characters.
- StringBuffer(int capacity): empty buffer with the given capacity.
- StringBuffer(String s): holds s, with capacity 16 + s.length().
- StringBuffer(CharSequence cs): holds the characters of cs.
2. Important methods:
- length() returns the number of characters stored; capacity() returns the allocated space.
- ensureCapacity(n) and setLength(n) control the storage and the length.
- charAt(i) reads a character; setCharAt(i, ch) changes it.
- append(x) is overloaded for all types and adds x at the end.
- insert(i, x) inserts x at index i.
- delete(start, end) removes characters; deleteCharAt(i) removes a single character.
- replace(start, end, str) replaces the characters from start to end−1 with str.
- reverse() reverses the contents.
When the length exceeds the capacity, the buffer grows automatically, normally to (old capacity × 2) + 2.
3. Program:
public class BufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.length() + " " + sb.capacity()); // 4 20
sb.append(" Program"); // Java Program
sb.insert(4, "FX"); // JavaFX Program
System.out.println(sb);
sb.replace(7, 14, "App"); // JavaFX App
sb.deleteCharAt(6); // JavaFXApp
sb.setCharAt(0, 'j'); // javaFXApp
System.out.println(sb);
System.out.println(sb.reverse()); // ppAXFavaj
}
}Trace of the program:
- The capacity is 16 + 4 = 20.
- insert(4, "FX") places FX before the space, giving "JavaFX Program", which has length 14.
- Index 7 is 'P', so replace(7, 14, "App") gives "JavaFX App".
- Removing index 6 (the space) gives "JavaFXApp".
- setCharAt makes it "javaFXApp", and reverse gives "ppAXFavaj".
4. Comparison:
- String: immutable, and thread-safe because it never changes. Repeated concatenation creates many temporary objects.
- StringBuffer: mutable and synchronized, so it is thread-safe but slightly slower.
- StringBuilder: mutable and not synchronized. It is the fastest choice for single-threaded code.
- String overrides equals() to compare contents. StringBuffer does not, so convert with toString() before comparing.
Conclusion: StringBuffer is the right choice when text must be modified many times and the object may be shared between threads. StringBuilder is preferred when only one thread uses it.
3 Why is multithreading needed? Explain the main thread and the two ways of creating threads in Java with a program, and describe the life cycle (states) of a thread. 10 marks
A thread is an independent path of execution inside a program. Multithreading lets one program carry out several tasks at the same time.
1. Need for multithreading:
- Responsiveness: a GUI stays usable while a long task runs in the background.
- Better use of the CPU: one thread computes while another waits for I/O.
- Multi-core processors: the threads of one process can run truly in parallel on different cores. On a single core they are only time-sliced.
- Threads share the memory of their process, so they are cheaper to create and switch than separate processes.
2. Main thread: when a program starts, the JVM creates the main thread, which runs main(). Thread.currentThread() returns a reference to it. Its default name is "main" and its priority is 5. Other threads are started from it, and it often waits for them with join().
3. Creating threads:
- Way 1: extend Thread and override run().
- Way 2: implement Runnable, write run(), and pass the object to a Thread constructor. This way is preferred because the class remains free to extend another class.
In both ways, start() must be called. It creates a new thread, which then calls run(). Calling run() directly just executes it in the current thread.
class Counter extends Thread {
public void run() {
for (int i = 1; i <= 3; i++)
System.out.println(getName() + " : " + i);
}
}
class Task implements Runnable {
public void run() {
System.out.println("Task in " + Thread.currentThread().getName());
}
}
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread m = Thread.currentThread();
System.out.println(m.getName() + " priority " + m.getPriority());
Counter c = new Counter();
Thread t = new Thread(new Task(), "Worker");
c.start();
t.start();
c.join();
t.join();
System.out.println("Main ends");
}
}The first line printed is "main priority 5" and the last line is "Main ends". The lines from Thread-0 and Worker may appear in any order, because the scheduler decides the order.
4. Thread states: a thread is always in one of the six states of the Thread.State enum.
- NEW: the thread has been created but not started.
- RUNNABLE: the thread is running or ready to run.
- BLOCKED: the thread is waiting for a monitor lock.
- WAITING: the thread is waiting indefinitely, through wait() or join().
- TIMED_WAITING: the thread is in sleep(ms), wait(ms) or join(ms).
- TERMINATED: run() has finished.
A thread that is notified out of wait() must first reacquire the monitor. If another thread still holds the lock, it moves to BLOCKED before it becomes RUNNABLE.
Conclusion: Threads created by extending Thread or by implementing Runnable let Java programs use multi-core hardware well, and they move through these well-defined states during their life.
4 What is thread synchronization? Explain race conditions and deadlock, and demonstrate inter-thread communication using wait() and notify() with a producer–consumer program. 10 marks
When several threads share data, their operations can interleave in harmful ways. Synchronization ensures that only one thread at a time executes a critical section on a shared object.
1. Synchronization: every object has a monitor (lock). A synchronized method, or a synchronized(obj) { } block, must acquire that lock before it runs. Other threads that need the same lock move to the BLOCKED state until the lock is released.
2. Race condition: count++ is really three steps: read, add and write. If two threads each run count++ 1000 times without synchronization, their steps can interleave and updates are lost, so the final count may be less than 2000. Declaring the increment method synchronized removes the race.
3. Deadlock: thread T1 locks A and then needs B, while thread T2 locks B and then needs A. Both wait forever.
Deadlock can be avoided by acquiring locks in one fixed global order, keeping critical sections short, or using timed lock attempts.
4. Inter-thread communication: the Object methods wait(), notify() and notifyAll() let threads cooperate. They may only be called while holding the object's lock; otherwise IllegalMonitorStateException is thrown.
- wait() releases the lock and suspends the thread.
- notify() wakes one waiting thread, and notifyAll() wakes all of them.
class Buffer {
private int item;
private boolean full = false;
synchronized void put(int v) throws InterruptedException {
while (full) wait();
item = v; full = true;
System.out.println("Produced " + v);
notify();
}
synchronized int get() throws InterruptedException {
while (!full) wait();
full = false;
System.out.println("Consumed " + item);
notify();
return item;
}
}
public class PCDemo {
public static void main(String[] args) {
Buffer b = new Buffer();
new Thread(() -> {
try { for (int i = 1; i <= 3; i++) b.put(i); }
catch (InterruptedException e) { }
}).start();
new Thread(() -> {
try { for (int i = 1; i <= 3; i++) b.get(); }
catch (InterruptedException e) { }
}).start();
}
}Output: Produced 1, Consumed 1, Produced 2, Consumed 2, Produced 3, Consumed 3.
The buffer holds only one item. The producer waits while it is full and the consumer waits while it is empty, so the two threads strictly alternate. The while loop re-checks the condition after waking, which guards against spurious wake-ups.
5. Suspending, resuming and stopping a thread: the old methods suspend(), resume() and stop() are deprecated. A suspended thread keeps the locks it holds, which can cause deadlock, and stop() can leave shared data half-updated. The safe way is a flag that run() checks. A volatile boolean suspended makes run() call wait() inside a synchronized block, resume sets it to false and calls notify(), and a volatile boolean stopped makes run() return.
Conclusion: Synchronization prevents race conditions, careful lock ordering prevents deadlock, and wait/notify lets threads coordinate without busy waiting.
5 Describe the JDBC architecture and driver types. Explain the steps to set up MySQL with Connector/J and write a Java program that connects to a database and displays records using a ResultSet. 10 marks
JDBC (Java Database Connectivity) is the standard Java API, in package java.sql, for running SQL statements against relational databases in a vendor-independent way.
1. Architecture: an application calls the JDBC API. DriverManager selects a suitable driver, and the driver translates the calls into the database's own protocol.
2. Driver types:
- Type 1, JDBC-ODBC bridge: removed in Java 8.
- Type 2, native-API driver: uses client libraries.
- Type 3, network-protocol driver: works through middleware.
- Type 4, thin driver: pure Java and talks directly to the database. Connector/J is a Type 4 driver.
3. Setting up MySQL and Connector/J:
- Install MySQL Server, set the root password and start the service.
- Create the database with CREATE DATABASE college; and the table with CREATE TABLE student(rollno INT PRIMARY KEY, name VARCHAR(30), cgpa DOUBLE); then insert some rows.
- Download MySQL Connector/J and add the mysql-connector-j jar file to the classpath, either with java -cp or in the IDE build path.
- The driver class is com.mysql.cj.jdbc.Driver and the URL has the form jdbc:mysql://localhost:3306/college.
4. Steps to establish a connection:
- Load the driver. Class.forName is optional from JDBC 4.0 onwards.
- Get a Connection with DriverManager.getConnection(url, user, password).
- Create a Statement, or a PreparedStatement for parameterised queries.
- Execute: executeQuery for SELECT returns a ResultSet; executeUpdate for INSERT, UPDATE or DELETE returns a row count.
- Process the ResultSet.
- Close all resources.
import java.sql.*;
public class StudentList {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
try (Connection con = DriverManager.getConnection(url, "root", "pass");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT rollno, name, cgpa FROM student")) {
while (rs.next()) {
System.out.println(rs.getInt("rollno") + " " + rs.getString("name") + " " + rs.getDouble(3));
}
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}5. ResultSet: its cursor starts before the first row, and next() advances it until it returns false. Values are read with getXxx using a column name or a 1-based index. A default ResultSet is forward-only and read-only. createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY) gives a scrollable one that supports previous(), first(), last() and absolute(n).
Conclusion: With the Connector/J jar on the classpath and these steps, any Java program can query MySQL. Try-with-resources closes the connection, statement and result set automatically.
6 Explain the structure of a JavaFX application. Write a JavaFX program that displays text and an image, handles a button click and mouse events, and explain the common layout panes. 10 marks
JavaFX is Java's modern toolkit for building graphical interfaces. A JavaFX application extends javafx.application.Application and overrides start(Stage). main() calls launch(args), which creates the application and calls start().
1. Window structure: the Stage is the window. It shows one Scene, and the Scene holds a scene graph of nodes with a single root, usually a layout pane. Scene Builder is a drag-and-drop tool that saves a design as an FXML file. FXMLLoader loads that file, and a controller class connects to its controls through @FXML fields.
2. Displaying text and images: Label or Text nodes show text. setFont changes the font of both, setTextFill sets the colour of a Label, and setFill sets the colour of a Text node. An image is loaded with the Image class and shown through an ImageView node, which can be resized with setFitWidth and setPreserveRatio.
3. Event handling: the user's action on a source node creates an event object, which is delivered to a registered EventHandler (often written as a lambda). setOnAction handles button clicks. Mouse events include setOnMouseClicked, setOnMousePressed, setOnMouseReleased, setOnMouseEntered, setOnMouseExited, setOnMouseMoved and setOnMouseDragged. The MouseEvent object supplies getX(), getY(), getButton() and getClickCount().
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class WelcomeApp extends Application {
@Override
public void start(Stage stage) {
Label msg = new Label("Welcome to JavaFX");
msg.setFont(new Font("Arial", 20));
ImageView view = new ImageView(new Image("file:logo.png"));
view.setFitWidth(120);
view.setPreserveRatio(true);
Button btn = new Button("Click Me");
btn.setOnAction(e -> msg.setText("Button clicked"));
view.setOnMouseClicked(e -> msg.setText("Image clicked at " + e.getX() + ", " + e.getY()));
view.setOnMouseEntered(e -> view.setOpacity(0.6));
view.setOnMouseExited(e -> view.setOpacity(1.0));
VBox root = new VBox(10, msg, view, btn);
root.setAlignment(Pos.CENTER);
stage.setScene(new Scene(root, 300, 250));
stage.setTitle("Demo");
stage.show();
}
public static void main(String[] args) { launch(args); }
}What the program does:
- Clicking the button changes the label.
- Hovering over the image dims it, and moving away restores it.
- Clicking the image reports the click coordinates.
4. Layout panes arrange child nodes automatically:
- HBox and VBox: place children in a single row or column, with spacing.
- BorderPane: provides top, bottom, left, right and center regions.
- GridPane: places children in rows and columns.
- FlowPane: wraps children to the next line.
- StackPane: stacks children on top of each other.
- Pane: uses absolute positions.
Conclusion: A JavaFX program is built as Stage → Scene → scene graph. Nodes display content, layout panes position the nodes, and event handlers make the interface interactive.
Public sources that settled doubtful points
Only the points the second AI pass doubted were looked up. These are the pages that confirmed or contradicted them; nothing here is copied from them.
Further reading
Titles only, for your own study. Nothing on this page is copied from them. The units follow the official JNTUK R23 CSE syllabus (PDF) ↗.
- Java One Step Ahead · Anita Seth and B. L. Juneja
- Joy with Java: Fundamentals of Object Oriented Programming · Debasis Samanta and Monalisa Sarma
- Java 9 for Programmers · Paul Deitel and Harvey Deitel
- Java: The Complete Reference · Herbert Schildt
- Introduction to Java Programming · Y. Daniel Liang