Skip to main content

Java Beginner's Guide

Table of Contents

  1. Introduction to Java
  2. Setting Up Java Environment
  3. Basic Program Structure
  4. Data Types
  5. Variables and Constants
  6. Operators
  7. Input and Output
  8. Scanner Class
  9. Random Class
  10. Number Formatting
  11. Strings
  12. Control Structures
  13. Arrays
  14. Methods
  15. Practice Exercises

Introduction to Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). Unlike JavaScript, Java is:

  • Compiled language (JavaScript is interpreted)
  • Statically typed (JavaScript is dynamically typed)
  • Platform independent ("Write once, run anywhere")
  • Strongly typed (more strict about data types)

Key Features

  • Object-Oriented Programming (OOP)
  • Platform Independence
  • Memory Management (Garbage Collection)
  • Multi-threading support
  • Rich Standard Library

Setting Up Java Environment

Required Components

  1. JDK (Java Development Kit) - Contains compiler and development tools
  2. IDE - IntelliJ IDEA, Eclipse, or VS Code with Java extensions
  3. Text Editor - Any text editor works for simple programs

First Program Structure

// Every Java program needs a class
public class HelloWorld {
// Main method - entry point of program
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Comparison with JavaScript:

// JavaScript - much simpler
console.log("Hello, World!");

Basic Program Structure

Essential Components

// 1. Package declaration (optional)
package com.example;

// 2. Import statements
import java.util.Scanner;
import java.util.Random;

// 3. Class declaration
public class MyProgram {

// 4. Main method (required for executable programs)
public static void main(String[] args) {
// Program code goes here
System.out.println("Program starts here");
}
}

Key Rules

  • Class name must match filename
  • Case sensitive (MyClass ≠ myclass)
  • Semicolon required after each statement
  • Curly braces define code blocks

Data Types

Java has two categories of data types:

1. Primitive Data Types

TypeSizeRangeDefaultJavaScript Equivalent
byte8 bits-128 to 1270Number
short16 bits-32,768 to 32,7670Number
int32 bits-2³¹ to 2³¹-10Number
long64 bits-2⁶³ to 2⁶³-10LBigInt
float32 bits±3.4E380.0fNumber
double64 bits±1.7E3080.0Number
char16 bits0 to 65,535'\u0000'String (single char)
boolean1 bittrue/falsefalseBoolean

Examples:

public class DataTypesDemo {
public static void main(String[] args) {
// Integer types
byte age = 25;
short year = 2024;
int population = 1000000;
long distance = 384400000L; // Note the 'L' suffix

// Floating-point types
float price = 19.99f; // Note the 'f' suffix
double pi = 3.14159265359;

// Character and boolean
char grade = 'A';
boolean isActive = true;

// Printing values
System.out.println("Age: " + age);
System.out.println("Price: $" + price);
System.out.println("Is Active: " + isActive);
}
}

2. Non-Primitive (Reference) Data Types

// Strings
String name = "John Doe";
String message = new String("Hello World");

// Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};

// Objects
Scanner input = new Scanner(System.in);
Random random = new Random();

Variables and Constants

Variable Declaration

// Syntax: dataType variableName = value;
int age = 25;
double salary = 50000.50;
String name = "Alice";

// Multiple variables of same type
int x = 10, y = 20, z = 30;

// Declaration without initialization
int count;
count = 100; // Initialize later

Constants (Final Variables)

// Use 'final' keyword for constants
final double PI = 3.14159;
final int MAX_USERS = 1000;
final String COMPANY_NAME = "TechCorp";

// Constants are typically in UPPER_CASE

Variable Naming Rules

