Java Programming Day 1

HimanshiHimanshi
9 min read

๐Ÿ“ Day 1: Java Basics with Bro Code โ€“ Part 1

Hi! I'm learning Java from Bro Code's YouTube course and documenting everything here. These are the beginner concepts I practiced today, explained in my own words with full code examples and comments. ๐Ÿ˜Š


โœ… 1. Hello World Program

// Program 1: Hello World
public class HelloWorld {
    public static void main(String[] args) {
        // Prints "Hello world!" on the screen
        System.out.println("Hello world!");

        // Prints another line
        System.out.println("I love Pizza!");
    }
}

๐Ÿ“˜ What I learned:

  • System.out.println() is used to display text.

  • Java programs start with the main method.

  • Every statement ends with a ;.


โœ… 2. Integer Variables โ€“ Declaration vs Initialization

// Program 2: Integer Variables
public class IntegerExample {
    public static void main(String[] args) {

        // Declaration: telling Java that you're going to use an integer
        int age;

        // Initialization: giving it a value
        age = 18;

        // Declaration and initialization in one step
        int year = 2025;
        int quantity = 1;

        // Displaying values
        System.out.println("Age: " + age);
        System.out.println("Year: " + year);
        System.out.println("Quantity: " + quantity);
    }
}

๐Ÿ“˜ What I learned:

  • int stores whole numbers (no decimals).

  • Declaration = int age;

  • Initialization = age = 18;

  • You can combine both like: int age = 18;


โœ… 3. Double Variables โ€“ Decimal Numbers

// Program 3: Double Variables
public class DoubleExample {
    public static void main(String[] args) {

        // Storing decimal numbers using 'double'
        double price = 19.9;
        double price2 = 19.0;
        double gpa = 8.1;
        double temperature = -12.5;

        // Displaying decimal values
        System.out.println("Price: $" + price);
        System.out.println("Price2: $" + price2);
        System.out.println("GPA: " + gpa);
        System.out.println("Temperature: " + temperature + "ยฐC");
    }
}

๐Ÿ“˜ What I learned:

  • double is used for decimal values.

  • Useful for things like GPA, temperature, price, etc.


โœ… 4. Char Variables โ€“ Single Characters

// Program 4: Character Variables
public class CharExample {
    public static void main(String[] args) {

        // Storing a single character using 'char'
        char grade = 'A';       // Student's grade
        char currency = '$';    // Currency symbol
        char symbol = '!';      // Just a symbol

        // Displaying characters
        System.out.println("Grade: " + grade);
        System.out.println("Currency: " + currency);
        System.out.println("Symbol: " + symbol);
    }
}

๐Ÿ“˜ What I learned:

  • char stores one single character only.

  • Must use single quotes like 'A', not double quotes.


โœ… 5. Boolean Variables โ€“ True or False

// Program 5: Boolean Variables
public class BooleanExample {
    public static void main(String[] args) {

        // Booleans can be either true or false
        boolean isStudent = true;
        boolean forSale = false;
        boolean isOnline = true;

        // Displaying boolean values
        System.out.println("Are you a student? " + isStudent);
        System.out.println("Is it for sale? " + forSale);
        System.out.println("Are you online? " + isOnline);
    }
}

๐Ÿ“˜ What I learned:

  • boolean is used for yes/no or true/false values.

  • Very useful in conditions and logic.


โœ… 6. If-Else Statement โ€“ Making Decisions

// Program 6: If-Else Statement
public class IfExample {
    public static void main(String[] args) {

        // A boolean condition
        boolean isStudent = true;

        // Checking the condition
        if (isStudent) {
            System.out.println("You are a student!");
        } else {
            System.out.println("You are not a student.");
        }
    }
}

๐Ÿ“˜ What I learned:

  • if is used to check a condition.

  • else is used when the condition is not true.

  • Conditions must return a boolean value (true or false).


โœ… 7. Taking Input from User + If-Else Logic

