Java Core Concepts: I/O, Data Types, and Structures
Posted on Mar 28, 2025 in Computers
Unit 1: Java Fundamentals
Input, Output, and Basic Types
- Core Concepts: Scanner, print, println, printf, integers
-
Scanner:
- Gets input from the user and opens a console.
- Syntax:
Scanner scnr = new Scanner(System.in);
- Syntax for reading input:
- Integer:
int num = scnr.nextInt();
- Double:
double currentTemp = scnr.nextDouble();
- String (single word):
String userWord = scnr.next();
- String (entire line):
String userLine = scnr.nextLine();
-
Basic Print Methods:
System.out.print()
: Prints information; the cursor stays on the same line.System.out.println()
: Prints information; adds a new line after the text.System.out.printf()
: Prints formatted output, useful for multiple variables and specific number formats (like doubles).- Syntax (Concatenation with print/println):
System.out.println(variable1 + " hey " + variable2);
- Syntax (Formatted float/double):
System.out.printf("%.2f", myDouble);
(Prints myDouble rounded to 2 decimal places)
-
Comments: Lines ignored by the compiler, used for clarification.
- Single-line comment syntax:
// This is a comment for code
- Multi-line comment syntax:
/* This is for multiple lines */
-
Variables: Declaration uses variable type then name.
- Syntax (Integer):
int userAge = 1;
- Syntax (String):
String message = "fever";
- Initializing Variables: Integer variables (and others) are often assigned initial values upon declaration.
Doubles, Math, and Strings
- Core Concepts: Doubles, Math class, String class
- Floating-Point Numbers (Doubles): Numbers containing decimals.
%d
in printf
indicates a decimal integer.%f
in printf
indicates a floating-point number.%.nf
means print a floating-point number rounded to n decimal places. Ex: %.2f
%8.2f
means print a floating-point number, rounded to 2 decimal places, using 8 total spaces (including the decimal point and digits).
- Methods: A list of statements executed by invoking the method’s name (a method call).
- Main Method Syntax:
public static void main(String[] args) {}
public
: Modifier (access level)static
: Keyword (belongs to the class, not an object)void
: Return type (returns nothing)main
: Method name (entry point for execution)String[] args
: Parameter list (array of strings for command-line arguments)
- Example Method Stub Syntax:
public static int max(int x, int y) {}
public
: Modifierstatic
: Keywordint
: Return type (returns an integer)max
: Method name(int x, int y)
: Parameter list
- Math Class Methods:
Math.pow(x, y)
– Power: xyMath.sqrt(x)
– Square root of xMath.abs(x)
– Absolute value of x
- String Literals: A character sequence surrounded by double quotes.
- Syntax:
String pump = "up";
Control Flow and Logic
- Core Concepts: Branching (if/else), boolean logic, String comparison
- Logical Operators: Operate on boolean (true/false) operands.
- AND Syntax:
a && b
(True if both a and b are true) - OR Syntax:
a || b
(True if either a or b is true) - NOT Syntax:
!a
(True if a is false, false if a is true)
- String Comparison: Checks if two strings have the same sequence of characters. Returns true or false.
- Syntax:
str1.equals(str2);
Unit 2: Loops, Arrays, and Objects
File Input, Methods, and Loops
- Core Concepts: File input vs. Console input, more methods, for loops
- For Loop: Executes a block of code repeatedly. Consists of three parts:
- Loop variable initialization
- Loop expression (condition)
- Loop variable update
- Syntax:
int i; ... for (i = 0; i < N; ++i) { /* loop body */ }
- Increment Operator: Increases a variable’s value by 1. (e.g.,
i = i + 1
or ++i
or i++
) - Decrement Operator: Decreases a variable’s value by 1. (e.g.,
i = i - 1
or --i
or i--
) - String
split()
Method: Splits a string into an array of substrings based on a specified delimiter.- Syntax Example:
String sentence = "the only thing we have to fear is fear itself";
String[] words;
words = sentence.split(" "); // Split by space
System.out.println(Arrays.toString(words));
// prints: [the, only, thing, we, have, to, fear, is, fear, itself]
Arrays and Basic Objects
- Core Concepts: Arrays and Objects
- Array: An ordered list of items of a given data type.
- Syntax (Declaration and Creation):
dataType[] arrayName = new dataType[numElements];
Example: int[] gameScores = new int[4];
- Initializing an Array: Assigning initial values to array elements at declaration.
- Syntax:
dataType[] arrayName = {element1, element2, ...};
Example: int[] myArray = {5, 4, 7};
- Printing an Array: Use the
Arrays.toString()
method.- Syntax:
System.out.println("The scores array is " + Arrays.toString(arrayName));
Objects vs. Primitives
- Core Concepts: Objects vs. primitives in methods, NULL, equals
- Class: Describes a type, category, or concept of a ‘thing’ (e.g., Bird, Person, Fruit). It’s a blueprint.
- Object: An instance of a class; a specific ‘thing’ described by the class (e.g., a specific robin, me, a specific apple).
- Object Methods: Objects can have methods (functions associated with them).
- Mutator Methods: Change the state (data) of the object.
- Accessor Methods: Retrieve information about the object without changing it.
- Method Calls on Objects: Methods are called ‘on the object’ using dot notation (
.
).console.nextLine();
// console
is the object, Scanner
is its class/typeinput.toLowerCase();
// input
is the object, String
is its class/typename.toUpperCase();
// name
is the object, String
is its class/type
- The
split()
method in the String
class splits a single string into an array of strings based on a programmer-defined separator.
Wrapper Classes and ArrayList
- Primitive Types: Directly store data values (e.g.,
int
, double
, char
, boolean
). - Reference Types: Store references (memory addresses) to objects. All classes are reference types (e.g.,
String
, Scanner
, ArrayList
, and Wrapper Classes).
Primitive Types and Their Wrapper Classes
Reference Type (Wrapper Class) | Associated Primitive Type |
---|
Character | char |
Integer | int |
Double | double |
Boolean | boolean |
Long | long |
- Autoboxing and Unboxing: Automatic conversion between primitive types and their corresponding wrapper class objects.
- Autoboxing: Primitive to Wrapper Class
- Unboxing: Wrapper Class to Primitive
Autoboxing Examples
Action | Example Code |
---|
Assign primitive type to wrapper class variable | // Autoboxing of 20.25 (double) to a Double object
Double floorArea = 20.25;
Integer calcResult;
// Autoboxing of expression result (int) to an Integer object
calcResult = 5 / 2; // calcResult becomes Integer(2)
int num1 = 23;
// Autoboxing of num1 (int) to an Integer object
Integer num2 = num1;
|
Unboxing Examples
Action | Example Code |
---|
Assign wrapper class variable to primitive type | Double num1 = 3.14;
Character letter1 = 'A';
// Unboxing of Double object to double primitive
double num2 = num1;
// Unboxing of Character object to char primitive
char letter2 = letter1;
|
- ArrayList: An ordered, dynamic list (resizable array) of reference type items.
- Syntax:
ArrayList<ElementType> variableName = new ArrayList<ElementType>();
(Replace ElementType
with the class of objects the list will hold, e.g., String
, Integer
) - Common
ArrayList
Methods:add(element)
: Adds an element to the end of the list.add(index, element)
: Adds an element at a particular index.get(index)
: Returns the element at a particular index.remove(index)
: Removes the element at a particular index.size()
: Returns the number of items in the list.sort(comparator)
: Sorts the list (requires a Comparator
or elements must be Comparable
).
Unit 3: Advanced Data Structures
LinkedList
- LinkedList: Implements the
List
interface using a doubly-linked list structure. Elements are ordered. Efficient for adding/removing elements at the beginning or end.- Syntax:
LinkedList<ElementType> variableName = new LinkedList<ElementType>();
- Uses similar methods to
ArrayList
(add
, get
, remove
, size
) plus specific methods like addFirst
, addLast
, removeFirst
, removeLast
.
Set and Map Collections
- Set: A collection that does not allow duplicate elements and has no defined order (no indexes).
- Map: A collection that stores key-value pairs. Keys must be unique, but values can be duplicated. Keys are used to retrieve associated values.
- The collection of keys forms a Set.
- Syntax (using
HashMap
implementation):Map<String, Double> scores = new HashMap<String, Double>();
scores.put("Amy", 2.3);
scores.put("Moe", 4.1);
scores.put("Sue", 5.5);
scores.put("Lee", 2.3);
scores.put("Eve", 7.8);
- Iterating over a Map (example using keySet):
public void printEach(Map<String, Double> scoreboard) {
// Get the set of keys
for (String name : scoreboard.keySet()) {
// Get the value associated with the key
double score = scoreboard.get(name);
System.out.println(name + " --> " + score);
}
}
- Common implementations include
HashMap
, TreeMap
, LinkedHashMap
.
Queue and Stack Concepts
- Queue: A collection designed for holding elements prior to processing, following the First-In, First-Out (FIFO) principle.
- Think of it as a waiting line.
- Elements are added at the back (tail) and removed from the front (head).
- You typically interact with the element at the head of the queue.
- Common operations:
add
/offer
(insert), remove
/poll
(retrieve and remove), element
/peek
(retrieve without removing).
- Stack: A collection following the Last-In, First-Out (LIFO) principle.
- Think of it as a stack of plates.
- Elements are added (pushed) and removed (popped) from the same end (the top).
- Common operations:
push
(add to top), pop
(remove from top), peek
(view top without removing).