Introduction to Java | Programming Basics
What is Java?
Java is a versatile, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). Known for its platform independence and strong community support, Java has become a staple for developing everything from desktop to web applications.
Hello World Program
The classic "Hello, World!" program demonstrates the basic syntax of Java:
Code Example
public class HelloWorld
{
public static void main(String[] args)
{
// Output "Hello, World!" to the console
System.out.println("Hello, World!");
}
}
Output
Data Types in Java
Java has a rich set of data types that can be categorized into two groups: primitive and non-primitive.
- Primitive Types: byte, short, int, long, float, double, char, boolean
- Non-Primitive Types: Strings, Arrays, Classes, Interfaces
Example: Using Different Data Types
Code Example
public class DataTypesExample {
public static void main(String[] args) {
int number = 10; // Integer
double decimal = 5.75; // Double
char letter = 'A'; // Character
boolean flag = true; // Boolean
System.out.println("Number: " + number);
System.out.println("Decimal: " + decimal);
System.out.println("Letter: " + letter);
System.out.println("Flag: " + flag);
}
}
Basic Syntax
Java programs consist of classes and methods. Every application must have at least one class with a main
method.
- Class Names: Class names should start with an uppercase letter.
- Method Names: Method names should start with a lowercase letter.
- Braces: Curly braces
{}
are used to define the body of methods and classes. - Semicolons: Each statement ends with a semicolon
;
.
Variables and Constants
Variables store data that can change during program execution. Constants are values that cannot be altered once defined.
Code Example
public class VariablesExample {
public static void main(String[] args) {
int age = 25; // Variable
final double PI = 3.14159; // Constant
System.out.println("Age: " + age);
System.out.println("Value of PI: " + PI);
}
}
Control Flow
Java supports various control flow statements such as loops and conditional statements to manage program execution.
Example: If-Else and Loops
Code Example
public class ControlFlowExample {
public static void main(String[] args) {
int number = 10;
// If-Else Statement
if (number % 2 == 0) {
System.out.println(number + " is even.");
}
else {
System.out.println(number + " is odd.");
}
// For Loop
System.out.println("Counting to 5:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Practice Exercises
- Write a program to check if a number is positive, negative, or zero.
- Create a program to display the multiplication table of a given number.
- Implement a program to calculate the sum of the first 10 natural numbers.
💡 Pro Tip
Always use meaningful names for variables and methods to make your code more readable.