// Program 7: Scanner Input and Conditional Logic
import java.util.Scanner;

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

        // Create a Scanner object to take input
        Scanner scanner = new Scanner(System.in);

        // Input: name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello " + name);

        // Input: age (int)
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println("You are " + age + " years old.");

        scanner.nextLine(); // Clear newline left by nextInt()

        // Input: favorite color
        System.out.print("Enter your favorite color: ");
        String color = scanner.nextLine();
        System.out.println("Your favorite color is: " + color);

        // Input: GPA (double)
        System.out.print("Enter your GPA: ");
        double gpa = scanner.nextDouble();
        System.out.println("Your GPA is: " + gpa);

        scanner.nextLine(); // Clear newline left by nextDouble()

        // Input: Are you a student?
        System.out.print("Are you a student? (true/false): ");
        boolean isStudent = scanner.nextBoolean();

        // Decision making using if-else
        if (isStudent) {
            System.out.println("You are enrolled as a Student.");
        } else {
            System.out.println("You are not enrolled.");
        }

        scanner.close();
    }
}

๐Ÿ“˜ What I learned:

  • Use Scanner to take input from users.

  • Always close your scanner when done: scanner.close();

  • Use nextLine() after nextInt() or nextDouble() to consume leftover newline.

  • You can combine user input and logic using if-else to build interactive programs.

โœ… 8. Calculate Area of a Rectangle โ€“ Using Scanner & Math

javaCopyEdit// Program 8: Calculate Area of Rectangle using user input
import java.util.Scanner;

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

        // Step 1: Declare and initialize variables
        double width = 0;   // Declaration + Initialization
        double height = 0;  // Declaration + Initialization
        double area = 0;    // To store the calculated result

        // Step 2: Create Scanner object
        Scanner scanner = new Scanner(System.in);

        // Step 3: Ask user to input width
        System.out.print("Enter the width: ");
        width = scanner.nextDouble();  // Read decimal input for width

        // Step 4: Ask user to input height
        System.out.print("Enter the height: ");
        height = scanner.nextDouble(); // Read decimal input for height

        // Step 5: Calculate area using formula: width ร— height
        area = width * height;

        // Step 6: Display the result
        System.out.println("The area is: " + area + " cmยฒ");

        // Step 7: Close the scanner
        scanner.close();
    }
}

Overview:

This program prompts the user to enter the width and height of a rectangle, calculates the area using these inputs, and then displays the result. It uses Java's Scanner class to capture user input from the console.


Step-by-step Description:

  1. Variable Declaration and Initialization
    The program starts by declaring three double variables:

    • width: to hold the width of the rectangle

    • height: to hold the height of the rectangle

    • area: to store the calculated area
      Each of these variables is initialized to 0 to ensure they have a defined value before use.

  2. Creating a Scanner Object
    A Scanner object named scanner is created. This object enables the program to read user input from the standard input stream (keyboard).

  3. Prompting for Width
    The program prints the prompt "Enter the width: " to the console, inviting the user to enter the rectangleโ€™s width. It then reads the userโ€™s input as a decimal number (double) and stores it in the variable width.

  4. Prompting for Height
    Similarly, the program asks the user to enter the height with the prompt "Enter the height: ". It reads the decimal input and stores it in the variable height.

  5. Calculating the Area
    The area of a rectangle is calculated using the formula:

    area=widthร—height\text{area} = \text{width} \times \text{height}area=widthร—height

    The program multiplies the two inputs and stores the result in the variable area.

  6. Displaying the Result
    The calculated area is displayed back to the user in a formatted message:
    "The area is: X cmยฒ"
    where X is the computed value of area.

  7. Closing the Scanner
    To prevent resource leaks, the program closes the scanner object once it is no longer needed.


Key Points:

  • The use of double allows the program to handle decimal numbers, which is useful for more precise measurements.

  • The Scanner class is a standard way to read input from the user.

  • Multiplying width and height gives the area of the rectangle.

  • Closing the scanner is good practice in Java to free system resources.


โœ… 9. Mad Libs Story Generator โ€“ Fun with Strings & Input

