UIL Computer Science Contest — Session 2

9:55 AM – 10:40 AM  |  Expanded Study Guide: Basic Java Syntax & Object-Oriented Programming

Basic Syntax of Java

Even though the official topics list covers everything that will be on the UIL CS Contest, it is not presented in the order you should study it. Below is a study-friendly outline — the same order as the original outline — with each bullet expanded into an explanation and a runnable Java example.

1. Arithmetic in Binary, Octal, and Hexadecimal

Computers store everything in binary (base 2). Programmers often use octal (base 8) and hexadecimal (base 16) as shorthand because they convert cleanly to binary. Java lets you write integer literals directly in any of these bases, and provides utility methods to convert between them.

BaseDigits UsedJava Literal PrefixExample
Binary (base 2)0–10b0b1010 = 10
Octal (base 8)0–70012 = 10
Decimal (base 10)0–9(none)10
Hexadecimal (base 16)0–9, A–F0x0xA = 10
public class NumberSystems {
    public static void main(String[] args) {
        int bin = 0b1010;     // binary literal
        int oct = 012;        // octal literal
        int hex = 0xA;        // hexadecimal literal

        System.out.println(bin);  // 10
        System.out.println(oct);  // 10
        System.out.println(hex);  // 10

        // Converting a decimal number to other bases (as text)
        int n = 42;
        System.out.println(Integer.toBinaryString(n)); // 101010
        System.out.println(Integer.toOctalString(n));  // 52
        System.out.println(Integer.toHexString(n));    // 2a

        // Parsing a string in a given base back into an int
        int fromBinary = Integer.parseInt("101010", 2); // 42
        System.out.println(fromBinary);
    }
}
UIL tip: practice converting by hand (division-remainder for decimal→binary, grouping bits by 3 for octal, grouping bits by 4 for hex) — many contest questions expect manual conversion, not a calculator.

2. Write the Hello World Program

Every Java program needs a class, and every standalone program needs a main method — this is where execution begins.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Output: Hello, World!

Notice the required pieces: the class name must match the filename (HelloWorld.java), public static void main(String[] args) is the fixed signature Java looks for, and System.out.println prints text followed by a newline (use System.out.print to omit the newline).

3. Character Set — ASCII and Unicode

A character set maps numbers to characters. ASCII uses 7 bits (0–127) to represent English letters, digits, and punctuation. Java's char type actually uses Unicode (16 bits), a superset of ASCII that can represent characters from virtually every written language. Because characters are just numbers under the hood, you can do arithmetic on them.

public class CharDemo {
    public static void main(String[] args) {
        char letter = 'A';
        int code = letter;              // implicit widening: char -> int
        System.out.println(code);       // 65 (ASCII/Unicode value of 'A')

        char next = (char) (letter + 1);
        System.out.println(next);       // B

        // Useful for looping through the alphabet
        for (char c = 'a'; c <= 'e'; c++) {
            System.out.print(c + " ");  // a b c d e
        }
    }
}

4. Formation of Variables

A variable is a named storage location. Java naming rules: must start with a letter, _, or $; cannot start with a digit; cannot be a reserved keyword (like class or int); and is case-sensitive. Convention: variables use camelCase.

int score = 100;         // valid
double _average = 88.5;  // valid, starts with underscore
String $name = "Alex";   // valid, but unusual style
// int 2ndPlace = 5;     // INVALID - cannot start with a digit
// int class = 5;        // INVALID - 'class' is a reserved keyword

5. Types — Primitive Types and Reference Types

Java has two categories of types. Primitive types hold raw values directly in memory. Reference types (everything else — objects, arrays, Strings) hold a reference (address) pointing to an object stored elsewhere.

CategoryExamplesDefault Value
Primitive — integerbyte, short, int, long0
Primitive — floating pointfloat, double0.0
Primitive — otherchar, boolean'\u0000', false
ReferenceString, int[], any class objectnull
public class TypesDemo {
    public static void main(String[] args) {
        int age = 17;                 // primitive
        double gpa = 3.95;            // primitive
        boolean isSenior = true;      // primitive
        char grade = 'A';             // primitive

        String name = "Jordan";       // reference type
        int[] scores = {90, 85, 100}; // reference type (array)

        System.out.println(name + " is " + age + " years old.");
    }
}

6. Statements and Expressions

An expression evaluates to a value (e.g., 3 + 4 evaluates to 7). A statement is a complete instruction, often built from one or more expressions, and ends with a semicolon.

int a = 3, b = 4;
int sum = a + b;      // "a + b" is an expression; the whole line is a statement
System.out.println(sum); // method call statement
if (sum > 5) {         // "sum > 5" is a boolean expression
    System.out.println("Big sum");
}