  • Start with letter, underscore, or dollar sign
  • Can contain letters, digits, underscores, dollar signs
  • Cannot be Java keywords
  • Case sensitive
  • Use camelCase convention
// Valid variable names
int studentAge;
double bankBalance;
String firstName;
boolean isLoggedIn;

// Invalid variable names
// int 2ndPlace; // Starts with digit
// String class; // Java keyword
// double my-salary; // Contains hyphen

Operators

1. Arithmetic Operators

public class ArithmeticDemo {
public static void main(String[] args) {
int a = 10, b = 3;

System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3 (integer division)
System.out.println("Modulus: " + (a % b)); // 1

// For decimal division
double result = (double) a / b;
System.out.println("Decimal Division: " + result); // 3.333...
}
}

2. Assignment Operators

int x = 10;

x += 5; // x = x + 5; (x becomes 15)
x -= 3; // x = x - 3; (x becomes 12)
x *= 2; // x = x * 2; (x becomes 24)
x /= 4; // x = x / 4; (x becomes 6)
x %= 4; // x = x % 4; (x becomes 2)

3. Comparison Operators

int a = 10, b = 20;

System.out.println(a == b); // false (equal to)
System.out.println(a != b); // true (not equal to)
System.out.println(a < b); // true (less than)
System.out.println(a > b); // false (greater than)
System.out.println(a <= b); // true (less than or equal)
System.out.println(a >= b); // false (greater than or equal)

4. Logical Operators

boolean x = true, y = false;

System.out.println(x && y); // false (AND)
System.out.println(x || y); // true (OR)
System.out.println(!x); // false (NOT)

// Short-circuit evaluation
int a = 10, b = 0;
if (b != 0 && a / b > 0) { // Second condition won't execute if b == 0
System.out.println("Safe division");
}

5. Increment/Decrement Operators

int count = 5;

// Pre-increment/decrement
System.out.println(++count); // 6 (increment first, then use)
System.out.println(--count); // 5 (decrement first, then use)

// Post-increment/decrement
System.out.println(count++); // 5 (use first, then increment)
System.out.println(count--); // 6 (use first, then decrement)

Input and Output

Output with System.out

public class OutputDemo {
public static void main(String[] args) {
String name = "Alice";
int age = 25;
double salary = 50000.50;

// Different ways to print
System.out.println("Simple message");
System.out.println("Name: " + name);
System.out.print("Age: "); // Doesn't add new line
System.out.println(age);

// Formatted output
System.out.printf("Name: %s, Age: %d, Salary: $%.2f%n", name, age, salary);

// Format specifiers:
// %s - String
// %d - Integer
// %f - Float/Double
// %.2f - Float with 2 decimal places
// %n - New line (platform independent)
}
}

Scanner Class

The Scanner class is used for reading input from various sources (keyboard, files, etc.).

Basic Usage

import java.util.Scanner;

public class ScannerDemo {
public static void main(String[] args) {
// Create Scanner object for keyboard input
Scanner scanner = new Scanner(System.in);

// Reading different data types
System.out.print("Enter your name: ");
String name = scanner.nextLine();

System.out.print("Enter your age: ");
int age = scanner.nextInt();

System.out.print("Enter your salary: ");
double salary = scanner.nextDouble();

System.out.print("Are you employed? (true/false): ");
boolean employed = scanner.nextBoolean();

// Display results
System.out.println("\n--- Your Information ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Employed: " + employed);

// Always close the scanner
scanner.close();
}
}

Scanner Methods

Scanner input = new Scanner(System.in);

// Reading different types
String line = input.nextLine(); // Reads entire line
String word = input.next(); // Reads single word
int number = input.nextInt(); // Reads integer
double decimal = input.nextDouble(); // Reads double
boolean flag = input.nextBoolean(); // Reads boolean
char character = input.next().charAt(0); // Reads single character

// Checking if input is available
if (input.hasNextInt()) {
int num = input.nextInt();
}

if (input.hasNextLine()) {
String line = input.nextLine();
}

Common Scanner Issues and Solutions

Scanner input = new Scanner(System.in);

System.out.print("Enter age: ");
int age = input.nextInt();

// Problem: nextInt() leaves newline character
System.out.print("Enter name: ");
String name = input.nextLine(); // This will be empty!

// Solution: Use nextLine() after nextInt()
input.nextLine(); // Consume the leftover newline
System.out.print("Enter name: ");
String name = input.nextLine(); // Now this works correctly

Random Class

The Random class is used to generate random numbers.

Basic Usage

import java.util.Random;

public class RandomDemo {
public static void main(String[] args) {
// Create Random object
Random random = new Random();

// Generate different types of random numbers
int randomInt = random.nextInt(); // Any integer
int diceRoll = random.nextInt(6) + 1; // 1 to 6
int range = random.nextInt(100); // 0 to 99

double randomDouble = random.nextDouble(); // 0.0 to 1.0
boolean randomBoolean = random.nextBoolean();

// Generate random numbers in specific ranges
int min = 10, max = 50;
int randomInRange = random.nextInt(max - min + 1) + min; // 10 to 50

System.out.println("Random integer: " + randomInt);
System.out.println("Dice roll: " + diceRoll);
System.out.println("Random 0-99: " + range);
System.out.println("Random double: " + randomDouble);
System.out.println("Random boolean: " + randomBoolean);
System.out.println("Random 10-50: " + randomInRange);
}
}

Practical Examples

import java.util.Random;

public class RandomExamples {
public static void main(String[] args) {
Random rand = new Random();

// Random password generator
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder password = new StringBuilder();
for (int i = 0; i < 8; i++) {
int index = rand.nextInt(chars.length());
password.append(chars.charAt(index));
}
System.out.println("Random password: " + password);

// Coin flip simulation
System.out.print("Coin flip: ");
if (rand.nextBoolean()) {
System.out.println("Heads");
} else {
System.out.println("Tails");
}

// Random color selection
String[] colors = {"Red", "Blue", "Green", "Yellow", "Purple"};
String randomColor = colors[rand.nextInt(colors.length)];
System.out.println("Random color: " + randomColor);
}
}

Number Formatting

Java provides several ways to format numbers for better presentation.

Using DecimalFormat

import java.text.DecimalFormat;

public class NumberFormatting {
public static void main(String[] args) {
double number = 1234567.89123;

// Create DecimalFormat objects with patterns
DecimalFormat df1 = new DecimalFormat("#,###.##");
DecimalFormat df2 = new DecimalFormat("$#,###.00");
DecimalFormat df3 = new DecimalFormat("0.0000");
DecimalFormat df4 = new DecimalFormat("#.##%");

System.out.println("Original: " + number);
System.out.println("Formatted 1: " + df1.format(number));
System.out.println("Currency: " + df2.format(number));
System.out.println("Fixed decimals: " + df3.format(number));
System.out.println("Percentage: " + df4.format(0.75));

// Common patterns:
// # - Optional digit
// 0 - Required digit
// , - Thousands separator
// . - Decimal point
// % - Percentage
}
}

Using printf for Formatting

public class PrintfFormatting {
public static void main(String[] args) {
double price = 19.99;
int quantity = 5;
String item = "Books";

// Various formatting options
System.out.printf("Item: %-10s Qty: %3d Price: $%6.2f%n", item, quantity, price);
System.out.printf("Total: $%.2f%n", price * quantity);

// Number formatting
double pi = Math.PI;
System.out.printf("Pi: %.2f%n", pi); // 2 decimal places
System.out.printf("Pi: %.4f%n", pi); // 4 decimal places
System.out.printf("Pi: %10.2f%n", pi); // Width 10, 2 decimals
System.out.printf("Pi: %010.2f%n", pi); // Pad with zeros

// Integer formatting
int num = 42;
System.out.printf("Number: %d%n", num); // Standard integer
System.out.printf("Number: %5d%n", num); // Width 5, right-aligned
System.out.printf("Number: %-5d%n", num); // Width 5, left-aligned
System.out.printf("Number: %05d%n", num); // Width 5, zero-padded
}
}

Currency and Percentage Formatting

import java.text.NumberFormat;
import java.util.Locale;

public class CurrencyFormatting {
public static void main(String[] args) {
double amount = 1234567.89;
double percentage = 0.75;

// Currency formatting
NumberFormat currencyUS = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat currencyUK = NumberFormat.getCurrencyInstance(Locale.UK);

System.out.println("US Currency: " + currencyUS.format(amount));
System.out.println("UK Currency: " + currencyUK.format(amount));

// Percentage formatting
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Percentage: " + percent.format(percentage));

// Number formatting with grouping
NumberFormat number = NumberFormat.getNumberInstance();
System.out.println("Number: " + number.format(amount));
}
}

Strings

Strings are objects in Java, not primitive types (unlike JavaScript where they can be both).

String Creation and Basic Operations

public class StringDemo {
public static void main(String[] args) {
// String creation
String str1 = "Hello World"; // String literal
String str2 = new String("Hello World"); // Using constructor

// String properties
System.out.println("Length: " + str1.length());
System.out.println("Empty? " + str1.isEmpty());
System.out.println("Character at index 0: " + str1.charAt(0));

// String comparison (IMPORTANT: Don't use == for strings!)
String name1 = "Alice";
String name2 = "Alice";
String name3 = new String("Alice");

System.out.println(name1.equals(name2)); // true
System.out.println(name1.equals(name3)); // true
System.out.println(name1 == name2); // true (string pool)
System.out.println(name1 == name3); // false (different objects)
System.out.println(name1.equalsIgnoreCase("ALICE")); // true

// String searching
String text = "Java Programming";
System.out.println("Contains 'Java': " + text.contains("Java"));
System.out.println("Starts with 'Java': " + text.startsWith("Java"));
System.out.println("Ends with 'ing': " + text.endsWith("ing"));
System.out.println("Index of 'Pro': " + text.indexOf("Pro"));
}
}

String Manipulation

public class StringManipulation {
public static void main(String[] args) {
String original = " Hello World ";

// Case conversion
System.out.println("Upper: " + original.toUpperCase());
System.out.println("Lower: " + original.toLowerCase());

// Trimming whitespace
System.out.println("Trimmed: '" + original.trim() + "'");

// Substring operations
String text = "Java Programming";
System.out.println("Substring(0,4): " + text.substring(0, 4)); // "Java"
System.out.println("Substring(5): " + text.substring(5)); // "Programming"

// String replacement
System.out.println("Replace 'a' with '@': " + text.replace('a', '@'));
System.out.println("Replace 'Java': " + text.replace("Java", "Python"));

// String splitting
String csv = "apple,banana,orange,grape";
String[] fruits = csv.split(",");
System.out.println("Fruits count: " + fruits.length);
for (String fruit : fruits) {
System.out.println("- " + fruit);
}
}
}

StringBuilder for Efficient String Building

public class StringBuilderDemo {
public static void main(String[] args) {
// StringBuilder is mutable and efficient for multiple concatenations
StringBuilder sb = new StringBuilder();

sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.append("!");

System.out.println("StringBuilder result: " + sb.toString());

// Inserting and deleting
sb.insert(5, " Beautiful");
System.out.println("After insert: " + sb.toString());

sb.delete(5, 15); // Remove " Beautiful"
System.out.println("After delete: " + sb.toString());

// Reversing
sb.reverse();
System.out.println("Reversed: " + sb.toString());

// Performance comparison (for large operations)
long startTime = System.currentTimeMillis();

// Using String concatenation (inefficient)
String result = "";
for (int i = 0; i < 10000; i++) {
result += "a";
}

long endTime = System.currentTimeMillis();
System.out.println("String concatenation time: " + (endTime - startTime) + "ms");

startTime = System.currentTimeMillis();

// Using StringBuilder (efficient)
StringBuilder efficientSb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
efficientSb.append("a");
}
String efficientResult = efficientSb.toString();

endTime = System.currentTimeMillis();
System.out.println("StringBuilder time: " + (endTime - startTime) + "ms");
}
}

