Projects

Project 1 — Basic Arithmetic (Java)

Takes two integers and prints their sum, difference, product, and quotient with a divide-by-zero check.

//Take two numbers and print the sum difference product and quotient
import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
    System.out.println("What is the first variable?");
    int number1 = scanner.nextInt();
    System.out.println(number1);
    System.out.println("What is the second variable?");
    int number2 = scanner.nextInt();
    System.out.println(number2);
    System.out.print("The sum is:");
    System.out.println(number1 + number2);
    System.out.println("The difference is:");
    System.out.println(number1 - number2);
    System.out.println("The product is:");
    System.out.println(number1 * number2);
    System.out.println("The division is:");
    if (number2 == 0) {
      System.out.println("number 2 is 0 so it can't be divided");
    } else {
      System.out.println(number1 / number2);
    }
  }
}

Project 2 — Ice Cream Sales (Java)

Reads 3 days of chocolate/vanilla/strawberry sales; prints total and average.

import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter the chocolate sales on the first day:");
    int ciko1 = scanner.nextInt();
    System.out.println("Please enter the vanilla sales on the first day:");
    int vanil1 = scanner.nextInt();
    System.out.println("Please enter the strawberry sales on the first day:");
    int straw1 = scanner.nextInt();
    System.out.println("Please enter the chocolate sales on the second day:");
    int ciko2 = scanner.nextInt();
    System.out.println("Please enter the vanilla sales on the second day:");
    int vanil2 = scanner.nextInt();
    System.out.println("Please enter the strawberry sales on the second day:");
    int straw2 = scanner.nextInt();
    System.out.println("Please enter the chocolate sales on the third day:");
    int ciko3 = scanner.nextInt();
    System.out.println("Please enter the vanilla sales on the third day:");
    int vanil3 = scanner.nextInt();
    System.out.println("Please enter the strawberry sales on the third day:");
    int straw3 = scanner.nextInt();
    int total = (ciko1+vanil1+straw1+ciko2+vanil2+straw2+ciko3+vanil3+straw3);
    double average1 = (total/6);
    int average = (total/6);
    System.out.println(total);
    System.out.println(average1);
    System.out.println(average);
  }
}

Project 3 — Rocket to the Stars (Java)

User enters mass (kg), engine force (N), burn time (s). Prints acceleration, final velocity, and altitude.

import java.util.Scanner;
public class RocketToTheStars {
  public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter rocket mass (kg): ");
    double mass = scanner.nextDouble();
    System.out.print("Enter engine force (N): ");
    double force = scanner.nextDouble();
    System.out.print("Enter burn time (s): ");
    double time = scanner.nextDouble();
    double a = force / mass;
    double v = a * time;
    double h = 0.5 * a * time * time;
    System.out.println();
    System.out.println("Net acceleration (m/s^2): " + a);
    System.out.println("Net acceleration (int): " + (int)a);
    System.out.println();
    System.out.println("Final velocity (m/s): " + v);
    System.out.println("Final velocity (int): " + (int)v);
    System.out.println();
    System.out.println("Altitude reached (m): " + h);
    System.out.println("Altitude (int): " + (int)h);
    System.out.println();
    System.out.println(" /\\");
    System.out.println(" / \\");
    System.out.println(" |====|");
    System.out.println(" |    |");
    System.out.println(" |NASA|");
    System.out.println("  ||||");
    System.out.println("  ||||");
  }
}

Project 4 — Square Root (SICP-Style, No sqrt)

Newton's method with 3 manual steps, no loops or Math.sqrt.

import java.util.Scanner;
public class SqrtNewtonThreeSteps {
  public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter N: ");
    double N = scanner.nextDouble();
    double x0 = N / 2.0;
    double x1 = 0.5 * (x0 + N / x0);
    double x2 = 0.5 * (x1 + N / x1);
    double x3 = 0.5 * (x2 + N / x2);
    System.out.println("Initial guess x0 = " + x0);
    System.out.println("x1 = " + x1);
    System.out.println("x2 = " + x2);
    System.out.println("x3 = " + x3);
    System.out.println("Approx sqrt(N) ≈ " + x3);
    System.out.println("Approx sqrt(N) (int) = " + (int)x3);
  }
}