javaCopyEdit// Program 9: A Mad Libs-style word game using user input and string concatenation
import java.util.Scanner;

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

        // Step 1: Create Scanner object to read user input
        Scanner scanner = new Scanner(System.in);

        // Step 2: Declare variables (only declared here, initialized later)
        String adjective1;
        String noun1;
        String adjective2;
        String verb1;
        String adjective3;

        // Step 3: Get user inputs
        System.out.print("Enter an adjective (description): ");
        adjective1 = scanner.nextLine();  // e.g., "funny"

        System.out.print("Enter a noun (animal or person): ");
        noun1 = scanner.nextLine();  // e.g., "monkey"

        System.out.print("Enter an adjective (description): ");
        adjective2 = scanner.nextLine();  // e.g., "noisy"

        System.out.print("Enter a verb ending with -ing (action): ");
        verb1 = scanner.nextLine();  // e.g., "dancing"

        System.out.print("Enter an adjective (description): ");
        adjective3 = scanner.nextLine();  // e.g., "amazed"

        // Step 4: Generate the fun story using concatenation
        System.out.println("\nToday I went to a " + adjective1 + " zoo.");
        System.out.println("In an exhibit, I saw a " + noun1 + ".");
        System.out.println("The " + noun1 + " was " + adjective2 + " and " + verb1 + "!");
        System.out.println("I was " + adjective3 + "!");

        // Step 5: Close scanner to avoid memory leaks
        scanner.close();
    }
}

๐Ÿ“˜Overview:

This program creates a simple interactive story where the user provides words that fit specific parts of speech. These words are then combined to form a funny, personalized story. It demonstrates basic user input, string variables, and concatenation in Java.


Step-by-step Explanation:

  1. Scanner Creation for User Input
    The program starts by creating a Scanner object to read text input from the user. This object enables the program to capture the words the user types.

  2. Declaring String Variables
    Several string variables are declared to store the different types of words the user will provide:

    • adjective1 (a descriptive word)

    • noun1 (a noun, like an animal or person)

    • adjective2 (another descriptive word)

    • verb1 (a verb ending with โ€œ-ingโ€, describing an action)

    • adjective3 (one more descriptive word)

  3. Getting User Input
    The program prompts the user to enter each type of word one by one. For each prompt, it waits for the user to type a word or phrase and presses enter. This input is then stored in the corresponding variable. Example inputs might be "funny" for an adjective or "monkey" for a noun.

  4. Building and Displaying the Story
    After collecting all the inputs, the program constructs a short story by combining fixed text with the userโ€™s words. This is done by concatenating the strings to form complete sentences. For example:

    • "Today I went to a funny zoo."

    • "In an exhibit, I saw a monkey."

    • "The monkey was noisy and dancing!"

    • "I was amazed!"
      This creates a personalized and humorous narrative based on the userโ€™s inputs.

  5. Closing the Scanner
    Finally, the program closes the scanner object to free up system resources and avoid potential memory issues.


Key Concepts Highlighted:

  • User Input: Collecting multiple inputs from the user in sequence.

  • String Variables: Storing words and phrases for later use.

  • String Concatenation: Joining strings and variables together to form meaningful sentences.

  • Interactive Storytelling: Using input to dynamically generate text output.


๐Ÿง  Summary (Updated with String Input)

ConceptKeywordExampleNotes
Print OutputprintlnSystem.out.println("Hi");Displays text
Integersintint age = 18;Whole numbers
Decimalsdoubledouble price = 49.99;Decimal numbers
Characterscharchar grade = 'A';One character
Booleansbooleanboolean isJavaFun = true;true or false
StringsStringString name = "Alice";Text enclosed in double quotes
InputScannerScanner sc = new Scanner();Reads user input
Concatenation+"Hello " + nameCombines multiple strings
1
Subscribe to my newsletter

Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshi
Himanshi

Hi! I'm a curious and self-driven programmer currently pursuing my BCA ๐ŸŽ“ and diving deep into the world of Java โ˜• from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. Iโ€™m learning Java through Bro Codeโ€™s YouTube tutorials, experimenting with code, and documenting everything I understand โ€” from basic syntax to real-world applications โ€” to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. Youโ€™ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. ๐Ÿ’ก Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge ๐Ÿ› ๏ธ Tools: Java โ€ข HTML/CSS โ€ข JavaScript โ€ข Python (basics) โ€ข SQL ๐ŸŽฏ Goal: To become a confident Full Stack Developer & AI Explorer ๐Ÿ“ Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe