Writing Java Source Code
Understanding Java Source Code Structure
Java source code is typically organized with specific rules and conventions. Each Java program is composed of classes, methods, and statements that define the program's behavior.
Basic Source Code Components
graph TD
A[Package Declaration] --> B[Import Statements]
B --> C[Class Definition]
C --> D[Methods]
D --> E[Program Logic]
Naming Conventions
Element |
Naming Rule |
Example |
Class Names |
Start with Capital Letter |
StudentRecord |
Method Names |
Start with Lowercase |
calculateTotal() |
Variables |
Camel Case |
studentAge |
Constants |
Uppercase with Underscores |
MAX_STUDENTS |
Creating a Simple Java Class
// Package declaration (optional)
package com.labex.tutorial;
// Import necessary classes
import java.util.Scanner;
// Class definition
public class StudentManagement {
// Instance variables
private String studentName;
private int studentAge;
// Constructor method
public StudentManagement(String name, int age) {
this.studentName = name;
this.studentAge = age;
}
// Method to display student information
public void displayInfo() {
System.out.println("Name: " + studentName);
System.out.println("Age: " + studentAge);
}
// Main method for program execution
public static void main(String[] args) {
StudentManagement student = new StudentManagement("John Doe", 20);
student.displayInfo();
}
}
Data Types in Java
Java supports multiple data types:
graph TD
A[Primitive Types] --> B[Integer Types]
A --> C[Floating Point Types]
A --> D[Boolean Type]
A --> E[Character Type]
B --> F[byte]
B --> G[short]
B --> H[int]
B --> I[long]
C --> J[float]
C --> K[double]
Variable Declaration and Initialization
// Primitive type declarations
int age = 25;
double salary = 5000.50;
boolean isStudent = true;
char grade = 'A';
// Reference type declaration
String name = "LabEx Student";
Control Structures
Conditional Statements
// If-else statement
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
// Switch statement
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
}
Loops
// For loop
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
// While loop
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
Compiling Java Source Code
To compile the Java source code on Ubuntu 22.04:
## Compile the Java file
javac StudentManagement.java
## Run the compiled program
java StudentManagement
Best Practices
- Use meaningful variable and method names
- Keep methods small and focused
- Follow consistent indentation
- Add comments to explain complex logic
- Handle exceptions properly
By following these guidelines, you can write clean, readable, and efficient Java source code using LabEx programming techniques.