Project 5 — Princeton Java #25 Wind Chill

Calculates wind chill from temperature and wind speed.

import java.util.Scanner;
public class WindChill {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter the t value:");
    double t = scanner.nextDouble();
    System.out.println("Please enter the v value:");
    double v = scanner.nextDouble();
    double w = 35.74 + 0.6215*t + (0.4275*t - 35.75) * Math.pow(v, 0.16);
    System.out.println("Temperature = " + t);
    System.out.println("Wind speed = " + v);
    System.out.println("Wind chill = " + w);
  }
}

Project 6 — Princeton Java #26 Polar Coordinates

Reads Cartesian (x,y) and converts to polar coordinates (r,θ).

import java.util.Scanner;
public class PolarCoordinates {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter x value:");
    double x = scanner.nextDouble();
    System.out.println("Please enter y value:");
    double y = scanner.nextDouble();
    double r = Math.sqrt(x*x + y*y);
    double theta = Math.atan2(y, x);
    System.out.println("r = " + r);
    System.out.println("theta = " + theta);
  }
}

Project 7 — Princeton Java #29 Day of Week

Uses Zeller’s congruence to compute the day of the week.

import java.util.Scanner;
public class DayOfWeek {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter the day:");
    int day = scanner.nextInt();
    System.out.println("Please enter the month:");
    int month = scanner.nextInt();
    System.out.println("Please enter the year:");
    int year = scanner.nextInt();
    int y0 = year - (14 - month) / 12;
    int x = y0 + y0/4 - y0/100 + y0/400;
    int m0 = month + 12 * ((14 - month) / 12) - 2;
    int d0 = (day + x + (31*m0)/12) % 7;
    System.out.println(d0);
  }
}

Project 8 — Web Problem: Divisibility (Java)

Checks if two integers are both divisible by 7; prints True if both are, otherwise False.

import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the first number");
    int num1 = scanner.nextInt();
    System.out.println("Enter the second number");
    int num2 = scanner.nextInt();
    if ((num1 % 7 == 0) && (num2 % 7 == 0)){
      System.out.println("True");
    } else {
      System.out.println("False");
    }
  }
}

Project 9 — Web Exercise: Swap (Java)

Reads two integers, swaps their values using a temporary variable, and prints the updated numbers.

import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the first number:");
    int num1 = scanner.nextInt();
    System.out.println("Enter the second number:");
    int num2 = scanner.nextInt();
    int temp = 0;
    temp = num1;
    num1 = num2;
    num2 = temp;
    System.out.println("Updated First number is :" + num1);
    System.out.println("Updated Second number is : " + num2);
  }
}

Project 10 — Web Exercise: Ordered (Java)

Reads three integers and prints True if the middle number is between the other two; otherwise False.

import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter 3 numbers:");
    int x = scanner.nextInt();
    int y = scanner.nextInt();
    int z = scanner.nextInt();
    if (((x >= y) && (y >= z)) || ((z >= y) && (y >= x))){
      System.out.println("True");
    } else {
      System.out.println("False");
    }
  }
}

Project 11 — Pen & Paper → Code: Grade Calculator (Java)

Pen & Paper notes: Read three scores, compute total, average, and letter grade.

