Object Oriented Programming With JavaUnit 114 min read
Java Basics: Syntax, Structure & Core Concepts
Unit 1 of Object Oriented Programming With Java introduces Java's architecture, syntax rules, program structure, and fundamental concepts like variables, data types, operators, and control flow—essential for writing executable Java code.
TAKEAWAYS:
- Java programs run on the JVM, making it platform-independent ("write once, run anywhere").
- Every Java program must have a
mainmethod with signaturepublic static void main(String[] args). - Variables store data, and data types (primitive and reference) define what kind of data they hold.
- Operators perform operations on variables (arithmetic, logical, relational, etc.).
- Control flow (loops, conditionals) dictates program execution logic.
- Comments (
//,/* */,/** */) improve code readability and documentation.
1. Java Program Structure
Java programs follow a strict structure. Every executable Java program must have:
- A class (public by convention).
- A
mainmethod (entry point for execution).
Example: Basic Java Program
// Single-line comment
/*
Multi-line comment
*/
public class HelloWorld { // Class declaration
public static void main(String[] args) { // Main method
System.out.println("Hello, World!"); // Statement
}
}
Key Components
| Component | Description |
|---|---|
| Class | Blueprint for objects (must match filename). |
main Method |
Entry point for JVM execution (public static void main(String[] args)). |
| Statements | Instructions executed sequentially (end with ;). |
| Comments | Ignored by JVM (//, /* */, /** */). |
2. Java Syntax Rules
Java is case-sensitive and enforces strict syntax rules:
- Class names must start with uppercase (e.g.,
Student). - Method names start with lowercase (e.g.,
calculateGrade()). - Statements end with a semicolon (
;). - Blocks use curly braces
{}.
Example: Variable Declaration
public class Variables {
public static void main(String[] args) {
int age = 20; // Primitive type
String name = "Alice"; // Reference type
System.out.println(name + " is " + age + " years old.");
}
}
Output:
Alice is 20 years old.
3. Data Types in Java
Java supports two categories of data types:
- Primitive Types (8 types, store direct values).
- Reference Types (objects, store memory addresses).
Primitive Data Types
| Type | Size (bits) | Range | Example |
|---|---|---|---|
byte |
8 | -128 to 127 | byte b = 10; |
short |
16 | -32,768 to 32,767 | short s = 100; |
int |
32 | -2,147,483,648 to 2,147,483,647 | int i = 1000; |
long |
64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | long l = 1000000L; |
float |
32 | 3.4e-038 to 3.4e+038 | float f = 3.14f; |
double |
64 | 1.7e-308 to 1.7e+308 | double d = 3.14159; |
char |
16 | Unicode (0 to 65,535) | char c = 'A'; |
boolean |
1 | true or false |
boolean flag = true; |
Reference Types
String(immutable sequence of characters).- Arrays (fixed-size collections).
- Objects (instances of classes).
Example: Array Declaration
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
String[] names = {"Alice", "Bob", "Charlie"}; // Array of Strings
4. Variables and Constants
- Variables: Store data that can change (
int age = 20;). - Constants: Fixed values (
final double PI = 3.14159;).
Example: Constants
public class Constants {
public static void main(String[] args) {
final double TAX_RATE = 0.13; // Constant (cannot be changed)
double total = 100.0 * (1 + TAX_RATE);
System.out.println("Total with tax: " + total);
}
}
Output:
Total with tax: 113.0
5. Operators in Java
Operators perform operations on variables and values.
Types of Operators
| Category | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, %, ++, -- |
int sum = a + b; |
| Relational | ==, !=, >, <, >=, <= |
if (a > b) |
| Logical | &&, ||, ! |
if (a > 0 && b < 10) |
| Assignment | =, +=, -=, *=, /= |
a += 5; |
| Bitwise | &, |, ^, ~, <<, >> |
int mask = a & 0xFF; |
Example: Arithmetic Operators
public class Operators {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("a + b = " + (a + b)); // 13
System.out.println("a - b = " + (a - b)); // 7
System.out.println("a * b = " + (a * b)); // 30
System.out.println("a / b = " + (a / b)); // 3 (integer division)
System.out.println("a % b = " + (a % b)); // 1 (remainder)
}
}
6. Control Flow Statements
Control flow determines the order of execution.
flowchart TD
A["Start"] --> B["Check if age >= 18"]
B -->|"Yes"| C["Print 'Eligible to vote.'"]
B -->|"No"| D["Print 'Not eligible.'"]
C --> E["End"]
D --> EFlowchart of the if-else example for voting eligibility
a. Conditional Statements
if,else if,else: Execute code based on conditions.switch: Execute one of many code blocks.
Example: if-else
int age = 18;
if (age >= 18) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible.");
}
Example: switch
char grade = 'B';
switch (grade) {
case 'A': System.out.println("Excellent!"); break;
case 'B': System.out.println("Good job!"); break;
case 'C': System.out.println("Average."); break;
default: System.out.println("Try harder.");
}
b. Loops
for: Repeat code a fixed number of times.while: Repeat while a condition is true.do-while: Execute at least once, then repeat while condition is true.
Example: for Loop
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
Example: while Loop
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
7. Input and Output
Java uses System.out.println() for output and Scanner for input.
Example: User Input
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close();
}
}
8. Comments in Java
Comments improve code readability and documentation.
- Single-line:
// This is a comment - Multi-line:
/* This is a multi-line comment */ - Javadoc:
/** Documentation */(used for API generation).
Example: Javadoc
/**
* This class calculates the area of a rectangle.
*/
public class Rectangle {
/**
* Calculates the area of a rectangle.
* @param length Length of the rectangle.
* @param width Width of the rectangle.
* @return Area of the rectangle.
*/
public static double calculateArea(double length, double width) {
return length * width;
}
}
In the Real World
Java’s fundamentals power many real-world applications in Nepal and globally:
eSewa (Nepal)
- Uses Java’s
Stringmanipulation to validate user inputs (e.g., phone numbers, transaction IDs). - Example: Checking if a phone number is exactly 10 digits before processing a payment.
- Uses Java’s
Khalti (Nepal)
- Relies on Java’s
Scannerandif-elseconditions for user authentication (e.g., verifying OTPs). - Example: A loop to retry OTP entry if the user fails 3 times.
- Relies on Java’s
Ncell (Nepal)
- Uses Java’s
switch-caseto route calls based on user input (e.g., pressing1for balance check,2for recharge). - Example:
int choice = scanner.nextInt(); switch (choice) { case 1: checkBalance(); break; case 2: recharge(); break; default: System.out.println("Invalid choice."); }
- Uses Java’s
Google (Global)
- Java’s
ArrayListmanages dynamic data (e.g., search results, ads). - Example: Storing and sorting millions of search queries efficiently.
- Java’s
YouTube (Global)
- Java’s
Stringandif-elsehandle video metadata (e.g., checking if a video is age-restricted). - Example:
if (video.isAgeRestricted() && user.getAge() < 18) { showRestrictedContentWarning(); }
- Java’s
Exam Tip
- Memorize the
mainmethod signature:public static void main(String[] args)is mandatory for executable programs. - Practice variable declarations: Know the difference between primitive (
int,double) and reference (String,Array) types. - Understand operator precedence: For example,
*has higher precedence than+, soa + b * cis evaluated asa + (b * c). - Write comments: Even simple programs should include comments for clarity (especially in exams).
- Trace code step-by-step: For questions involving loops or conditions, draw a table of variable values at each step.
- Common mistakes to avoid:
- Forgetting semicolons (
;). - Mismatched braces (
{}). - Using incorrect data types (e.g.,
Stringinstead ofint).
- Forgetting semicolons (
- For array questions, always show:
- Initial array state.
- State after each operation (e.g., insertion, deletion).
- Example:
int[] arr = {1, 2, 3}; // After arr[1] = 5: // arr = {1, 5, 3}
Worked Example: Loan Interest Calculation (Bank Scenario)
Problem: Write a Java program to calculate simple interest for a bank loan. Formula:
import java.util.Scanner;
public class LoanInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (in %): ");
double rate = scanner.nextDouble() / 100; // Convert % to decimal
System.out.print("Enter time (in years): ");
double time = scanner.nextDouble();
double interest = principal * rate * time;
System.out.printf("Simple Interest: %.2f%n", interest);
System.out.printf("Total Amount: %.2f%n", principal + interest);
scanner.close();
}
}
Trace for Input: Principal = 10000, Rate = 5%, Time = 2 Years
| Step | Variable | Value | Calculation |
|---|---|---|---|
| 1 | principal |
10000.0 | User input |
| 2 | rate |
0.05 | 5 / 100 |
| 3 | time |
2.0 | User input |
| 4 | interest |
1000.0 | 10000 * 0.05 * 2 |
| 5 | Total Amount |
11000.0 | 10000 + 1000 |
Output:
Simple Interest: 1000.00
Total Amount: 11000.00
Visual: Java Program Execution Flow
flowchart TD
A["Start"] --> B["JVM Loads Class"]
B --> C["Finds main() Method"]
C --> D["Executes main()"]
D --> E["Runs Statements Sequentially"]
E --> F["End of Program"]Visual: Array Operations
Initial Array:
int[] arr = {10, 20, 30, 40, 50};
After arr[2] = 99:
// State after modification
arr = {10, 20, 99, 40, 50};
Comparison Table: Primitive vs. Reference Types
| Feature | Primitive Types | Reference Types |
|---|---|---|
| Storage | Direct value | Memory address (object) |
| Default Value | 0, 0.0, false, etc. |
null |
| Methods | No methods | Can have methods (e.g., String.length()) |
| Memory | Stack memory | Heap memory |
| Example | int x = 5; |
String s = new String("Hi"); |
Visual: Operator Precedence
mindmap
root((Operator Precedence))
--> Arithmetic
--> Multiplicative (* / %)
--> Additive (+ -)
--> Relational (== != > < >= <=)
--> Logical (! && ||)
--> Assignment (= += -= *= /=)Key Formulas to Remember
- Simple Interest: (Where , , )
- Compound Interest:
- Area of Rectangle:
Common Pitfalls in Exams
- Forgetting
public static void main(String[] args): Leads to compilation errors. - Incorrect variable naming: Java is case-sensitive (
age≠Age). - Mismatched braces: Always count
{}pairs. - Using
==for objects: Use.equals()forStringcomparisons.// Wrong: if (str1 == str2) { ... } // Correct: if (str1.equals(str2)) { ... } - Off-by-one errors in loops:
// Prints 1 to 4 (not 5) for (int i = 1; i <= 5; i++) { ... }
In the real world
- eSewa uses control flow statements (loops and conditionals) to validate user transactions. For example, when checking if a user has sufficient balance before processing a payment, it uses
if-elseblocks to handle success/failure cases. - Nepali banks (e.g., NMB, Global IME) apply data types (primitive like
intfor account numbers,doublefor balances) and operators (arithmetic for interest calculations) in their ATM systems to process withdrawals/deposits. - Pathao leverages arrays (or linked lists) to manage driver locations in real-time, updating them dynamically as drivers accept/reject rides.
Based on the TU BITM syllabus for Object Oriented Programming With Java (IT234), unit 1.
Discussion
Loading…