Control Structures

If-Else Statements

public class IfElseDemo {
public static void main(String[] args) {
int score = 85;

// Simple if-else
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}

// Ternary operator (shorthand if-else)
String result = (score >= 60) ? "Pass" : "Fail";
System.out.println("Result: " + result);

// Nested conditions
int age = 20;
boolean hasLicense = true;

if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
} else {
System.out.println("Need license to drive");
}
} else {
System.out.println("Too young to drive");
}

// Logical operators in conditions
if (age >= 18 && hasLicense) {
System.out.println("Eligible to drive");
}
}
}

Switch Statements

public class SwitchDemo {
public static void main(String[] args) {
int dayNumber = 3;
String dayName;

// Traditional switch
switch (dayNumber) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println("Day: " + dayName);

// Switch with multiple cases
char grade = 'B';
switch (grade) {
case 'A':
case 'a':
System.out.println("Excellent!");
break;
case 'B':
case 'b':
System.out.println("Good job!");
break;
case 'C':
case 'c':
System.out.println("Average");
break;
default:
System.out.println("Keep trying!");
}

// Modern switch expression (Java 14+)
String season = switch (dayNumber) {
case 1, 2, 12 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Fall";
default -> "Invalid month";
};
}
}

Loops

public class LoopsDemo {
public static void main(String[] args) {

// 1. For Loop
System.out.println("=== For Loop ===");
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}

// For loop with different increments
for (int i = 0; i < 10; i += 2) {
System.out.print(i + " "); // 0 2 4 6 8
}
System.out.println();

// Countdown
for (int i = 5; i >= 1; i--) {
System.out.println("Countdown: " + i);
}

// 2. While Loop
System.out.println("\n=== While Loop ===");
int count = 1;
while (count <= 3) {
System.out.println("While count: " + count);
count++;
}

// 3. Do-While Loop (executes at least once)
System.out.println("\n=== Do-While Loop ===");
int num = 6;
do {
System.out.println("Do-while num: " + num);
num++;
} while (num <= 5); // This will execute once even though condition is false

// 4. Enhanced For Loop (for arrays and collections)
System.out.println("\n=== Enhanced For Loop ===");
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println("Number: " + number);
}

// 5. Nested Loops
System.out.println("\n=== Nested Loops (Multiplication Table) ===");
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print((i * j) + "\t");
}
System.out.println(); // New line after each row
}

// 6. Loop Control Statements
System.out.println("\n=== Loop Control ===");
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue; // Skip iteration when i = 3
}
if (i == 8) {
break; // Exit loop when i = 8
}
System.out.print(i + " ");
}
System.out.println();
}
}

Arrays

Arrays store multiple values of the same type in a single variable.

Array Declaration and Initialization

public class ArraysDemo {
public static void main(String[] args) {
// Array declaration and initialization
int[] numbers = {10, 20, 30, 40, 50}; // Method 1

String[] names = new String[5]; // Method 2 - declare size first
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
names[3] = "Diana";
names[4] = "Eve";

double[] prices = new double[]{19.99, 29.99, 39.99}; // Method 3

// Array properties
System.out.println("Numbers length: " + numbers.length);
System.out.println("First number: " + numbers[0]);
System.out.println("Last number: " + numbers[numbers.length - 1]);

// Accessing array elements
System.out.println("\n=== Numbers Array ===");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}

// Enhanced for loop (for-each)
System.out.println("\n=== Names Array ===");
for (String name : names) {
System.out.println("Name: " + name);
}

// Array operations
System.out.println("\n=== Array Operations ===");

// Finding maximum value
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum: " + max);

// Calculating sum and average
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}