import java.util.Scanner;
public class MyProgram {
  public static int computeTotal(int a, int b, int c) { return a + b + c; }
  public static double computeAverage(int total) { return total / 3.0; } // avoid int division
  public static String letterGrade(double average) {
    if (average >= 90) return "A";
    else if (average >= 80) return "B";
    else if (average >= 70) return "C";
    else if (average >= 60) return "D";
    else return "F";
  }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the value a: ");
    int a = scanner.nextInt();
    System.out.print("Please enter the value b: ");
    int b = scanner.nextInt();
    System.out.print("Please enter the value c: ");
    int c = scanner.nextInt();
    int total = computeTotal(a, b, c);
    double average = computeAverage(total);
    String grade = letterGrade(average);
    System.out.println("Total = " + total);
    System.out.println("Average = " + average);
    System.out.println("Letter = " + grade);
    scanner.close();
  }
}

Project 12 — Pen & Paper → Code: Triangle Classifier (Java)

Pen & Paper notes: Validate triangle then classify as equilateral/isosceles/scalene.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter the side a");
    int a = scanner.nextInt();
    System.out.println("Please enter the next side");
    int b = scanner.nextInt();
    System.out.println("Please enter the next next side");
    int c = scanner.nextInt();
    printResult(a, b, c);
    scanner.close();
  }
  static boolean isTriangle(int a, int b, int c) { return (a + b > c) && (a + c > b) && (b + c > a); }
  static String triangleType(int a, int b, int c) {
    if (a == b && b == c) return "equilateral";
    else if (a == b || a == c || b == c) return "isosceles";
    else return "scalene";
  }
  static void printResult(int a, int b, int c) {
    if (!isTriangle(a, b, c)) { System.out.println("Not a triangle"); }
    else { String triangleType = triangleType(a, b, c); System.out.println(triangleType); }
  }
}

Princeton Web Exercise 2 — RGBtoYIQ.java

Converts 8-bit RGB to YIQ (normalized 0–1) and prints Y, I, Q.

import java.util.Scanner;
public class RGBtoYIQ {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int R = scanner.nextInt();
    int G = scanner.nextInt();
    int B = scanner.nextInt();
    double r = R / 255.0;
    double g = G / 255.0;
    double b = B / 255.0;
    double Y = 0.299 * r + 0.587 * g + 0.114 * b;
    double I = 0.596 * r - 0.274 * g - 0.322 * b;
    double Q = 0.211 * r - 0.523 * g + 0.312 * b;
    System.out.printf("Y=%.6f I=%.6f Q=%.6f%n", Y, I, Q);
  }
}

Princeton Web Exercise 3 — YIQtoRGB.java

Converts YIQ back to 8-bit RGB (values clamped to [0,1] before scaling).

import java.util.Scanner;
public class YIQtoRGB {
  private static double clamp(double x, double lo, double hi) { return Math.max(lo, Math.min(hi, x)); }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double Y = scanner.nextDouble();
    double I = scanner.nextDouble();
    double Q = scanner.nextDouble();
    double r = Y + 0.956 * I + 0.621 * Q;
    double g = Y - 0.272 * I - 0.647 * Q;
    double b = Y - 1.106 * I + 1.703 * Q;
    r = clamp(r, 0.0, 1.0);
    g = clamp(g, 0.0, 1.0);
    b = clamp(b, 0.0, 1.0);
    int R = (int)Math.round(r * 255);
    int G = (int)Math.round(g * 255);
    int B = (int)Math.round(b * 255);
    System.out.println(R + " " + G + " " + B);
  }
}

Princeton Web Exercise 4 — CMYKtoRGB.java

Converts CMYK to 8-bit RGB.

import java.util.Scanner;
public class CMYKtoRGB {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double C = scanner.nextDouble();
    double M = scanner.nextDouble();
    double Y = scanner.nextDouble();
    double K = scanner.nextDouble();
    int R = (int)Math.round(255 * (1 - C) * (1 - K));
    int G = (int)Math.round(255 * (1 - M) * (1 - K));
    int B = (int)Math.round(255 * (1 - Y) * (1 - K));
    System.out.println(R + " " + G + " " + B);
  }
}

Princeton Web Exercise 5 — DivideByZero.java

Demonstrates integer vs. floating-point division/mod by zero with try/catch.

public class DivideByZero {
  public static void main(String[] args) {
    try { System.out.println("17 / 0 = " + (17 / 0)); }
    catch (ArithmeticException e) { System.out.println("17 / 0 -> ArithmeticException: " + e.getMessage()); }
    try { System.out.println("17 % 0 = " + (17 % 0)); }
    catch (ArithmeticException e) { System.out.println("17 % 0 -> ArithmeticException: " + e.getMessage()); }
    System.out.println("17.0 / 0.0 = " + (17.0 / 0.0));
    System.out.println("17.0 % 0.0 = " + (17.0 % 0.0));
  }
}

Princeton Web Exercise 6 — FibonacciWord.java

Builds Fibonacci words f(n) = f(n−1) + f(n−2) starting from "a","b".

public class FibonacciWord {
  public static void main(String[] args) {
    String a = "a";
    String b = "b";
    System.out.println("f(0) = " + a);
    System.out.println("f(1) = " + b);
    for (int n = 2; n <= 10; n++) {
      String c = b + a;
      System.out.println("f(" + n + ") = " + c);
      a = b; b = c;
    }
  }
}

Princeton Web Exercise 7 — StdStats.java

Reads doubles from stdin; prints mean and sample standard deviation.

import java.util.Scanner;
import java.util.ArrayList;
public class StdStats {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    ArrayList<Double> list = new ArrayList<>();
    while (scanner.hasNextDouble()) list.add(scanner.nextDouble());
    int n = list.size();
    if (n == 0) {
      System.out.println("mean = NaN");
      System.out.println("sample stddev = NaN");
      return;
    }
    double sum = 0.0;
    for (double v : list) sum += v;
    double mean = sum / n;
    double sq = 0.0;
    for (double v : list) sq += (v - mean) * (v - mean);
    double sampleVar = (n > 1) ? sq / (n - 1) : Double.NaN;
    double sampleStd = Math.sqrt(sampleVar);
    System.out.println("mean = " + mean);
    System.out.println("sample stddev = " + sampleStd);
  }
}

Princeton Web Exercise 8 — AllEqual3.java

Checks if three integers are all equal.

import java.util.Scanner;
public class AllEqual3 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    boolean all = (a == b) && (b == c);
    System.out.println(all);
  }
}

Princeton Web Exercise 9 — Distance.java

Computes Euclidean distance between (x1,y1) and (x2,y2).

import java.util.Scanner;
public class Distance {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double x1 = scanner.nextDouble();
    double y1 = scanner.nextDouble();
    double x2 = scanner.nextDouble();
    double y2 = scanner.nextDouble();
    double dx = x2 - x1;
    double dy = y2 - y1;
    double d = Math.sqrt(dx * dx + dy * dy);
    System.out.println(d);
  }
}

Princeton Web Exercise 12 — TriangleArea.java

Heron's formula from side lengths a, b, c.

import java.util.Scanner;
public class TriangleArea {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double a = scanner.nextDouble();
    double b = scanner.nextDouble();
    double c = scanner.nextDouble();
    double s = (a + b + c) / 2.0;
    double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
    System.out.println(area);
  }
}

Princeton Web Exercise 13 — EquatorialToHorizontal.java

Converts equatorial (declination, hour angle) to horizontal (altitude, azimuth).

import java.util.Scanner;
public class EquatorialToHorizontal {
  private static double toRad(double deg) { return Math.toRadians(deg); }
  private static double toDeg(double rad) { return Math.toDegrees(rad); }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double phi = toRad(scanner.nextDouble());
    double delta = toRad(scanner.nextDouble());
    double H = toRad(scanner.nextDouble());
    double sinAlt = Math.sin(phi) * Math.sin(delta) + Math.cos(phi) * Math.cos(delta) * Math.cos(H);
    double Alt = Math.asin(sinAlt);
    double numerator = Math.cos(phi) * Math.sin(delta) - Math.sin(phi) * Math.cos(delta) * Math.cos(H);
    double denom = Math.cos(Alt);
    double Az = Math.acos(numerator / denom);
    System.out.printf("Altitude(deg)=%.6f%n", toDeg(Alt));
    System.out.printf("Azimuth(deg)=%.6f%n", toDeg(Az));
  }
}