7. Simple Assignment Statements

The = operator stores the value of the right-hand expression into the variable on the left. Java also provides compound assignment shortcuts.

int x = 10;
x = x + 5;   // x is now 15
x += 5;      // shortcut for x = x + 5;  now x is 20
x -= 3;      // x = x - 3;               now x is 17
x *= 2;      // x = x * 2;               now x is 34
x /= 4;      // x = x / 4;               now x is 8 (integer division)

8. Operators

Java groups operators into families by what they act on:

Arithmetic: + - * / % ++ --

int a = 17, b = 5;
System.out.println(a + b);  // 22
System.out.println(a - b);  // 12
System.out.println(a * b);  // 85
System.out.println(a / b);  // 3   (integer division truncates)
System.out.println(a % b);  // 2   (remainder / modulo)

int c = 5;
System.out.println(c++);    // prints 5, THEN increments c to 6 (post-increment)
System.out.println(++c);    // increments c to 7 FIRST, then prints 7 (pre-increment)

Comparison: < ≤ > ≥ == !=

System.out.println(5 < 10);   // true
System.out.println(5 <= 5);   // true
System.out.println(5 > 10);   // false
System.out.println(5 >= 6);   // false
System.out.println(5 == 5);   // true  (equality)
System.out.println(5 != 5);   // false (inequality)

Boolean: ! && ||

boolean sunny = true, warm = false;
System.out.println(!sunny);           // false  (NOT)
System.out.println(sunny && warm);    // false  (AND - both must be true)
System.out.println(sunny || warm);    // true   (OR - at least one true)
// && and || are "short-circuit": if sunny is false, sunny && warm
// never even evaluates warm.

Bitwise: & | ~ ^

int a = 0b1100; // 12
int b = 0b1010; // 10
System.out.println(a & b);  // 0b1000 = 8   (AND, bit by bit)
System.out.println(a | b);  // 0b1110 = 14  (OR, bit by bit)
System.out.println(a ^ b);  // 0b0110 = 6   (XOR, bit by bit)
System.out.println(~a);     // -13          (NOT, flips every bit)

Shift: << >> >>>

int a = 4; // 0b0100
System.out.println(a << 1);  // 8   (shift left = multiply by 2)
System.out.println(a >> 1);  // 2   (shift right = divide by 2, keeps sign)

int neg = -8;
System.out.println(neg >> 1);   // -4 (arithmetic shift, sign-preserving)
System.out.println(neg >>> 1);  // large positive number (logical shift, fills with 0)

9. Conditionals: if-else, switch

int score = 82;

// if / else if / else
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C or lower");
}

// switch statement
int day = 3;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Some other day");
}

10. Loops: while, for, do-while, foreach

// while - checks condition BEFORE each iteration
int i = 0;
while (i < 3) {
    System.out.println("while: " + i);
    i++;
}

// for - compact loop with init, condition, and update
for (int j = 0; j < 3; j++) {
    System.out.println("for: " + j);
}

// do-while - runs body at least ONCE, checks condition AFTER
int k = 0;
do {
    System.out.println("do-while: " + k);
    k++;
} while (k < 3);

// foreach (enhanced for) - iterates over every element of a collection/array
int[] nums = {10, 20, 30};
for (int n : nums) {
    System.out.println("foreach: " + n);
}

11. Methods: Built-in, Library, User-defined

A method is a named, reusable block of code. Built-in/library methods ship with Java (like Math.sqrt); user-defined methods are ones you write yourself.

public class MethodsDemo {

    // user-defined method: takes two ints, returns their sum
    static int add(int a, int b) {
        return a + b;
    }

    // user-defined method: no return value (void)
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        greet("Taylor");                  // calling a user-defined method
        System.out.println(add(3, 4));    // 7

        // calling built-in / library methods
        System.out.println(Math.sqrt(16));      // 4.0
        System.out.println("hello".toUpperCase()); // HELLO
    }
}

12. Libraries: math, string, random

import java.util.Random;

public class LibraryDemo {
    public static void main(String[] args) {
        // Math library
        System.out.println(Math.max(3, 7));   // 7
        System.out.println(Math.abs(-5));     // 5
        System.out.println(Math.pow(2, 10));  // 1024.0

        // String library
        String s = "UIL Contest";
        System.out.println(s.length());            // 11
        System.out.println(s.substring(0, 3));      // UIL
        System.out.println(s.indexOf("Contest"));   // 4
        System.out.println(s.replace("UIL", "TX")); // TX Contest

        // Random library
        Random rand = new Random();
        int dieRoll = rand.nextInt(6) + 1; // random int from 1 to 6
        System.out.println(dieRoll);
    }
}

