Basic Java Programming Concepts

1. Variables and Data Types

What is a Variable?

Think of a variable as a labeled container or a “storage box” in your computer’s memory. You store data inside this box so you can use, modify, or reference it later in your code.

Every variable in Java requires three things:

  1. Data Type: Specifies what kind of data the box can hold (e.g., numbers, text).

  2. Name (Identifier): The unique name used to access the container.

  3. Value: The actual data assigned to the variable.

 

Data Types in Java

Java is a strongly typed language, meaning every variable must have a declared data type. Data types fall into two main categories:

A. Primitive Data Types

These are built-in types that store raw values directly in memory

 

  • byte: Extremely small integers (1 byte, range: –128 to 127).

  • short: Small integers (2 bytes).

  • int: Standard integer numbers (4 bytes) – Most Commonly Used.

  • long: Very large integers (8 bytes, append an L at the end).

  • float: Single-precision decimal numbers (4 bytes, append an f at the end).

  • double: Double-precision decimal numbers (8 bytes) – Most Commonly Used for Decimals.

  • char: A single character enclosed in single quotes ' ' (2 bytes, uses Unicode).

  • boolean: Stores only true or false (1 bit).

 

B. Non-Primitive Data Types

These store references to objects rather than raw values. The most common non-primitive type for text is:

  • String: Stores sequences of text enclosed in double quotes " ".

Example Code: Declaring and Initializing Variables

public class VariablesDemo {
public static void main(String[] args) {
// Primitive Data Types
int userAge = 21;
double accountBalance = 1250.75;
char userGrade = 'A';
boolean isSubscriber = true;

// Non-Primitive Data Type
String userName = "Alex";

// Displaying stored values
System.out.println("User: " + userName);
System.out.println("Age: " + userAge);
System.out.println("Balance: $" + accountBalance);
System.out.println("Grade: " + userGrade);
System.out.println("Subscribed: " + isSubscriber);
}
}

2. Operators in Java

Operators are symbols that perform mathematical or logical operations on variables and values (called operands).

Category Symbols Purpose Example
Arithmetic +, -, *, /, % Perform basic math calculations 10 % 3 evaluates to 1 (remainder)
Relational ==, !=, >, <, >=, <= Compare two values (returns true/false) age >= 18
Logical && (AND), || (OR), ! (NOT) Combine boolean expressions (age >= 18) && isRegistered
Assignment =, +=, -=, *=, /= Assign or update variable values score += 10 (same as score = score + 10)
Unary ++ (Increment), -- (Decrement) Increase or decrease a value by 1 count++

Example Code: Working with Operators

public class OperatorsDemo {
public static void main(String[] args) {
int itemPrice = 200;
int walletBalance = 500;
int discountCode = 50;

// Arithmetic Operator
int finalPrice = itemPrice - discountCode;

// Relational Operator
boolean canAfford = walletBalance >= finalPrice;

// Logical Operator
boolean isEligibleForPurchase = canAfford && (finalPrice > 100);

System.out.println("Final Price: $" + finalPrice);
System.out.println("Can afford purchase? " + canAfford);
System.out.println("Eligible for special deal? " + isEligibleForPurchase);

// Unary Operator
int streak = 5;
streak++; // Increases streak to 6
System.out.println("Current Streak: " + streak);
}
}

3. Input and Output in Java

To make interactive applications, programs need to display output to users and read input from them.

Output in Java

Java uses the built-in System.out object:

  • System.out.print(): Prints text without moving to a new line.

  • System.out.println(): Prints text and automatically jumps to the next line.

 

Input in Java using Scanner

To accept input from the console, Java provides the Scanner class from the java.util package.

 

Commonly Used Scanner Methods:

  • nextInt(): Reads an integer value.

  • nextDouble(): Reads a decimal value.

  • next(): Reads a single word.

  • nextLine(): Reads a complete line of text.

Example Code: User Profile Generator

import java.util.Scanner; // Step 1: Import the Scanner class

public class InputOutputDemo {
public static void main(String[] args) {
// Step 2: Create a Scanner object
Scanner scanner = new Scanner(System.in);

// Prompting user for input
System.out.print("Enter your gamer tag: ");
String gamerTag = scanner.nextLine();

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

System.out.print("Enter your win rate percentage (e.g., 68.5): ");
double winRate = scanner.nextDouble();

// Outputting formatted data
System.out.println("\n--- Player Card Created ---");
System.out.println("Tag: " + gamerTag);
System.out.println("Level: " + level);
System.out.println("Win Rate: " + winRate + "%");

// Step 3: Close the scanner to prevent memory leaks
scanner.close();
}
}

4. Type Casting

Type casting occurs when you assign a value of one primitive data type to another data type.

Types of Casting

A. Implicit (Widening) Casting

  • Automatic: Handled by Java automatically.

  • Safe: Converts a smaller data type into a larger data type without losing data precision.

  • Flow: byte → short → char → int → long → float → double

 

B. Explicit (Narrowing) Casting

  • Manual: Requires explicit programmer intervention.

  • Caution: Converts a larger data type into a smaller data type, which can result in data loss.

 

Example Code: Type Casting in Action

public class TypeCastingDemo {
public static void main(String[] args) {
// Widening (Implicit) Casting: int to double
int totalScore = 450;
double precisionScore = totalScore; // Automatic conversion
System.out.println("Integer Score: " + totalScore);
System.out.println("Converted to Double: " + precisionScore);

// Narrowing (Explicit) Casting: double to int
double exactPrice = 99.99;
int roundedPrice = (int) exactPrice; // Manual casting (truncates decimal part)

System.out.println("\nExact Price: $" + exactPrice);
System.out.println("Cast to Integer: $" + roundedPrice); // Output is 99
}
}

 

5. Comments in Java

Comments are notes added directly inside the source code to explain logic. The Java compiler completely ignores comments during code execution.

Why Use Comments?

  • Improves code readability for team members.

  • Helps you remember your code logic when returning to a project later.

  • Temporarily disables specific lines of code during debugging.

 

Types of Comments

  • Single-Line Comments: Starts with //. Used for brief notes.

  • Multi-Line Comments: Enclosed within /* and */. Used for longer explanations across multiple lines.

  • Documentation Comments (Javadoc): Enclosed within /** and */. Used for generating formal documentation for APIs and public methods.

 

Example Code: Types of Comments

/**
* <h1>Module 2 Practice Code</h1>
* This class demonstrates all three types of Java comments.
*
* @author Coding Tutor
* @version 1.0
*/
public class CommentsDemo {
public static void main(String[] args) {

// Single-line comment: Declaring maximum allowed attempts
int maxAttempts = 3;

/*
Multi-line comment:
The following variable checks if the user
has active administrative privileges.
*/
boolean isAdmin = false;

System.out.println("Max Attempts allowed: " + maxAttempts);
System.out.println("Is Admin: " + isAdmin);
}
}

 

 

 

 

 

 

 

 

 

 

Â