UNIT – III
Arrays & Strings • Interface & Packages
Exception Handling
Java Programming – Study Notes
Bachelor of Computer Applications (BCA)
I.K. Gujral Punjab Technical University (PTU)
Course Outcomes Covered: CO2 (Arrays, Strings, Interface, Packages) & CO5 (Exception Handling)
PART A Arrays – Introduction, Processing, Passing/Returning, Object Arrays, 2D & Multi-D Arrays
PART B Strings – String class, Concatenation, Comparison, Substring, StringBuffer, StringTokenizer
PART C Interfaces – Basics, Multiple Interfaces, Multiple/Multilevel Inheritance via Interface
PART D Packages – Creating & Accessing Packages, Static Import, Access Specifiers
PART E Exception Handling – Try/Catch, Multiple Catch, Nested Try, Finally, Throw, Built-in Exceptions
Java Programming – Unit III Notes BCA – PTU
PART A — CO2
Arrays
1. Introduction to Array
An array is a collection of elements of the same data type stored in contiguous memory locations and
accessed using a single name with an index.
• Index starts at 0; last index = length - 1.
• Default values on creation: numeric → 0, boolean → false, object refs → null.
• .length is a field, not a method — written without ().
int[] marks; // declaration
marks = new int[5]; // memory allocation (size 5)
int[] scores = {85, 90, 78, 92, 65}; // declaration + initialization
[Link]([Link]); // 5
[Link](scores[0]); // 85
2. Processing Array Contents
Arrays are processed using loops — to traverse, search, sort, or compute values like sum/average/max.
int[] nums = {12, 45, 3, 67, 23};
int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += nums[i];
}
[Link]("Sum = " + sum);
// for-each (enhanced for loop) - read only
for (int n : nums) {
[Link](n + " ");
}
[Link](nums); // ascending sort: 3 12 23 45 67
3. Passing Array as Argument
In Java, arrays are objects, so they are passed to methods by reference (the address is copied). Changes
made to array elements inside the method reflect back in the caller.
static void doubleValues(int[] arr) {
for (int i = 0; i < [Link]; i++) {
arr[i] = arr[i] * 2;
}
}
public static void main(String[] args) {
int[] data = {1, 2, 3};
doubleValues(data);
for (int d : data) [Link](d + " "); // 2 4 6
}
Page 2
Java Programming – Unit III Notes BCA – PTU
4. Returning Array from Methods
A method can have an array type as its return type. The method creates the array and returns its reference to
the caller.
static int[] createSquares(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = (i + 1) * (i + 1);
}
return result;
}
public static void main(String[] args) {
int[] sq = createSquares(5);
for (int s : sq) [Link](s + " "); // 1 4 9 16 25
}
5. Array of Objects
An array can also store references to objects of a class. Declaring the array does not create the objects —
each element must be instantiated individually with new, otherwise it stays null.
class Student {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
}
}
public class ArrayOfObjects {
public static void main(String[] args) {
Student[] students = new Student[3]; // 3 null references
students[0] = new Student("Raj", 88);
students[1] = new Student("Aman", 76);
students[2] = new Student("Simran", 92);
for (Student s : students) {
[Link]([Link] + " - " + [Link]);
}
}
}
6. 2D Arrays
A 2D array (array of arrays) represents data in rows and columns, like a matrix or table. Declared as
type[][] name.
Page 3
Java Programming – Unit III Notes BCA – PTU
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < [Link]; i++) { // rows
for (int j = 0; j < matrix[i].length; j++) { // columns
[Link](matrix[i][j] + " ");
}
[Link]();
}
• Java arrays can be jagged — each row can have a different number of columns, e.g. int[][] a =
new int[3][];
7. Arrays with Three or More Dimensions
Java allows multi-dimensional arrays beyond 2D, e.g. int[][][] for a 3D array. Useful for representing
data such as multiple matrices or 3D coordinate space.
int[][][] cube = new int[2][2][2];
int val = 1;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
cube[i][j][k] = val++;
[Link](cube[1][1][1]); // 8
★ Exam tip: Be ready to explain that array name in Java is a reference variable pointing to an object
on the heap — this is *why* arrays are passed by reference.
Page 4
Java Programming – Unit III Notes BCA – PTU
PART B — CO2
Strings
8. String Class
String is a class in [Link] representing a sequence of characters. Strings in Java are immutable —
once created, the content cannot be changed; any modification creates a new String object.
• String literal ("Hello") → stored in the String Constant Pool (reused if identical).
• new String(...) → always creates a new object on the heap, even if content is identical.
String s1 = "Hello"; // string pool
String s2 = new String("Hello"); // new object on heap
[Link](s1 == s2); // false -> different references
[Link]([Link](s2)); // true -> same content
9. String Concatenation
Strings can be joined using the + operator or the concat() method.
String first = "Hello";
String second = "World";
String r1 = first + " " + second; // using +
String r2 = [Link](" ").concat(second); // using concat()
[Link](r1); // Hello World
★ Repeated + concatenation inside a loop creates many temporary objects (inefficient) — prefer
StringBuilder/[Link]() instead.
10. Comparing Strings
Method Purpose
== Compares references (memory address), not content
.equals() Compares actual content, case-sensitive
.equalsIgnoreCase() Compares content, ignoring case
.compareTo() Lexicographic comparison; returns +ve, -ve, or 0
String a = "apple";
String b = "Apple";
[Link]([Link](b)); // false
[Link]([Link](b)); // true
[Link]([Link](b)); // positive value
11. Substring
Page 5
Java Programming – Unit III Notes BCA – PTU
substring(beginIndex) and substring(beginIndex, endIndex) extract part of a string.
endIndex is exclusive.
String str = "Programming";
[Link]([Link](3)); // gramming
[Link]([Link](0, 4)); // Prog
12. Difference between String and StringBuffer
String StringBuffer
Immutable – content cannot change Mutable – content can be modified in place
Every modification creates a new object (slower, more
Modifies the same object (faster for repeated edits)
memory)
Inherently thread-safe (immutable) Methods are synchronized → thread-safe
Supports + operator for joining No + overloading – use .append()
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Hello World
[Link](5, ","); // Hello, World
[Link]();
[Link](sb);
★ StringBuilder is identical to StringBuffer but not synchronized → faster in single-threaded code.
Often asked as a follow-up comparison.
13. StringTokenizer Class
StringTokenizer (in [Link]) breaks a string into tokens based on delimiter characters (default
delimiters: space, tab, newline).
import [Link];
public class TokenDemo {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Raj,Aman,Simran", ",");
while ([Link]()) {
[Link]([Link]());
}
}
}
// Output: Raj Aman Simran
• countTokens() — returns number of tokens remaining.
• hasMoreTokens() — returns true if more tokens exist.
Page 6
Java Programming – Unit III Notes BCA – PTU
PART C — CO2
Interface
14. Basics of Interface
An interface is a blueprint of a class — it declares what a class must do, not how. Declared with the
interface keyword and implemented using implements.
• Variables in an interface are implicitly public static final (constants).
• Methods are implicitly public abstract (before Java 8); Java 8+ also allows default and static
methods with bodies.
• Achieves abstraction and enables Java's form of multiple inheritance.
interface Shape {
double PI = 3.14159; // public static final (implicit)
double area(); // public abstract (implicit)
}
class Circle implements Shape {
double radius;
Circle(double radius) { [Link] = radius; }
public double area() {
return PI * radius * radius;
}
}
15. Multiple Interfaces
A single class can implement more than one interface, separated by commas. This is how Java
compensates for not allowing multiple class inheritance.
interface Printable { void print(); }
interface Showable { void show(); }
class Document implements Printable, Showable {
public void print() { [Link]("Printing..."); }
public void show() { [Link]("Showing..."); }
}
16. Multiple Inheritance Using Interface
Java does not allow multiple inheritance with classes (to avoid the diamond problem), but it is achieved
safely through interfaces, since interfaces only provide method declarations, not conflicting implementations.
interface A { void methodA(); }
interface B { void methodB(); }
class C implements A, B {
public void methodA() { [Link]("A's method"); }
public void methodB() { [Link]("B's method"); }
}
Page 7
Java Programming – Unit III Notes BCA – PTU
17. Multilevel Interface
One interface can extend another interface using extends (an interface can even extend multiple
interfaces). The implementing class must define all inherited abstract methods.
interface Animal { void eat(); }
interface Mammal extends Animal { void walk(); }
class Dog implements Mammal {
public void eat() { [Link]("Dog eats"); }
public void walk() { [Link]("Dog walks"); }
}
★ Exam tip: class extends class, interface extends interface(s), but class implements
interface(s). Note an interface can extends multiple interfaces, unlike a class.
Page 8
Java Programming – Unit III Notes BCA – PTU
PART D — CO2
Packages
18. Packages – Basics
A package is a namespace that groups related classes and interfaces together. It avoids naming conflicts
and provides access control.
• Built-in packages: [Link], [Link], [Link], etc.
• User-defined packages: created by the programmer using the package keyword.
19. Create and Access Packages
The package statement must be the first line of the source file (only comments may precede it).
// File: [Link]
package [Link];
public class MyMath {
public static int square(int n) {
return n * n;
}
}
Compiling: javac -d . [Link] → creates folder structure
com/touristx/util/[Link]
// Accessing the package in another file
import [Link];
public class Test {
public static void main(String[] args) {
[Link]([Link](5)); // 25
}
}
• Without import, a class can still be accessed using its fully qualified name:
[Link](5).
20. Static Import and Package Class
import static allows direct use of static members of a class without prefixing the class name.
import static [Link].*;
public class StaticImportDemo {
public static void main(String[] args) {
[Link](sqrt(25)); // instead of [Link](25)
[Link](PI); // instead of [Link]
}
}
The [Link] class provides metadata about a package (name, version, vendor), retrieved
using getClass().getPackage().
Page 9
Java Programming – Unit III Notes BCA – PTU
21. Access Specifiers
Subclass (diff. Different
Modifier Same Class Same Package
pkg) Package
private Yes No No No
default (none) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
★ Exam tip: default (no modifier written) access is also called package-private — accessible only
within the same package.
Page 10
Java Programming – Unit III Notes BCA – PTU
PART E — CO5
Exception Handling
22. Introduction
An exception is an event that disrupts the normal flow of a program's execution. Java handles exceptions
using objects derived from the Throwable class.
Throwable
|-- Error (serious, not normally handled)
+-- Exception
|-- Checked Exceptions (checked at compile time, e.g. IOException)
+-- RuntimeException (unchecked, e.g. ArithmeticException)
• Checked exceptions: must be handled or declared (IOException, SQLException).
• Unchecked exceptions: occur at runtime (ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException).
23. Try and Catch Blocks
Risky code is placed inside a try block; the corresponding catch block handles the exception if it occurs,
preventing abnormal termination.
public class TryCatchDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
}
}
}
24. Multiple Catch
A single try block may be followed by multiple catch blocks to handle different exception types. They are
checked top to bottom, so more specific exceptions must come before more general ones.
try {
int[] arr = new int[5];
arr[10] = 50 / 0;
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
} catch (Exception e) {
[Link]("General error");
}
// Java 7+ multi-catch shorthand:
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { ... }
Page 11
Java Programming – Unit III Notes BCA – PTU
25. Nested Try
A try block can be placed inside another try block when an inner operation needs its own, separate
exception handling.
try {
try {
int[] a = {1, 2, 3};
[Link](a[5]);
} catch (ArithmeticException e) {
[Link]("Inner catch: Arithmetic");
}
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch: Array Index");
}
26. Finally
The finally block always executes, whether an exception occurs or not (unless [Link]() is
called or the JVM crashes). Typically used for cleanup — closing files, releasing connections, etc.
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception caught");
} finally {
[Link]("Finally block executed - cleanup here");
}
27. Throw Statement
The throw keyword is used to explicitly throw an exception object (built-in or custom).
public class ThrowDemo {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
[Link]("Eligible to vote");
}
public static void main(String[] args) {
checkAge(15); // throws exception, terminates if uncaught
}
}
`throw` `throws`
Used inside a method body to actually raise an Used in the method signature to declare possible
exception exceptions
Followed by an exception instance: throw new Followed by exception class name(s): void m()
Exception(); throws IOException
28. Built-In Exceptions
Page 12
Java Programming – Unit III Notes BCA – PTU
Exception Occurs When
ArithmeticException Invalid arithmetic operation, e.g. divide by zero
ArrayIndexOutOfBoundsException Array accessed with an illegal/out-of-range index
NullPointerException Method/field accessed on a null reference
Invalid String-to-number conversion, e.g.
NumberFormatException
[Link]("abc")
ClassNotFoundException JVM cannot find the requested class (checked)
StringIndexOutOfBoundsException Invalid index used with String methods
IOException Input/output operation fails (checked)
FileNotFoundException Requested file does not exist (checked)
★ Exam tip: Remember the 5 keywords of exception handling together — try, catch, finally,
throw, throws.
End of Unit III Notes — prepared for quick revision before exams. Good luck, Raj!
Page 13