Princeton Web Exercise 14 — BMI.java

Computes Body Mass Index from weight and height.

import java.util.Scanner;
public class BMI {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double w = scanner.nextDouble();
    double h = scanner.nextDouble();
    double bmi = w / (h * h);
    System.out.println(bmi);
  }
}

Princeton Web Exercise 15 — CarLoan.java

Monthly payment for fixed-rate car loan.

import java.util.Scanner;
public class CarLoan {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double P = scanner.nextDouble();
    int Y = scanner.nextInt();
    double R = scanner.nextDouble();
    int n = 12 * Y;
    double r = (R / 100.0) / 12.0;
    double payment = (P * r) / (1.0 - Math.pow(1.0 + r, -n));
    System.out.println(payment);
  }
}

Princeton Web Exercise 16 — Trig.java

Evaluates basic trig functions and their inverses for a given degree input.

import java.util.Scanner;
public class Trig {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double deg = scanner.nextDouble();
    double rad = Math.toRadians(deg);
    System.out.println("sin = " + Math.sin(rad));
    System.out.println("cos = " + Math.cos(rad));
    System.out.println("tan = " + Math.tan(rad));
    System.out.println("asin(sin) = " + Math.toDegrees(Math.asin(Math.sin(rad))));
    System.out.println("acos(cos) = " + Math.toDegrees(Math.acos(Math.cos(rad))));
    System.out.println("atan(tan) = " + Math.toDegrees(Math.atan(Math.tan(rad))));
  }
}

Princeton Web Exercise 17 — Barycenter.java

Distance r1 from mass m1 to the system barycenter for a two-body system.

import java.util.Scanner;
public class Barycenter {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double m1 = scanner.nextDouble();
    double m2 = scanner.nextDouble();
    double a = scanner.nextDouble();
    double r1 = a * m2 / (m1 + m2);
    System.out.println(r1);
  }
}

Princeton Web Exercise 18 — GuessTheBiggerStrategy.java

Threshold-based strategy simulation: see one number, decide to keep or switch.

import java.util.Scanner;
import java.util.Random;
public class GuessTheBiggerStrategy {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int T = scanner.nextInt();
    int trials = scanner.nextInt();
    int wins = 0;
    Random rng = new Random();
    for (int k = 0; k < trials; k++) {
      int a = rng.nextInt(101);
      int b = rng.nextInt(101);
      boolean revealA = rng.nextBoolean();
      int seen = revealA ? a : b;
      boolean chooseSeen = (seen >= T);
      int chosen = chooseSeen ? seen : (revealA ? b : a);
      int other = chooseSeen ? (revealA ? b : a) : seen;
      if (chosen >= other) wins++;
    }
    double rate = 100.0 * wins / trials;
    System.out.printf("Win rate ≈ %.2f%%%n", rate);
  }
}

Princeton Web Exercise 2 — GradeInRange.java

Reads an int grade and checks if 90 ≤ grade ≤ 100 using a chained comparison fix.

import java.util.Scanner;
public class GradeInRange {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int grade = scanner.nextInt();
    boolean isA = (90 <= grade && grade <= 100);
    System.out.println(isA);
  }
}

Princeton Web Exercise 6 — CastDemo.java

Shows integer division vs. proper floating-point division.

public class CastDemo {
  public static void main(String[] args) {
    double x1 = (double) (3 / 5); // integer division first → 0.0
    double x2 = 3 / 5.0;          // correct: 0.6
    System.out.println(x1);
    System.out.println(x2);
  }
}

Princeton Web Exercise 7 — IntOverflow.java

Demonstrates overflow when multiplying ints before widening to long.

public class IntOverflow {
  public static void main(String[] args) {
    int x = 65536;
    long wrong = x * x;       // int*int overflows before widening
    long correct = (long) x * x; // widen first, then multiply in long
    System.out.println(wrong);
    System.out.println(correct);
  }
}

Princeton Web Exercise 8 — SqrtEquality.java

Floating-point quirks: sqrt(2)*sqrt(2) vs 2.

public class SqrtEquality {
  public static void main(String[] args) {
    boolean eq = (Math.sqrt(2) * Math.sqrt(2) == 2);
    System.out.println(eq);
    System.out.println(Math.sqrt(2) * Math.sqrt(2)); // show tiny rounding error
  }
}

Princeton Web Exercise 14 — LeapYear.java

Determines if a given year is a leap year. (This version uses command-line args.)

public class LeapYear {
  public static void main(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: java LeapYear <year>");
      return;
    }
    try {
      int y = Integer.parseInt(args[0]);
      boolean leap = (y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0));
      System.out.println(leap);
    } catch (NumberFormatException e) {
      System.out.println("Invalid year");
    }
  }
}

Princeton Web Exercise 15 — CompileError_ThreeLiteral.java (intended to FAIL)

Demonstrates a compile-time type error.

public class CompileError_ThreeLiteral {
  public static void main(String[] args) {
    int a = 27 * "three"; // compile-time error: bad operand types
    System.out.println(a);
  }
}

Working variant — MultiplyParsed.java

Compiles and runs: parse "3" to an int before multiplying.

public class MultiplyParsed {
  public static void main(String[] args) {
    int a = 27;
    int b = Integer.parseInt("3");
    System.out.println(a * b);
  }
}

Princeton Web Exercise 16 — UninitializedLocal.java (intended to FAIL)

Shows compile error for using an uninitialized local variable.

public class UninitializedLocal {
  public static void main(String[] args) {
    double x;
    System.out.println(x); // compile-time error: variable x might not have been initialized
  }
}

Princeton Web Exercise 17 — DivisionMix.java

Contrasts int/int, int/double, double/int, double/double.

public class DivisionMix {
  public static void main(String[] args) {
    int threeInt = 3;
    int fourInt = 4;
    double threeDouble = 3.0;
    double fourDouble = 4.0;
    System.out.println(threeInt / fourInt);
    System.out.println(threeInt / fourDouble);
    System.out.println(threeDouble / fourInt);
    System.out.println(threeDouble / fourDouble);
  }
}

Princeton Web Exercise 24 — FahrenheitToCelsius.java

Highlights the integer division pitfall in temperature conversion.

import java.util.Scanner;
public class FahrenheitToCelsius {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double F = scanner.nextDouble();
    double wrong = (F - 32) * (5 / 9);   // integer division → 0
    double correct = (F - 32) * (5.0 / 9); // proper double arithmetic
    System.out.println(wrong);
    System.out.println(correct);
  }
}

Princeton Web Exercise 25 — ExponentiationDemo.java

Shows Math.pow vs. multiplication; warns that ^ is XOR.

import java.util.Scanner;
public class ExponentiationDemo {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double a = scanner.nextDouble();
    double squaredByPow = Math.pow(a, 2);
    double squaredByMul = a * a;
    System.out.println(squaredByPow);
    System.out.println(squaredByMul);
  }
}
// (If you write a ^ 2 with integers, that’s bitwise XOR, not exponentiation.)

Princeton Web Exercise 26 — BooleanLiterals.java

Legal vs illegal boolean literals.

public class BooleanLiterals {
  public static void main(String[] args) {
    boolean b = true; // legal
    System.out.println(b);
  }
}
// (If you purposely try these, they will FAIL to compile:
// boolean b = 1; boolean b = "true"; boolean b = True;)

Princeton Web Exercise 27 — MaxWithoutIf.java

Computes max(a,b) using arithmetic/abs; no if.