13. Arrays: 1-D and 2-D

public class ArrayDemo {
    public static void main(String[] args) {
        // 1-D array
        int[] scores = {88, 92, 79, 100};
        System.out.println(scores[0]);        // 88
        System.out.println(scores.length);    // 4
        scores[1] = 95;                       // modify an element

        for (int i = 0; i < scores.length; i++) {
            System.out.println(scores[i]);
        }

        // 2-D array (array of arrays) - like a grid/matrix
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println(grid[1][2]); // row 1, col 2 -> 6

        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                System.out.print(grid[row][col] + " ");
            }
            System.out.println();
        }
    }
}

14. Input / Output: Console, Files

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class IODemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Console input
        Scanner console = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = console.nextLine();
        System.out.println("Hello, " + name);

        // File input
        Scanner fileReader = new Scanner(new File("data.txt"));
        while (fileReader.hasNextLine()) {
            System.out.println(fileReader.nextLine());
        }
        fileReader.close();
    }
}

Once you have studied and internalized this basic syntax, you should start coding. Here are some great sites to practice on:

Object-Oriented Programming Expanded

Object-Oriented Programming (OOP) organizes code around objects — bundles of data (fields) and behavior (methods) — rather than around a sequence of instructions. There are four main principles you must master. Below, each one includes a plain-language definition and a Java example built around a shared Animal theme so you can see how they connect.

1. Abstraction

Hiding complex implementation details and exposing only what's necessary through a simple interface. You know what something does without needing to know how it does it.

abstract class Animal {
    abstract void makeSound(); // WHAT it does,
                                // not HOW
}

class Dog extends Animal {
    void makeSound() {          // the HOW is
        System.out.println("Woof!"); // hidden inside
    }
}

2. Encapsulation

Bundling data and the methods that operate on it into one unit (a class), and restricting direct access to internal fields — usually via private fields with public get/set methods.

class BankAccount {
    private double balance; // hidden

    public double getBalance() {
        return balance;
    }

    public void deposit(double amt) {
        if (amt > 0) balance += amt;
    }
}
// balance can't be changed directly
// from outside - only through deposit()

3. Inheritance

A class (subclass) can acquire the fields and methods of another class (superclass) using extends, allowing code reuse and the creation of specialized versions of a general class.

class Animal {
    String name;
    void eat() {
        System.out.println(name + " is eating");
    }
}

class Cat extends Animal {   // Cat inherits
    void meow() {             // eat() and name
        System.out.println(name + " says Meow");
    }
}

// Cat c = new Cat();
// c.name = "Whiskers";
// c.eat();   // inherited method
// c.meow();  // Cat's own method

4. Polymorphism

"Many forms" — the same method call behaves differently depending on the actual object type. In Java this is achieved through method overriding (runtime) and method overloading (compile-time).

class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}
class Dog extends Animal {
    void makeSound() {           // overriding
        System.out.println("Woof!");
    }
}
class Cat extends Animal {
    void makeSound() {           // overriding
        System.out.println("Meow!");
    }
}

Animal[] animals = { new Dog(), new Cat() };
for (Animal a : animals) {
    a.makeSound(); // Woof! then Meow!
    // same call, different behavior
}

Putting It All Together

Here is one small program that demonstrates all four pillars working together: abstraction (the abstract Shape class), encapsulation (private fields with getters), inheritance (Circle and Rectangle extend Shape), and polymorphism (calling area() behaves differently for each shape).

abstract class Shape {
    abstract double area(); // abstraction
}

class Circle extends Shape {           // inheritance
    private double radius;             // encapsulation

    Circle(double radius) { this.radius = radius; }

    double area() {                    // polymorphism (override)
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {        // inheritance
    private double width, height;      // encapsulation

    Rectangle(double w, double h) { width = w; height = h; }

    double area() {                    // polymorphism (override)
        return width * height;
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(3), new Rectangle(4, 5) };
        for (Shape s : shapes) {
            System.out.println("Area: " + s.area());
        }
    }
}
Output:
Area: 28.274333882308138
Area: 20.0

Tutorials to Get Started

What's Next

Now that you are familiar with the basic syntax of Java and the core ideas of object-oriented programming, download the current Topics List and study it very carefully. On the second page of the Topics list are the first 15 questions — these are questions you must not miss. Note that the last two questions are free response questions.

Let's now work through some of the questions on the written portion of the UIL Contest.