Multi-dimensional Arrays

public class MultiDimensionalArrays {
public static void main(String[] args) {
// 2D Array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Alternative declaration
int[][] grid = new int[3][3];
grid[0][0] = 1;
grid[1][1] = 5;
grid[2][2] = 9;

// Printing 2D array
System.out.println("=== Matrix ===");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row
}

// Enhanced for loop with 2D arrays
System.out.println("\n=== Grid (Enhanced For) ===");
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}

// Jagged arrays (arrays of different lengths)
int[][] jaggedArray = {
{1, 2},
{3, 4, 5, 6},
{7, 8, 9}
};

System.out.println("\n=== Jagged Array ===");
for (int i = 0; i < jaggedArray.length; i++) {
System.out.print("Row " + i + ": ");
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}

Array Utility Methods

import java.util.Arrays;

public class ArrayUtilities {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9, 3};

System.out.println("Original: " + Arrays.toString(numbers));

// Sorting array
int[] sortedNumbers = numbers.clone(); // Create a copy
Arrays.sort(sortedNumbers);
System.out.println("Sorted: " + Arrays.toString(sortedNumbers));

// Binary search (array must be sorted first)
int index = Arrays.binarySearch(sortedNumbers, 8);
System.out.println("Index of 8: " + index);

// Filling array with same value
int[] filled = new int[5];
Arrays.fill(filled, 42);
System.out.println("Filled: " + Arrays.toString(filled));

