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

Hello, World!

Data Types in Java

Java has a rich set of data types that can be categorized into two groups: primitive and non-primitive.

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.

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

  1. Write a program to check if a number is positive, negative, or zero.
  2. Create a program to display the multiplication table of a given number.
  3. 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.