Introduction to Java
Java is a versatile, object-oriented programming language that runs on the Java Virtual Machine (JVM). One of Java's core strengths is its "write once, run anywhere" capability, meaning compiled Java code can execute on any platform with a JVM installed.
Command Line Basics
Understanding the command line interface is essential for Java developers. Here are fundamental CMD commands:
Changing Drives
D:
Switches to the D: drive.
Viewing Directory Contents
dir
Displays all files and folders in the current directory, including hidden items.
Navigating Directories
cd directory_name
Enters a single directory.
cd ..
Returns to the parent directory.
cd directory1\directory2
Enters a nested directory structure.
cd\
Returns to the root directory of the current drive.
Screen Management
cls
Clears the console screen.
exit
Closes the command prompt window.
Environment Variables
To execute programs from any directory without typing the full path, add the application's locasion to the system's PATH environment variable:
- Right-click "This PC" and select Properties
- Navigate to Advanced System Settings
- Click Environment Variables
- Locate the "Path" variable and add the application directory
Java Development Environment
JDK, JRE, and JVM
JDK (Java Development Kit) is the complete development kit containing:
- JVM (Java Virtual Machine): Executes Java bytecode
- Core Libraries: Pre-written Java classes
- Development Tools: javac (compiler), java (launcher), jdb (debugger)
JRE (Java Runtime Enviroment) includes the JVM and core libraries, sufficient for running Java applications.
Relationship: JDK → JRE → JVM
Directory Structure (JDK)
bin: Executable commands (javac, java)conf: Configuration filesinclude: Platform-specific header filesjmods: Module fileslegal: License documentationlib: Additional libraries
Your First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld");
}
}
Save this as HelloWorld.java and compile with:
javac HelloWorld.java
java HelloWorld
Core Language Elements
Comments
Comments provide explanatory text and are ignored by the compiler:
// Single-line comment
/*
* Multi-line
* comment
*/
Keywords
Keywords are reserved words with special meaning in Java, such as class, public, static, void, if, else, for, while.
Literals
Literals are constant values that appear directly in code:
| Type | Description | Examples |
|---|---|---|
| Integer | Whole numbers | 666, -88 |
| Floating-point | Decimal numbers | 13.14, -5.21 |
| String | Text in double quotes | "HelloWorld" |
| Character | Single character in single quotes | 'A', '0' |
| Boolean | Logical values | true, false |
| Null | Empty reference | null |
public class LiteralsDemo {
public static void main(String[] args) {
System.out.println(666);
System.out.println(-999);
System.out.println(-1.2);
System.out.println('A');
System.out.println(true);
System.out.println(false);
}
}
Escape Characters
The tab character (\t) aligns output:
public class TabDemo {
public static void main(String[] args) {
System.out.println("Name" + '\t' + "Age");
System.out.println("John" + '\t' + "25");
}
}
Output:
Name Age
John 25
Variables
A variable is a container that stores a single data value. Variables must be declared with a specific type.
Variable Declaration
public class VariableDemo {
public static void main(String[] args) {
int age = 25;
double salary = 5000.50;
String name = "Alice";
System.out.println(age);
System.out.println(salary);
}
}
Variable Usage
public class VariableUsage {
public static void main(String[] args) {
int count = 0;
// Using variable in calculations
count = count + 1;
System.out.println(count);
// Modifying variable value
count = 70;
System.out.println(count);
// Declaring multiple variables
int x = 100, y = 200, z = 300;
System.out.println(x);
System.out.println(y);
boolean isActive = true;
System.out.println(isActive);
}
}
Variable Rules
- A variable holds only one value at a time
- Variable names cannot be duplicated within the same scope
- Multiple variables can be declared in a single statement
- Variables must be initialized before use
- Variables are only accessible within their defined scope
Practical Example: Bus Passenger Count
public class BusPassengers {
public static void main(String[] args) {
int passengerCount = 0;
// First stop: 1 passenger boards
passengerCount = passengerCount + 1;
// Second stop: 2 board, 1 alights
passengerCount = passengerCount + 2 - 1;
// Third stop: 2 board, 1 alights
passengerCount = passengerCount + 2 - 1;
// Fourth stop: 1 passenger alights
passengerCount = passengerCount - 1;
// Fifth stop: 1 passenger boards
passengerCount = passengerCount + 1;
System.out.println("Passengers at final stop: " + passengerCount);
}
}
Data Types
Primitive Data Types
public class DataTypesDemo {
public static void main(String[] args) {
// Integer types
byte smallNumber = 10;
short shortNumber = 20;
int regularNumber = 30;
long largeNumber = 9999999999L; // Note: 'L' suffix required
// Floating-point types
float floatNumber = 10.1F; // Note: 'F' suffix required
double doubleNumber = 20.2;
// Character type
char grade = 'A';
// Boolean type
boolean isValid = true;
System.out.println(largeNumber);
System.out.println(floatNumber);
System.out.println(grade);
System.out.println(isValid);
}
}
Size Order: double > float > long > int > short > byte
Reference Data Types
Reference types include classes, interfaces, arrays, enums, annotations, and the String type.
Composite Variable Example
public class PersonInfo {
public static void main(String[] args) {
String studentName = "Michael Chen";
int studentAge = 18;
char gender = 'M';
double height = 180.5;
boolean hasScholarship = true;
System.out.println("Name: " + '\t' + studentName);
System.out.println("Age: " + '\t' + studentAge);
System.out.println("Gender: " + '\t' + gender);
System.out.println("Height: " + '\t' + height);
System.out.println("Scholarship: " + '\t' + hasScholarship);
}
}
Identifiers
Rules (Required)
- Can contain letters, digits, underscores (_), and dollar signs ($)
- Cannot start with a digit
- Cannot be Java keywords
- Are case-sensitive
Naming Conventions
Camel Case (Variables and Methods):
- Single word: lowercase (e.g.,
name) - Multiple words: first word lowercase, subsequent words capitalized (e.g.,
firstName)
Pascal Case (Classes):
- Single word: first letter capitalized (e.g.,
Student) - Multiple words: each word capitalized (e.g.,
GoodStudent)
Keyboard Input
Java provides the Scanner class for reading user input:
import java.util.Scanner;
public class KeyboardInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter an integer:");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
}
}
Multiple Values:
import java.util.Scanner;
public class MultipleInputs {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number:");
int num1 = scanner.nextInt();
System.out.println("Enter second number:");
int num2 = scanner.nextInt();
System.out.println("Sum: " + (num1 + num2));
}
}
Operators
Arithmetic Operators
public class ArithmeticOps {
public static void main(String[] args) {
System.out.println(3 + 2); // Addition: 5
System.out.println(5 - 1); // Subtraction: 4
System.out.println(7 * 9); // Multiplication: 63
System.out.println(10 / 3); // Division: 3
System.out.println(10.0 / 3); // Division: 3.333...
System.out.println(10 % 3); // Modulo: 1
}
}
Extracting Digits
import java.util.Scanner;
public class DigitExtraction {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a three-digit number:");
int number = scanner.nextInt();
System.out.println("Units: " + '\t' + (number % 10));
System.out.println("Tens: " + '\t' + ((number / 10) % 10));
System.out.println("Hundreds: " + '\t' + (number / 100));
}
}
Type Casting
public class TypeCasting {
public static void main(String[] args) {
byte b1 = 19;
byte b2 = 20;
byte result = (byte)(b1 + b2);
System.out.println(result);
}
}
Increment/Decrement Operators
public class IncrementDemo {
public static void main(String[] args) {
int x = 10;
int y = x++; // y gets original value: 10, x becomes 11
int z = ++x; // x becomes 12, z gets 12
System.out.println(x); // 12
System.out.println(y); // 10
System.out.println(z); // 12
}
}
Assignment Operators
=, +=, -=, *=, /=, %=
Relational Operators
==, !=, >, <, >=, <=
Logical Operators
&& (AND), || (OR), ! (NOT)
Ternary Operator
condition ? valueIfTrue : valueIfFalse
Operator Precedence
Java uses two's complement representation for integers. A byte ranges from +127 to -128.
Control Flow
Sequential Structure
Statements execute in order from top to bottom:
public class SequentialDemo {
public static void main(String[] args) {
System.out.println("Step 1: Initialize application");
System.out.println("Step 2: Load configuration");
System.out.println("Step 3: Connect to database");
System.out.println("Step 4: Start server");
}
}
If Statement
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your score:");
int score = scanner.nextInt();
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Cinema Seat Assignment:
import java.util.Scanner;
public class SeatAssignment {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter ticket number (1-100):");
int ticket = scanner.nextInt();
if (ticket >= 0 && ticket <= 100) {
if (ticket % 2 == 1) {
System.out.println("Sit on the left side");
} else {
System.out.println("Sit on the right side");
}
}
}
}
Switch Statement
import java.util.Scanner;
public class SwitchDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 1-5:");
int num = scanner.nextInt();
switch (num) {
case 1 -> System.out.println("Greater than 0, less than 2");
case 2 -> System.out.println("Greater than 1, less than 3");
case 3 -> System.out.println("Greater than 2, less than 4");
case 4 -> System.out.println("Greater than 3, less than 5");
case 5 -> System.out.println("Greater than 4, less than 6");
default -> System.out.println("Invalid input");
}
}
}
Traditional Switch Syntax:
import java.util.Scanner;
public class WeekdayDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter day number (1-7):");
int day = scanner.nextInt();
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Invalid day");
}
}
}
For Loop
public class ForLoopDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
While Loop
public class WhileLoopDemo {
public static void main(String[] args) {
int counter = 1;
while (counter <= 5) {
System.out.println(counter);
counter++;
}
}
}
Do-While Loop
Executes at least once before checking the condition.
Infinite Loop
// for(;;) { }
// while(true) { }
Break and Continue
public class BreakContinue {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips iteration when i equals 3
}
System.out.println(i);
}
}
}
Arrays
Arrays are containers that store multiple values of the same data type.
Array Declaration and Initialization
Static Initialization:
public class ArrayInit {
public static void main(String[] args) {
// Full format
int[] ages = new int[]{11, 12, 13, 14};
// Shortcut format
int[] scores = {11, 12, 13, 14};
// String array
String[] names = new String[]{"Alice", "Bob", "Charlie"};
String[] cities = {"Beijing", "Shanghai", "Guangzhou"};
// Double array
double[] heights = {1.85, 1.72, 1.68, 1.78};
}
}
Array Address:
public class ArrayAddress {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
System.out.println(numbers);
// Output: [I@7ef20235
// [ = array, I = int, @ = separator, address in hex
}
}
Accessing Elements
public class ArrayAccess {
public static void main(String[] args) {
int[] data = {10, 20, 30, 40};
// Get element at index 2
System.out.println(data[2]); // 30
// Modify element at index 2
data[2] = 100;
System.out.println(data[2]); // 100
}
}
Array Traversal
public class ArrayTraversal {
public static void main(String[] args) {
int[] values = {11, 12, 13, 14};
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
}
Dynamic Array Initialization
public class DynamicArray {
public static void main(String[] args) {
String[] students = new String[50];
students[0] = "Alice";
students[1] = "Bob";
System.out.println(students[0]);
System.out.println(students[1]);
System.out.println(students[2]); // null (default value)
}
}
Default Values:
- Integer types: 0
- Floating-point types: 0.0
- Character: '\u0000' (space)
- Boolean: falce
- Reference types: null
Array Memory
Java memory consists of:
- Stack: Method execution memory
- Heap: Objects and arrays (new created)
- Method Area: Class files
- Native Method Stack: JVM native operations
- Registers: CPU operations
Common Array Operations
Finding Maximum and Minimum:
public class MinMaxFinder {
public static void main(String[] args) {
int[] numbers = {33, 5, 22, 44, 55};
int minimum = numbers[0];
int maximum = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > maximum) {
maximum = numbers[i];
}
if (numbers[i] < minimum) {
minimum = numbers[i];
}
}
System.out.println("Maximum: " + maximum);
System.out.println("Minimum: " + minimum);
}
}
Array Sum:
public class ArraySum {
public static void main(String[] args) {
int[] numbers = {33, 5, 22, 44, 55};
int total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
System.out.println("Sum: " + total);
}
}
Random Number Array:
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[] values = new int[10];
Random random = new Random();
for (int i = 0; i < values.length; i++) {
values[i] = random.nextInt(100) + 1;
}
int sum = 0;
for (int i = 0; i < values.length; i++) {
sum += values[i];
}
System.out.println("Sum: " + sum);
}
}
Swapping Elements:
public class ElementSwap {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Swap first and last elements
int temp = numbers[0];
numbers[0] = numbers[4];
numbers[4] = temp;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Shuffling Array:
import java.util.Random;
public class ArrayShuffle {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
int randomIndex = random.nextInt(numbers.length);
int temp = numbers[i];
numbers[i] = numbers[randomIndex];
numbers[randomIndex] = temp;
}
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Methods
Methods are reusable code blocks that perform specific tasks.
Method Structure
public static returnType methodName(parameters) {
methodBody;
return value;
}
Method Examples
Void Method (No Return):
public class GameMethod {
public static void main(String[] args) {
startGame();
}
public static void startGame() {
System.out.println("Select character");
System.out.println("Start match");
System.out.println("Battle");
System.out.println("Defeat");
System.out.println("Blame teammates");
System.out.println("Surrender");
System.out.println("Game over");
}
}
Parameterized Method:
public class Calculator {
public static void main(String[] args) {
calculateSum(10, 20);
calculateSum(30, 40);
}
public static void calculateSum(int a, int b) {
System.out.println(a + b);
}
}
Method with Return Value:
public class RectangleArea {
public static void main(String[] args) {
double area = computeArea(5.0, 3.0);
System.out.println("Area: " + area);
}
public static double computeArea(double length, double width) {
return length * width;
}
}
Method Overloading
Multiple methods with the same name but different parameters:
public class ArrayCopy {
public static void main(String[] args) {
int[] source = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] result = copyRange(source, 0, 5);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
public static int[] copyRange(int[] array, int from, int to) {
int[] newArray = new int[to - from];
for (int i = 0; i < newArray.length; i++) {
newArray[i] = array[i + from];
}
return newArray;
}
}
Method Memory
Primitive Type Parameters:
public class PrimitivePass {
public static void main(String[] args) {
int value = 100;
System.out.println("Before method call: " + value);
modifyValue(value);
System.out.println("After method call: " + value);
}
public static void modifyValue(int value) {
value = 200;
}
}
// Output:
// Before method call: 100
// After method call: 100
Reference Type Parameters:
public class ReferencePass {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println("Before method call: " + numbers[1]);
modifyArray(numbers);
System.out.println("After method call: " + numbers[1]);
}
public static void modifyArray(int[] numbers) {
numbers[1] = 200;
}
}
// Output:
// Before method call: 2
// After method call: 200
Practical Applications
Flight Ticket Pricing
import java.util.Scanner;
public class TicketPrice {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter ticket price:");
int price = scanner.nextInt();
System.out.println("Enter month (1-12):");
int month = scanner.nextInt();
System.out.println("Enter class (0=First, 1=Economy):");
int seatType = scanner.nextInt();
if (month >= 5 && month <= 10) {
// Peak season (May-October)
if (seatType == 0) {
price = (int)(price * 0.9);
} else {
price = (int)(price * 0.85);
}
} else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)) {
// Off-season
if (seatType == 0) {
price = (int)(price * 0.7);
} else {
price = (int)(price * 0.65);
}
}
System.out.println("Final price: " + price);
}
}
Prime Number Finder
public class PrimeFinder {
public static void main(String[] args) {
int primeCount = 0;
for (int i = 101; i <= 200; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i + " is prime");
primeCount++;
}
}
System.out.println("Total primes: " + primeCount);
}
}
Random Verification Code
import java.util.Random;
public class VerificationCode {
public static void main(String[] args) {
char[] code = new char[5];
Random random = new Random();
// First 4 characters: uppercase or lowercase letters
for (int i = 0; i <= 3; i++) {
code[i] = (char)(random.nextBoolean()
? random.nextInt(26) + 65
: random.nextInt(26) + 97);
}
// Last character: digit
code[4] = (char)(random.nextInt(10) + 48);
for (int i = 0; i < code.length; i++) {
System.out.print(code[i]);
}
}
}
Array Copy
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
for (int i = 0; i < copy.length; i++) {
System.out.print(copy[i]);
}
}
}
Judge Scoring System
import java.util.Scanner;
public class JudgeScoring {
public static void main(String[] args) {
int[] scores = new int[6];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter score from judge " + (i + 1) + ": ");
scores[i] = scanner.nextInt();
}
int max = scores[0];
int min = scores[0];
int total = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) max = scores[i];
if (scores[i] < min) min = scores[i];
total += scores[i];
}
double average = (total - max - min) / 4.0;
System.out.println("Final score: " + average);
}
}
Number Encryption
import java.util.Scanner;
public class NumberEncrypt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of digits: ");
int count = scanner.nextInt();
int[] numbers = new int[count];
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter digit " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
printArray(numbers);
// Encrypt: add 5, then take mod 10
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (numbers[i] + 5) % 10;
}
// Reverse array
for (int i = 0, j = numbers.length - 1; i < j; i++, j--) {
int temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
printArray(numbers);
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i == arr.length - 1 ? arr[i] : arr[i] + ", ");
}
System.out.println("]");
}
}
Prize Draw
import java.util.Random;
public class PrizeDraw {
public static void main(String[] args) {
int[] prizes = {2, 588, 888, 1000, 10000};
Random random = new Random();
int[] drawn = new int[prizes.length];
int remaining = prizes.length;
while (remaining > 0) {
int index = random.nextInt(prizes.length);
boolean alreadyDrawn = false;
for (int j = 0; j < drawn.length - remaining; j++) {
if (drawn[j] == prizes[index]) {
alreadyDrawn = true;
break;
}
}
if (!alreadyDrawn) {
System.out.println(prizes[index] + " drawn");
drawn[drawn.length - remaining] = prizes[index];
remaining--;
}
}
}
}
Lottery System
import java.util.Random;
import java.util.Scanner;
public class LotterySystem {
public static void main(String[] args) {
int[] winningNumbers = generateWinningNumbers();
int[] userNumbers = getUserNumbers();
checkResults(winningNumbers, userNumbers);
}
public static int[] generateWinningNumbers() {
int[] numbers = new int[7];
Random random = new Random();
for (int i = 0; i < numbers.length - 1; i++) {
while (true) {
int num = random.nextInt(33) + 1;
boolean duplicate = false;
for (int j = 0; j < i; j++) {
if (numbers[j] == num) {
duplicate = true;
break;
}
}
if (!duplicate) {
numbers[i] = num;
break;
}
}
}
numbers[numbers.length - 1] = random.nextInt(16) + 1;
return numbers;
}
public static int[] getUserNumbers() {
int[] numbers = new int[7];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < numbers.length - 1; i++) {
System.out.print("Enter red ball " + (i + 1) + " (1-33): ");
numbers[i] = scanner.nextInt();
}
System.out.print("Enter blue ball (1-16): ");
numbers[numbers.length - 1] = scanner.nextInt();
return numbers;
}
public static void checkResults(int[] winning, int[] user) {
int redMatches = 0;
int blueMatch = 0;
for (int i = 0; i < user.length - 1; i++) {
for (int j = 0; j < winning.length - 1; j++) {
if (user[i] == winning[j]) {
redMatches++;
break;
}
}
}
blueMatch = user[user.length - 1] == winning[winning.length - 1] ? 1 : 0;
System.out.println("Your numbers:");
printArray(user);
System.out.println("Winning numbers:");
printArray(winning);
System.out.println("Red balls matched: " + redMatches);
System.out.println("Blue ball " + (blueMatch == 1 ? "matched" : "not matched"));
// Prize calculation logic
if (blueMatch == 1 && redMatches == 6) {
System.out.println("Jackpot! 10 million!");
} else if (redMatches == 6) {
System.out.println("First prize! 5 million!");
} else if (blueMatch == 1 && redMatches == 5) {
System.out.println("Second prize! 3000!");
} else if (blueMatch == 1 && redMatches == 4 || blueMatch == 0 && redMatches == 5) {
System.out.println("Third prize! 200!");
} else if (blueMatch == 1 && redMatches == 3 || blueMatch == 0 && redMatches == 4) {
System.out.println("Fourth prize! 10!");
} else if (blueMatch == 1 && redMatches < 3) {
System.out.println("Fifth prize! 5!");
} else {
System.out.println("No prize this time");
}
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i == arr.length - 1 ? arr[i] : arr[i] + ", ");
}
System.out.println("]");
}
}
Two-Dimensional Arrays
Two-dimensional arrays store arrays as elements, useful for organizing data in rows and columns.
Declaration and Initialization
public class TwoDArray {
public static void main(String[] args) {
// Static initialization - can have varying row lengths
int[][] matrix1 = new int[][]{{1, 2, 3}, {4, 5, 6, 7, 8, 9}};
int[][] matrix2 = {{1, 2, 3}, {4, 5, 6, 7, 8, 9}};
// Recommended format
int[][] grid = {
{1, 2, 3},
{4, 5, 6, 7, 8, 9}
};
// Accessing elements
System.out.println(grid[0]); // Address of first row
System.out.println(grid[0][0]); // 1
}
}
Traversal
public class TwoDTraversal {
public static void main(String[] args) {
int[][] data = {
{1, 2, 3},
{4, 5, 6, 7, 8, 9}
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.println(data[i][j]);
}
}
}
}
Dynamic Initialization
public class TwoDDynamic {
public static void main(String[] args) {
int[][] table = new int[3][5];
table[0][1] = 10;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
Quarterly Sales Calculation
public class QuarterlySales {
public static void main(String[] args) {
int[][] quarterlyData = {
{22, 66, 44},
{77, 33, 88},
{25, 45, 65},
{11, 66, 99}
};
int annualTotal = 0;
for (int i = 0; i < quarterlyData.length; i++) {
int quarterlySum = 0;
for (int j = 0; j < quarterlyData[i].length; j++) {
quarterlySum += quarterlyData[i][j];
}
System.out.println("Quarter " + (i + 1) + ": " + quarterlySum);
annualTotal += quarterlySum;
}
System.out.println("Annual Total: " + annualTotal);
}
}
Conclusion
This guide covered Java fundamentals including variables, data types, operators, control structures, arrays, and methods. The practical examples demonstrate real-world applications of these concepts. Mastery of these fundamentals provides a solid foundation for building more complex Java applications.