// Comparing arrays
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
int[] array3 = {1, 2, 4};

System.out.println("array1 equals array2: " + Arrays.equals(array1, array2)); // true
System.out.println("array1 equals array3: " + Arrays.equals(array1, array3)); // false

// Copying arrays
int[] copy1 = Arrays.copyOf(numbers, numbers.length);
int[] copy2 = Arrays.copyOfRange(numbers, 1, 4); // Copy elements from index 1 to 3

System.out.println("Full copy: " + Arrays.toString(copy1));
System.out.println("Range copy: " + Arrays.toString(copy2));
}
}

Methods

Methods are blocks of code that perform specific tasks and can be reused throughout your program.

Method Declaration and Usage

public class MethodsDemo {

// Method with no parameters and no return value
public static void greet() {
System.out.println("Hello, World!");
}

// Method with parameters and return value
public static int add(int a, int b) {
return a + b;
}

// Method with multiple parameters
public static double calculateArea(double length, double width) {
return length * width;
}

// Method that returns a String
public static String getFullName(String firstName, String lastName) {
return firstName + " " + lastName;
}

// Method with boolean return type
public static boolean isEven(int number) {
return number % 2 == 0;
}

// Method with array parameter
public static int findMax(int[] numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Array cannot be empty");
}

int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}

// Method with variable arguments (varargs)
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

// Method overloading (same name, different parameters)
public static double multiply(double a, double b) {
return a * b;
}

public static int multiply(int a, int b) {
return a * b;
}

public static double multiply(double a, double b, double c) {
return a * b * c;
}

public static void main(String[] args) {
// Calling methods
greet();

int result = add(10, 5);
System.out.println("10 + 5 = " + result);

double area = calculateArea(5.5, 3.2);
System.out.println("Area: " + area);

String fullName = getFullName("John", "Doe");
System.out.println("Full name: " + fullName);

System.out.println("Is 4 even? " + isEven(4));
System.out.println("Is 7 even? " + isEven(7));

int[] numbers = {10, 5, 20, 15, 30};
int max = findMax(numbers);
System.out.println("Maximum value: " + max);

// Using varargs method
System.out.println("Sum of 1,2,3: " + sum(1, 2, 3));
System.out.println("Sum of 1,2,3,4,5: " + sum(1, 2, 3, 4, 5));

// Method overloading examples
System.out.println("Int multiply: " + multiply(3, 4));
System.out.println("Double multiply: " + multiply(3.5, 2.5));
System.out.println("Triple multiply: " + multiply(2.0, 3.0, 4.0));
}
}

Utility Methods Example

import java.util.Scanner;

public class UtilityMethods {

// Method to validate if a number is within range
public static boolean isInRange(int number, int min, int max) {
return number >= min && number <= max;
}

// Method to get input with validation
public static int getValidInput(Scanner scanner, String prompt, int min, int max) {
int input;
do {
System.out.print(prompt);
input = scanner.nextInt();
if (!isInRange(input, min, max)) {
System.out.println("Please enter a number between " + min + " and " + max);
}
} while (!isInRange(input, min, max));
return input;
}

// Method to format currency
public static String formatCurrency(double amount) {
return String.format("$%.2f", amount);
}

// Method to calculate grade
public static char calculateGrade(int score) {
if (score >= 90) return 'A';
else if (score >= 80) return 'B';
else if (score >= 70) return 'C';
else if (score >= 60) return 'D';
else return 'F';
}

// Method to reverse a string
public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
return reversed.toString();
}

// Method to count vowels
public static int countVowels(String str) {
int count = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
if (vowels.indexOf(str.charAt(i)) != -1) {
count++;
}
}
return count;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Using utility methods
int age = getValidInput(scanner, "Enter your age (1-120): ", 1, 120);
System.out.println("Your age is: " + age);

double price = 29.99;
System.out.println("Price: " + formatCurrency(price));

int score = 85;
System.out.println("Grade for score " + score + ": " + calculateGrade(score));

String text = "Hello World";
System.out.println("Original: " + text);
System.out.println("Reversed: " + reverseString(text));
System.out.println("Vowel count: " + countVowels(text));

scanner.close();
}
}