import java.util.Scanner;
public class MaxWithoutIf {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int max = (a + b + Math.abs(a - b)) / 2;
    System.out.println(max);
  }
}

Princeton Web Exercise 28 — CubicDiscriminant.java

Computes cubic discriminant Δ for x³ + b x² + c x + d.

import java.util.Scanner;
public class CubicDiscriminant {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double b = scanner.nextDouble();
    double c = scanner.nextDouble();
    double d = scanner.nextDouble();
    double disc = (b*b)*(c*c) - 4*Math.pow(c, 3) - 4*Math.pow(b, 3)*d - 27*Math.pow(d, 2) + 18*b*c*d;
    System.out.println(disc);
  }
}

Princeton Web Exercise 30 — PoisonParentheses.java (intended to FAIL)

Shows why -(2147483648) is illegal as an int literal.

public class PoisonParentheses {
  public static void main(String[] args) {
    int x = -(2147483648); // compile-time error: integer number too large
    System.out.println(x);
  }
}

Working variant — PoisonParenthesesFixed.java

Correct ways to express Integer.MIN_VALUE or negate a long literal.

public class PoisonParenthesesFixed {
  public static void main(String[] args) {
    int ok = -2147483648;      // valid: MIN_VALUE as unary minus of literal
    long alsoOk = -(2147483648L); // long literal, then unary minus
    System.out.println(ok);
    System.out.println(alsoOk);
  }
}

Project — Turtle & Car (Java)

Simple OOP demo with two classes (Turtle and Car) and a runner.

// ThingsRunner.java
public class ThingsRunner {
  public static void main(String[] args) {
    Turtle turtle1 = new Turtle(15, 18, 0, 0, "Doruk");
    turtle1.Forward();
    turtle1.printOut();
    turtle1.moveTo(8, 8);
    turtle1.printOut();
    turtle1.setWidth(192);
    turtle1.setHeight(89);
    turtle1.printOut();

    Car car1 = new Car("Toyota", 180, 150, 0, 0);
    car1.drive(50);
    car1.printOut();
    car1.setWidth(200);
    car1.setHeight(160);
    car1.printOut();
    car1.openDoor();
    car1.printOut();
    car1.closeDoor();
    car1.printOut();
  }
}

// Turtle.java
public class Turtle {
  private double width, height, xPos, yPos;
  private String name;

  public Turtle(double width,double height,double xPos,double yPos,String name){
    this.width=width;
    this.height=height;
    this.xPos=xPos;
    this.yPos=yPos;
    this.name=name;
  }
  public void Forward(){ xPos += 1; }
  public void Forward(int pixels){ xPos += pixels; }
  public void backward(int pixels){ xPos -= pixels; }
  public void moveTo(int x,int y){ xPos=x; yPos=y; }
  public void setWidth(double w){ width=w; }
  public void setHeight(double h){ height=h; }
  public void printOut(){ System.out.println(toString()); }
  public String toString(){
    return "Turtle{"+"name='"+name+'\''
      +", width="+width+", height="+height+", xPos="+xPos+", yPos="+yPos+'}';
  }
}

// Car.java
public class Car {
  private String model;
  private double width,height,kmDriven,acceleration;
  private boolean doorOpen;

  public Car(String model,double width,double height,double kmDriven,double acceleration){
    this.model=model;
    this.width=width;
    this.height=height;
    this.kmDriven=kmDriven;
    this.acceleration=acceleration;
    this.doorOpen=false;
  }
  public void drive(double distance){ kmDriven += distance; }
  public void setWidth(double w){ width = w; }
  public void setHeight(double h){ height = h; }
  public void openDoor(){ doorOpen = true; }
  public void closeDoor(){ doorOpen = false; }
  public void printOut(){
    System.out.println("Car{"
      +"model='"+model+'\''
      +", width="+width
      +", height="+height
      +", kmDriven="+kmDriven
      +", acceleration="+acceleration
      +", doorOpen="+doorOpen+'}');
  }
}
Click here for more →