Java 101: Understanding the Core Concepts
Table of Contents
- Basic Syntax and Structure
- Variables and Data Types
- Control Structures
- Object - Oriented Programming in Java
- Exception Handling
- Input and Output Operations
- Common Practices and Best Practices
- Conclusion
- References
Basic Syntax and Structure
Structure of a Java Program
A Java program consists of one or more classes. The most basic Java program has a main method, which serves as the entry point of the program.
// A simple Java program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
In this example, HelloWorld is the class name. The main method is declared as public static void, where public means it can be accessed from anywhere, static means it belongs to the class rather than an instance of the class, and void means it does not return any value. The args parameter is an array of strings that can be used to pass command - line arguments to the program.
Compilation and Execution
To run a Java program, you first need to compile it using the javac compiler and then execute the compiled bytecode using the java command.
# Compile the program
javac HelloWorld.java
# Run the program
java HelloWorld
Variables and Data Types
Primitive Data Types
Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean.
public class VariableExample {
public static void main(String[] args) {
int num = 10;
double decimalNum = 10.5;
char letter = 'A';
boolean isTrue = true;
System.out.println("Integer: " + num);
System.out.println("Double: " + decimalNum);
System.out.println("Character: " + letter);
System.out.println("Boolean: " + isTrue);
}
}
Reference Data Types
Reference data types include classes, interfaces, and arrays. An array is a collection of elements of the same data type.
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Control Structures
Conditional Statements
Java supports if - else and switch statements for conditional execution.
public class ConditionalExample {
public static void main(String[] args) {
int num = 10;
if (num > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is less than or equal to 5");
}
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
Looping Statements
Java has for, while, and do - while loops for repetitive execution.
public class LoopExample {
public static void main(String[] args) {
// For loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// While loop
int j = 0;
while (j < 5) {
System.out.println(j);
j++;
}
// Do - while loop
int k = 0;
do {
System.out.println(k);
k++;
} while (k < 5);
}
}
Object - Oriented Programming in Java
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
class Car {
String color;
int year;
public Car(String color, int year) {
this.color = color;
this.year = year;
}
public void displayInfo() {
System.out.println("Color: " + color + ", Year: " + year);
}
}
public class ObjectExample {
public static void main(String[] args) {
Car myCar = new Car("Blue", 2020);
myCar.displayInfo();
}
}
Inheritance
Inheritance allows a class to inherit the properties and methods of another class.
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Shape myShape = new Circle();
myShape.draw();
}
}
Exception Handling
Java uses try - catch - finally blocks for exception handling.
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}
Input and Output Operations
Reading User Input
You can use the Scanner class to read user input from the console.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
scanner.close();
}
}
Writing Output to a File
You can use the FileWriter and BufferedWriter classes to write data to a file.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class OutputExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("This is a sample text.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Common Practices and Best Practices
Naming Conventions
- Classes: Use PascalCase (e.g.,
MyClass). - Methods and Variables: Use camelCase (e.g.,
myMethod,myVariable). - Constants: Use all uppercase with underscores (e.g.,
MAX_VALUE).
Code Readability
- Write short, single - purpose methods.
- Add comments to explain complex code segments.
Memory Management
- Avoid creating unnecessary objects.
- Use
try - with - resourcesstatements to automatically close resources.
Conclusion
Java is a powerful and versatile programming language with a rich set of core concepts. By understanding basic syntax, variables, control structures, object - oriented programming, exception handling, and input/output operations, you can build a solid foundation for Java development. Following common practices and best practices will help you write clean, efficient, and maintainable code.
References
- Oracle Java Documentation: https://docs.oracle.com/javase/8/docs/
- “Effective Java” by Joshua Bloch.
- “Head First Java” by Kathy Sierra and Bert Bates.