Practice Exercises

Here are practical exercises to reinforce your Java learning:

Exercise 1: Basic Calculator

import java.util.Scanner;

public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("=== Simple Calculator ===");
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();

System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);

System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();

double result = 0;
boolean validOperation = true;

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero!");
validOperation = false;
}
break;
default:
System.out.println("Error: Invalid operator!");
validOperation = false;
}

if (validOperation) {
System.out.printf("Result: %.2f %c %.2f = %.2f%n", num1, operator, num2, result);
}

scanner.close();
}
}

Exercise 2: Number Guessing Game

import java.util.Random;
import java.util.Scanner;

public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();

int targetNumber = random.nextInt(100) + 1; // 1 to 100
int attempts = 0;
int maxAttempts = 7;
boolean hasWon = false;

System.out.println("=== Number Guessing Game ===");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("You have " + maxAttempts + " attempts to guess it!");

while (attempts < maxAttempts && !hasWon) {
System.out.print("Attempt " + (attempts + 1) + " - Enter your guess: ");
int guess = scanner.nextInt();
attempts++;

if (guess == targetNumber) {
hasWon = true;
System.out.println("🎉 Congratulations! You guessed it in " + attempts + " attempts!");
} else if (guess < targetNumber) {
System.out.println("Too low! Try a higher number.");
} else {
System.out.println("Too high! Try a lower number.");
}

if (!hasWon && attempts < maxAttempts) {
System.out.println("Attempts remaining: " + (maxAttempts - attempts));
}
}

if (!hasWon) {
System.out.println("Game over! The number was: " + targetNumber);
}

scanner.close();
}
}

Exercise 3: Student Grade Management

import java.util.Scanner;

public class GradeManager {

public static double calculateAverage(double[] scores) {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.length;
}

public static char getLetterGrade(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 displayResults(String studentName, double[] scores, double average, char letterGrade) {
System.out.println("\n=== Grade Report ===");
System.out.println("Student: " + studentName);
System.out.print("Scores: ");
for (int i = 0; i < scores.length; i++) {
System.out.printf("%.1f", scores[i]);
if (i < scores.length - 1) System.out.print(", ");
}
System.out.println();
System.out.printf("Average: %.2f%n", average);
System.out.println("Letter Grade: " + letterGrade);
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter student name: ");
String studentName = scanner.nextLine();

System.out.print("Enter number of subjects: ");
int numSubjects = scanner.nextInt();

double[] scores = new double[numSubjects];

// Input scores
for (int i = 0; i < numSubjects; i++) {
System.out.print("Enter score for subject " + (i + 1) + ": ");
scores[i] = scanner.nextDouble();
}

// Calculate results
double average = calculateAverage(scores);
char letterGrade = getLetterGrade(average);

// Display results
displayResults(studentName, scores, average, letterGrade);

scanner.close();
}
}

Exercise 4: Word Counter and Analyzer

import java.util.Scanner;

public class TextAnalyzer {

public static int countWords(String text) {
if (text == null || text.trim().isEmpty()) {
return 0;
}
return text.trim().split("\\s+").length;
}

public static int countVowels(String text) {
int count = 0;
String vowels = "aeiouAEIOU";
for (char c : text.toCharArray()) {
if (vowels.indexOf(c) != -1) {
count++;
}
}
return count;
}

public static int countConsonants(String text) {
int count = 0;
for (char c : text.toCharArray()) {
if (Character.isLetter(c) && "aeiouAEIOU".indexOf(c) == -1) {
count++;
}
}
return count;
}

public static String reverseWords(String text) {
String[] words = text.split(" ");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]);
if (i > 0) reversed.append(" ");
}
return reversed.toString();
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("=== Text Analyzer ===");
System.out.print("Enter a sentence: ");
String text = scanner.nextLine();

// Perform analysis
int characters = text.length();
int charactersNoSpaces = text.replace(" ", "").length();
int words = countWords(text);
int vowels = countVowels(text);
int consonants = countConsonants(text);
String reversed = reverseWords(text);

