Unit 1: Java programming implementation
Software Lab-IX (Programming in Java) notes · PTU syllabus (BSIT505/BSBC505)
On this page
- Unit summary
- Setting up and running Java
- Operators and mathematical functions
- Decision making and loops
- Classes, objects and methods
- Arrays, strings and vectors
- Interfaces and packages
- Exception handling
- Applet and graphics programming
- AWT and event handling
- I/O handling
- Practical list
- Key terms
- Quick revision
- Important questions
Unit summary
This lab implements Java programs on operators and mathematical functions, decision-making and loops, classes, objects and methods, arrays, strings and vectors, interfaces, packages, exception handling, applets and graphics, AWT, event handling and file I/O.
After this unit you can
- Compile and run Java programs with the JDK
- Write programs using classes, inheritance, interfaces and packages
- Handle exceptions and file I/O
- Build GUI programs with AWT and event handling
PTU syllabus topics
- Operators and mathematical functions
- decision-making/branching/looping statements
- classes/objects/methods
- arrays/strings/vectors
- interfaces
- packages
- exception handling
- applet programming
- AWT
- event handling
- I/O handling
- 1try
Code that might fail
- 2catch
Handle a specific exception
- 3finally
Always runs: close resources
- 4throw
Raise an exception yourself
- 5throws
Declare exceptions a method may pass on
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
Operators and mathematical functions
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
Decision making and loops
javaimport java.util.Scanner;
public class Loops {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
System.out.println(n % 2 == 0 ? "Even" : "Odd");
long fact = 1; // factorial
for (int i = 2; i <= n; i++) fact *= i;
System.out.println("Factorial = " + fact);
int t = n, arm = 0, digits = String.valueOf(n).length(); // Armstrong check
while (t > 0) { arm += Math.pow(t % 10, digits); t /= 10; }
System.out.println(arm == n ? "Armstrong" : "Not Armstrong");
for (int i = 1; i <= 4; i++) { // pattern
for (int j = 1; j <= i; j++) System.out.print(j + " ");
System.out.println();
}
}
}Topic 4
Classes, objects and methods
javaclass BankAccount {
private String holder; private double balance;
BankAccount(String h, double b) { holder = h; balance = b; }
void deposit(double amt) { balance += amt; }
boolean withdraw(double amt) { if (amt > balance) return false; balance -= amt; return true; }
void show() { System.out.println(holder + " : Rs " + balance); }
}
class Savings extends BankAccount { // inheritance
double rate;
Savings(String h, double b, double r) { super(h, b); rate = r; }
@Override void show() { super.show(); System.out.println("Interest rate " + rate + "%"); }
}
public class BankDemo {
public static void main(String[] args) {
BankAccount acc = new Savings("Riya", 10000, 3.5);
acc.deposit(2500);
System.out.println(acc.withdraw(20000) ? "Done" : "Insufficient balance");
acc.show(); // runtime polymorphism
}
}Topic 5
Arrays, strings and vectors
javaimport java.util.*;
public class ArrStr {
public static void main(String[] args) {
int[] a = {34, 12, 78, 5, 61};
Arrays.sort(a);
System.out.println(Arrays.toString(a) + " max " + a[a.length - 1]);
int[][] m = {{1, 2}, {3, 4}}, n = {{5, 6}, {7, 8}}, p = new int[2][2];
for (int i = 0; i < 2; i++) // matrix multiplication
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++) p[i][j] += m[i][k] * n[k][j];
System.out.println(Arrays.deepToString(p)); // [[19, 22], [43, 50]]
String s = "madam";
System.out.println(new StringBuilder(s).reverse().toString().equals(s) ? "Palindrome" : "No");
String[] names = {"Kabir", "Aman", "Simran"};
Arrays.sort(names); // alphabetical order
System.out.println(String.join(", ", names));
Vector<String> v = new Vector<>(List.of("C", "C++"));
v.add("Java"); v.insertElementAt("Python", 0); v.removeElement("C");
System.out.println(v + " size " + v.size());
}
}Topic 6
Interfaces and 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 7
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 8
Applet and graphics programming
- 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 9
AWT and event handling
javaimport java.awt.*;
import java.awt.event.*;
public class LoginForm extends Frame implements ActionListener {
TextField user = new TextField(15), pass = new TextField(15);
Label msg = new Label(" ");
Button login = new Button("Login");
LoginForm() {
super("Login");
setLayout(new GridLayout(4, 2, 5, 5));
pass.setEchoChar('*');
add(new Label("User")); add(user); add(new Label("Password")); add(pass);
add(login); add(msg);
login.addActionListener(this);
addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } });
setSize(320, 160); setVisible(true);
}
public void actionPerformed(ActionEvent e) {
msg.setText(user.getText().equals("admin") && pass.getText().equals("sbs@123") ? "Welcome" : "Invalid");
}
public static void main(String[] a) { new LoginForm(); }
}- Also practise: a calculator with GridLayout buttons, a MouseListener program showing click coordinates, and a KeyListener program counting typed characters.
Topic 10
I/O handling
javaimport java.io.*;
public class FileDemo {
public static void main(String[] args) throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter("marks.txt"))) {
pw.println("Aman 78"); pw.println("Riya 91"); pw.println("Kabir 66");
}
int total = 0, count = 0;
try (BufferedReader br = new BufferedReader(new FileReader("marks.txt"))) {
String line;
while ((line = br.readLine()) != null) {
total += Integer.parseInt(line.split(" ")[1]); count++;
}
}
System.out.println("Average = " + (double) total / count);
File f = new File("marks.txt");
System.out.println(f.getName() + " " + f.length() + " bytes, exists: " + f.exists());
}
}Topic 11
Practical list
- Programs on arithmetic, relational, logical and bitwise operators and Math functions.
- Even–odd, largest of three, grade using if-else and switch; factorial, Fibonacci, prime, Armstrong and patterns using loops.
- Classes with constructors, overloading, static members; inheritance and overriding.
- Array sorting and searching, matrix addition and multiplication, string palindrome and sorting names, Vector operations.
- Interfaces and user-defined packages.
- Built-in and user-defined exceptions with try, catch, finally, throw and throws.
- Applet or Frame drawing shapes and a bar chart; passing parameters to an applet.
- AWT forms, calculator, mouse and key events.
- Reading, writing and copying files; RandomAccessFile updates.
Key terms
- javac
- Java compiler producing bytecode
- Package
- Folder-based group of related classes
- Custom exception
- User-defined subclass of Exception
- ActionListener
- Interface handling action events such as button clicks
- BufferedReader
- Character stream class reading text line by line
Quick revision
- javac and java; single-file launch.
- Operators, Math class, loops and patterns.
- Classes, inheritance, polymorphism, interfaces, packages (javac -d .).
- Arrays, strings, Vector; exceptions.
- Graphics, AWT, listeners, file I/O.
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 compile a class into a package folder?
- Q2.What does Math.round(4.6) return?
- Q3.Why does Java need custom exceptions?
- Q4.How do you hide password characters in an AWT TextField?
- Q5.Which method handles button clicks?
- Q6.How do you read a text file line by line?
Long-answer questions
- Q1.Write a program demonstrating inheritance and method overriding.
- Q2.Write a program using interfaces and packages.
- Q3.Write a program with built-in and user-defined exceptions.
- Q4.Write an AWT program with event handling.
Stuck on this unit?
Message SBS on WhatsApp for help with Software Lab-IX (Programming in Java), or to ask about studying B.Sc IT at Synetic.
