Unit 1
- Skill #1
Algoritm: a step-by-step process to follow when completing a task or solving a problem.
The sequencing of the tasks and clear instructions are essential.
Many algorithms canbe used to achieve the same goal- through different processes.
- Unit 1.1-1.4
Syntax Error
a mistake in the program where the rules of the language are not followed
Logic Error
mistakes in the program causes it to behave inccorrectly or unexpectedly
Run-Time Error
mistakes in the program that occurs during the execution of the program
Data Types
The type of information that available can store and what you can do with that information. There are five types:
1- Integer: Whole numbers.
2- Double: Numbers with decimals.
3- Boolean: Absolute. True or false.
4- String: Number of words, letters etc.
5- Char: One singular character.
public class Example {
public static void main(String[] args) {
public: acessible from anywhere in your program.
class: blueprint for objects in java, all code must be in classes.
static: belongs to the class itself, not to an object.
void: method does not return anything.
main: entry point of java.
- 1.5-1.9
All of the following are the same:
a = a + 1;
a += 1;
a++;
Input
In order to have input from user you have to "Scanner in=new Scanner(System.in);"
- 1.3 (codehs)
Literals and Escape Sequences
A literal is a fixed value, a constant.
Using "\" in order to add punctuation marks to the written output
Example: System.out.println("She said \"Hey!\"");
She said "Hey!"
\n = new line
\t = tab
- 1.4 (codehs)
Errors
When you give no value to a variable, the error of variable might NOT be INITIALIZED occurs.
If a variable is assigned to the wrong data tye, ERROR: INCOMPATIBLE TYPES occurs.
Objectss and Calling Methods
Use scanner to get input. Here is an example of using scanner:
Java Code
import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter weight (kg): ");
double weight = scanner.nextDouble();
System.out.print("Enter height (m): ");
double height = scanner.nextDouble();
double bmi = weight / (height * height);
System.out.println("BMI: ", bmi);
}
}
- 1.5) Casting (codehs)
Widening
Converting an integer to a double.
Narrowing
Converting a double to an integer. Note: even is the double is 9.9, norrowing converts it into 9 not 10. Rounding can be made by (+0.5) while converting.
- 1.7) API & Libraries
java.lang = already uploaded libraries ( String, math, system, runtime )
java.util = the libraries you upload ( Scanner, tandom, ArrayList, HashMap)
Java package = a collection of related classes grouped together.
API
Application Programming ınterface. Provides documentation that explains what hose libraries do and how to call the methods or actions. It is like an instruction manual.
CSAwesome Notes — Unit 1
- Getting started with Java, variables, primitive types, expressions, input, and basic APIs.
Contents
- Minimal program
- Primitive types & Strings
- Expressions & precedence
- Assignment, compound ops, ++/--
- Type conversion (casting)
- Input with
Scanner - Common errors
- Quick charts
- Mini-drills
Minimal program
Your smallest Java file uses a public class named like the file and a main method as the entry point.
public class Main {
public static void main(String[] args) {
System.out.println("hi");
}
}Primitive types & Strings
Java primitives: int (32-bit), double (64-bit), boolean (true/false), char (16-bit). String is a class (sequence of characters).
int count = 0;
double price = 19.99;
boolean ok = true;
char grade = 'A';
String name = "Ada";
System.out.println("Hello " + name);Expressions & precedence
Precedence: () > * / % > + -. Integer division truncates; one double operand makes the whole expression double.
int a = 7, b = 3;
System.out.println(a / b); // 2 (int division)
System.out.println(a / 3.0); // 2.3333333333333335
System.out.println("Total: " + 5 + 3); // "Total: 53"
System.out.println("Total: " + (5 + 3)); // "Total: 8"Assignment, compound ops, ++/--
These are equivalent: a = a + 1; • a += 1; • a++;
Prefix vs postfix matters only when used inside an expression or print.
int x = 5;
x += 3; // 8
System.out.println(x++); // prints 8, then x becomes 9
System.out.println(++x); // x becomes 10, then prints 10Type conversion (casting)
Widening (e.g., int→double) is automatic. Narrowing (double→int) needs an explicit cast and drops the fraction.
Cast the whole expression when you convert.
double y = 2.9;
int k = (int) y; // 2 (truncation)
int total = 284;
// WRONG: loses fraction first, then casts → 94.0
double avgWrong = (double)(total / 3);
// RIGHT: cast before division → 94.666...
double avgRight = (double) total / 3;
// "lossy conversion" fix: cast the result or use double destination
int i = (int)(2 * 2.2); // 4
double dx = 2 * 2.2; // 4.4Input with Scanner
Import, construct with System.in, then call typed methods like nextInt(), nextDouble().
import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter weight (kg): ");
double weight = scanner.nextDouble();
System.out.print("Enter height (m): ");
double height = scanner.nextDouble();
double bmi = weight / (height * height);
System.out.println("BMI: " + bmi);
}
}Common errors
- Syntax error — violates language rules (e.g., missing semicolon).
- Logic error — code compiles but behavior is wrong (e.g., integer division when you wanted decimal).
- Run-time error — occurs while executing (e.g., input mismatch).
- Incompatible types / lossy conversion — assigning double to int without a cast.
- Variable might not have been initialized — using a local variable before assignment.
Quick charts
Mini-drills
Copy, run, and predict outputs before you execute.
// 1) Integer vs double division
int p = 5, q = 2;
System.out.println(p / q); // ?
System.out.println(p / (double)q); // ?
// 2) Precedence sanity
System.out.println(2 + 3 * 4); // ?
System.out.println((2 + 3) * 4); // ?
// 3) Safe average
int s1 = 87, s2 = 92, s3 = 70;
double avg = (s1 + s2 + s3) / 3.0;
System.out.printf("avg=%.2f%n", avg);
// 4) Overflow demo
System.out.println(Integer.MAX_VALUE + 1); // ?Fivable Notes — Unit 1
Contents
- 1.9 Method Signatures & Procedural Abstraction
- 1.10 Static (Class) Methods
- 1.11 Math Class
- 1.13 Object Creation & Constructors
- 1.14 Calling Instance Methods
- 1.15 String Manipulation
1.9 — Method Signatures & Procedural Abstraction
A method’s signature = its name + parameter types (order matters). Return type is not included. Supports overloading if signatures differ. Parameters = placeholders; arguments = actual values. Void methods perform actions; non-void return values. Procedural abstraction = use a method by what it does, not how it works.
class Sig {
int add(int a, int b) { return a + b; } // add(int,int)
double add(double a, double b) { return a + b; } // add(double,double)
void greet(String name) { System.out.println("Hi " + name); }
}1.10 — Static (Class) Methods
Static methods belong to the class, not an object.
Call with ClassName.method().
Useful for utilities (math, conversions). Cannot access instance vars or use this.
class Util {
static int max(int a, int b) { return (a > b) ? a : b; }
public static void main(String[] a){ System.out.println(Util.max(7, 9)); }
}1.11 — Math Class
Math provides static methods: abs(), pow(), sqrt(), random().
Math.random() → double [0.0,1.0). Scale with multiply + offset.
Common pitfalls: off-by-one random ranges, int overflow on pow().
class Dice {
public static void main(String[] a){
int die = (int)(Math.random()*6) + 1; // 1–6
double r = Math.sqrt(49); // 7.0
System.out.println(die + " " + r);
}
}1.13 — Object Creation & Constructors
Use new to allocate memory + call a constructor.
Each object has its own instance variables.
Constructors can be overloaded with different parameter lists.
Beware: assigning one object to another copies the reference, not the object.
class Student {
String name; int age;
Student(String n, int a){ name=n; age=a; }
}
class Demo {
public static void main(String[] a){ Student s = new Student("Sarah",16); }
}1.14 — Calling Instance Methods
Instance methods belong to objects → call with dot operator.
Depend on the object’s state.
Calling on null throws NullPointerException.
Different from static methods, which belong to the class.
class Dog {
String name; Dog(String n){ name=n; }
String desc(){ return name + " is great"; }
}
class Park {
public static void main(String[] a){ System.out.println(new Dog("Max").desc()); }
}1.15 — String Manipulation
Strings are immutable.
Key methods: length(), substring(), indexOf(), equals(), compareTo(), case conversion.
Concatenate with +.
Pitfalls: using == instead of equals(), off-by-one with substring, forgetting to store return value.
class S {
public static void main(String[] a){
String e="user@school.edu";
int at=e.indexOf("@");
String user=e.substring(0,at), domain=e.substring(at+1);
System.out.println(user + " | " + domain); // user | school.edu
}
}