// Display results
System.out.println("\n=== Analysis Results ===");
System.out.println("Original text: " + text);
System.out.println("Total characters: " + characters);
System.out.println("Characters (no spaces): " + charactersNoSpaces);
System.out.println("Word count: " + words);
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Reversed words: " + reversed);
System.out.println("Uppercase: " + text.toUpperCase());
System.out.println("Lowercase: " + text.toLowerCase());

scanner.close();
}
}

Exercise 5: Simple Banking System

import java.text.DecimalFormat;
import java.util.Scanner;

public class SimpleBankAccount {
private static double balance = 1000.0; // Starting balance
private static DecimalFormat currency = new DecimalFormat("$#,##0.00");

public static void displayMenu() {
System.out.println("\n=== Simple Banking System ===");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Exit");
System.out.print("Choose an option (1-4): ");
}

public static void checkBalance() {
System.out.println("Current Balance: " + currency.format(balance));
}

public static void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + currency.format(amount));
System.out.println("New Balance: " + currency.format(balance));
} else {
System.out.println("Invalid deposit amount!");
}
}

public static void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + currency.format(amount));
System.out.println("New Balance: " + currency.format(balance));
} else if (amount > balance) {
System.out.println("Insufficient funds! Your balance is " + currency.format(balance));
} else {
System.out.println("Invalid withdrawal amount!");
}
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

System.out.println("Welcome to Simple Bank!");

do {
displayMenu();
choice = scanner.nextInt();

switch (choice) {
case 1:
checkBalance();
break;
case 2:
System.out.print("Enter deposit amount: $");
double depositAmount = scanner.nextDouble();
deposit(depositAmount);
break;
case 3:
System.out.print("Enter withdrawal amount: $");
double withdrawAmount = scanner.nextDouble();
withdraw(withdrawAmount);
break;
case 4:
System.out.println("Thank you for using Simple Bank!");
break;
default:
System.out.println("Invalid option! Please choose 1-4.");
}
} while (choice != 4);

scanner.close();
}
}

Summary and Next Steps

Key Concepts Covered

  • Data Types: Primitive and reference types, proper usage
  • Variables and Constants: Declaration, initialization, naming conventions
  • Operators: Arithmetic, comparison, logical, assignment
  • Input/Output: Scanner class for input, various output methods
  • Random Class: Generating random numbers and values
  • Number Formatting: DecimalFormat, printf, currency formatting
  • Strings: Creation, manipulation, StringBuilder for efficiency
  • Control Structures: if-else, switch, loops (for, while, do-while)
  • Arrays: Single and multi-dimensional arrays, array utilities
  • Methods: Declaration, parameters, return types, overloading

Comparison with JavaScript (Key Differences)

  • Static Typing: Java requires explicit type declarations
  • Compilation: Java is compiled to bytecode, JavaScript is interpreted
  • Object-Oriented: Java is primarily OOP, JavaScript supports multiple paradigms
  • Memory Management: Java has automatic garbage collection
  • Platform Independence: Java's "write once, run anywhere" philosophy

Best Practices for Java Beginners

  1. Always close Scanner objects to prevent resource leaks
  2. Use meaningful variable names (camelCase convention)
  3. Handle exceptions properly (we'll cover this in advanced topics)
  4. Use StringBuilder for multiple string concatenations
  5. Initialize variables before using them
  6. Follow proper indentation and code formatting
  7. Write comments to explain complex logic

Next Steps in Your Java Journey

  1. Object-Oriented Programming: Classes, objects, inheritance, polymorphism
  2. Exception Handling: try-catch blocks, custom exceptions
  3. Collections Framework: ArrayList, HashMap, Set, etc.
  4. File I/O: Reading from and writing to files
  5. GUI Development: Swing or JavaFX for desktop applications
  6. Web Development: Spring Framework for web applications
  7. Database Connectivity: JDBC for database operations

Practice Recommendations

  • Solve coding problems daily (start with simple, progress to complex)
  • Build small projects (calculator, todo list, simple games)
  • Read and understand other people's code
  • Join Java communities and forums
  • Practice with online coding platforms

Remember: Programming is learned by doing. The more you practice writing Java code, the more comfortable you'll become with the language. Start with simple programs and gradually work your way up to more complex applications.

Good luck with your Java programming journey! 🚀