Unit 1: Java programming exercises
Java Technologies Laboratory notes · PTU syllabus (PGCA1940)
On this page
- Unit summary
- Setting up and running Java
- I/O, arithmetic and expressions
- Number programs
- Pascal's triangle
- Arrays and matrices
- Counting vowels and consonants
- Inheritance types and access specifiers
- Creating packages
- Built-in exception handling
- Threads: model, priority and synchronisation
- Applets with text fields and buttons
- Swing: JButton and JTextField listeners
- Servlets: requests, cookies and sessions
- Key terms
- Quick revision
- Important questions
Unit summary
This lab builds Java skills from basic I/O and arithmetic through arrays, matrices, strings, inheritance, interfaces, packages, exceptions and threads to applets, Swing listeners, servlets with cookies and sessions.
After this unit you can
- Write and run Java programs for computation and arrays
- Apply OOP — inheritance, access specifiers, interfaces, packages
- Handle exceptions and use threads with priorities and synchronisation
- Build GUI programs and servlets with cookies and sessions
PTU syllabus topics
- Basic I/O and arithmetic operations
- expression evaluation
- average computation
- volume calculations
- multiplication tables
- prime checking
- Fibonacci series
- factorial
- quadratic equations
- weekday generation
- Pascal's triangle
- array printing/sorting/rotation
- matrix sum/difference/product/sparse-check
- vowel/consonant counting
- inheritance types
- access specifiers
- multiple inheritance via interfaces
- package creation
- built-in exception handling
- thread model implementation
- thread priority and synchronization
- applets with text fields and buttons
- JButton/JTextField listeners
- servlet HTTP request/response handling
- cookies and session tracking
- 1
Load the driver
- 2
Open a Connection
DriverManager.getConnection()
- 3
Create a Statement or PreparedStatement
- 4
Execute the query
- 5
Process the ResultSet
- 6
Close the connection
Topic 1
Setting up and running Java
- 1Install a JDK (17 or 21 LTS) and set PATH
- 2Write the program in an editor or IDE (VS Code, Eclipse, IntelliJ)
- 3Compile: javac Program.java
- 4Run: java Program
- 5Read compiler errors from the first one down
- Single-file launch: java Program.java compiles and runs in one step (Java 11+).
Topic 2
I/O, arithmetic and expressions
javapublic class MathDemo {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("Sum " + (a + b) + " Quotient " + (a / b) + " Remainder " + (a % b));
System.out.println("a > b ? " + (a > b) + " a & b = " + (a & b) + " a << 2 = " + (a << 2));
System.out.println(Math.sqrt(144) + " " + Math.pow(2, 10) + " " + Math.abs(-7));
System.out.println(Math.max(a, b) + " " + Math.round(4.6) + " " + Math.ceil(4.1) + " " + Math.floor(4.9));
double r = 7;
System.out.printf("Area of circle = %.2f%n", Math.PI * r * r);
System.out.println("Random 1–6: " + (int) (Math.random() * 6 + 1));
}
}Topic 3
Number programs
javaimport java.util.Scanner;
public class Numbers {
static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
static long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
public static void main(String[] a) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n + (isPrime(n) ? " is prime" : " is not prime"));
System.out.println("Factorial = " + fact(n));
int x = 0, y = 1; for (int i = 0; i < n; i++) { System.out.print(x + " "); int t = x + y; x = y; y = t; }
for (int i = 1; i <= 10; i++) System.out.println(n + " x " + i + " = " + n * i);
double A = 1, B = -3, C = 2, d = B * B - 4 * A * C; // quadratic roots
if (d >= 0) System.out.println(((-B + Math.sqrt(d)) / (2 * A)) + ", " + ((-B - Math.sqrt(d)) / (2 * A)));
else System.out.println("Imaginary roots");
}
}- Also: average of n numbers, volume of cube, cylinder and sphere (V = 4/3 πr³), weekday from a number using switch.
Topic 4
Pascal's triangle
javafor (int i = 0; i < 5; i++) {
int c = 1;
System.out.print(" ".repeat(5 - i));
for (int j = 0; j <= i; j++) { System.out.print(c + " "); c = c * (i - j) / (j + 1); }
System.out.println();
}Topic 5
Arrays and matrices
javaint[] a = {5, 2, 9, 1};
java.util.Arrays.sort(a); // sorting
int k = 1, n = a.length; int[] r = new int[n];
for (int i = 0; i < n; i++) r[(i + k) % n] = a[i]; // rotate right by k
int[][] p = {{1, 2}, {3, 4}}, q = {{5, 6}, {7, 8}}, m = new int[2][2];
for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int t = 0; t < 2; t++) m[i][j] += p[i][t] * q[t][j];
int zeros = 0; for (int[] row : p) for (int v : row) if (v == 0) zeros++;
boolean sparse = zeros > (p.length * p[0].length) / 2; // sparse check- Sum and difference use m[i][j] = p[i][j] ± q[i][j].
Topic 6
Counting vowels and consonants
javaString s = "Bathinda".toLowerCase(); int v = 0, c = 0;
for (char ch : s.toCharArray()) if (Character.isLetter(ch)) { if ("aeiou".indexOf(ch) >= 0) v++; else c++; }
System.out.println("Vowels " + v + ", consonants " + c); // 3, 5Topic 7
Inheritance types and access specifiers
- Single
- B extends A
- Multilevel
- C extends B extends A
- Hierarchical
- B and C extend A
- Multiple
- Only through interfaces — class C implements I1, I2
javainterface Printable { void print(); }
interface Showable { void show(); }
class Doc implements Printable, Showable {
public void print() { System.out.println("print"); }
public void show() { System.out.println("show"); }
}- Demonstrate private, default, protected and public by accessing members from the same class, same package, a subclass in another package, and an unrelated class.
Topic 8
Creating packages
java// shapes/Shape.java
package shapes;
public interface Shape { double area(); default String name() { return "Shape"; } }
// shapes/Circle.java
package shapes;
public class Circle implements Shape {
double r; public Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
public String name() { return "Circle"; }
}
// Main.java
import shapes.*;
public class Main {
public static void main(String[] args) {
Shape s = new Circle(3);
System.out.printf("%s area %.2f%n", s.name(), s.area());
}
}bashjavac -d . shapes/Shape.java shapes/Circle.java Main.java
java MainTopic 9
Built-in exception handling
javaimport java.util.Scanner;
class AgeException extends Exception { AgeException(String m) { super(m); } }
public class ExDemo {
static void checkAge(int age) throws AgeException {
if (age < 18) throw new AgeException("Not eligible to vote");
System.out.println("Eligible");
}
public static void main(String[] args) {
try {
int[] x = new int[2];
System.out.println(10 / Integer.parseInt(args.length > 0 ? args[0] : "0"));
x[3] = 1;
} catch (ArithmeticException e) { System.out.println("Divide by zero");
} catch (ArrayIndexOutOfBoundsException e) { System.out.println("Bad index");
} finally { System.out.println("finally runs"); }
try { checkAge(16); } catch (AgeException e) { System.out.println(e.getMessage()); }
}
}Topic 10
Threads: model, priority and synchronisation
javaclass Counter { int c; synchronized void inc() { c++; } }
public class ThreadDemo {
public static void main(String[] a) throws InterruptedException {
Counter k = new Counter();
Runnable r = () -> { for (int i = 0; i < 1000; i++) k.inc(); };
Thread t1 = new Thread(r, "T1"), t2 = new Thread(r, "T2");
t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY);
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println(k.c); // always 2000 with synchronized
}
}Topic 11
Applets with text fields and buttons
- Applets no longer run in browsers; run applet code with appletviewer on JDK 8, or draw the same output in a Frame as below.
javaimport java.awt.*;
public class Drawing extends Frame {
Drawing() { setTitle("Graphics"); setSize(420, 320); setVisible(true); }
public void paint(Graphics g) {
g.setColor(Color.red); g.drawLine(30, 60, 380, 60);
g.setColor(Color.blue); g.fillRect(30, 80, 100, 60);
g.setColor(Color.green); g.fillOval(150, 80, 80, 80);
g.setColor(Color.black); g.drawArc(250, 80, 100, 100, 0, 180);
g.drawPolygon(new int[]{60, 110, 10}, new int[]{200, 280, 280}, 3);
g.drawString("Java Graphics Lab", 150, 260);
}
public static void main(String[] a) { new Drawing(); }
}Topic 12
Swing: JButton and JTextField listeners
javaimport javax.swing.*;
public class Adder {
public static void main(String[] a) {
JFrame f = new JFrame("Adder");
JTextField x = new JTextField(5), y = new JTextField(5); JLabel out = new JLabel("=");
JButton b = new JButton("Add");
b.addActionListener(e -> out.setText("= " + (Integer.parseInt(x.getText()) + Integer.parseInt(y.getText()))));
JPanel p = new JPanel(); p.add(x); p.add(y); p.add(b); p.add(out);
f.add(p); f.setSize(300, 100); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true);
}
}Topic 13
Servlets: requests, cookies and sessions
- 1Install Apache Tomcat
- 2Create a dynamic web project (or Maven webapp)
- 3Write the servlet with @WebServlet
- 4Deploy the WAR to Tomcat
- 5Open http://localhost:8080/app/path
java@WebServlet("/visit")
public class Visit extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
HttpSession s = req.getSession();
Integer n = (Integer) s.getAttribute("n"); n = (n == null) ? 1 : n + 1; s.setAttribute("n", n);
res.addCookie(new Cookie("lastUser", req.getParameter("user")));
res.setContentType("text/html");
res.getWriter().println("Hello " + req.getParameter("user") + ", visit " + n);
}
}Key terms
- Scanner
- Class for reading console input
- Sparse matrix
- Matrix with mostly zero elements
- join()
- Waits for a thread to finish
- ActionListener
- Interface handling button clicks
- HttpSession
- Server-side session store
Quick revision
- Prime, factorial, Fibonacci, tables, quadratic roots, Pascal's triangle.
- Array sort and rotate; matrix sum, product, sparse check; vowels.
- Inheritance types; interfaces for multiple inheritance; access specifiers; packages.
- Exceptions; threads with priority and synchronized.
- Applets, Swing listeners, servlets with cookies and sessions.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.How do you read input with Scanner?
- Q2.How do you rotate an array by k positions?
- Q3.When is a matrix sparse?
- Q4.How is multiple inheritance achieved in Java?
- Q5.Why use synchronized in the thread program?
- Q6.How does a servlet track a session?
Long-answer questions
- Q1.Write a program for matrix multiplication and sparse checking.
- Q2.Write programs to demonstrate inheritance types and interfaces.
- Q3.Write a multithreaded program with priorities and synchronisation.
- Q4.Write a servlet using cookies and session tracking.
Stuck on this unit?
Message SBS on WhatsApp for help with Java Technologies Laboratory, or to ask about studying M.Sc IT at Synetic.
