Java Basics
1. Java Syntax
Java syntax is the set of rules that defines how a Java program is written and interpreted. It is similar to the grammar rules in a spoken language. For example, every Java statement must end with a semicolon (;). This is akin to ending a sentence with a period in English.
Example:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2. Variables and Data Types
Variables are containers for storing data values. In Java, every variable must have a specific data type, which defines the type of data the variable can hold. Java has primitive data types like int
for integers, double
for floating-point numbers, and boolean
for true/false values.
Example:
int age = 25; double salary = 50000.50; boolean isEmployed = true;
3. Operators
Operators are symbols that perform operations on variables and values. Java supports arithmetic operators like +, -, *, /, and % for addition, subtraction, multiplication, division, and modulus, respectively. Logical operators like && (logical AND) and || (logical OR) are used to combine conditions.
Example:
int a = 10; int b = 5; int sum = a + b; // sum is 15 boolean isValid = (a > b) && (b != 0); // isValid is true
4. Control Flow Statements
Control flow statements determine the order in which statements are executed in a program. Java provides conditional statements like if
, else
, and switch
to make decisions, and loop statements like for
, while
, and do-while
to repeat actions.
Example:
int score = 85; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); } else { System.out.println("Grade: C"); }
5. Methods
Methods are blocks of code that perform a specific task. They can be called multiple times within a program, making the code reusable. Methods can take parameters (input values) and return a result. The main
method is the entry point of a Java program.
Example:
public static int add(int x, int y) { return x + y; } public static void main(String[] args) { int result = add(3, 4); // result is 7 System.out.println("The sum is: " + result); }
6. Object-Oriented Programming (OOP)
Java is an object-oriented programming language, which means it is based on the concept of "objects," which can contain data and code to manipulate that data. OOP principles include encapsulation, inheritance, and polymorphism. Classes are the blueprints for creating objects.
Example:
class Car { String model; int year; public Car(String model, int year) { this.model = model; this.year = year; } public void start() { System.out.println("The " + model + " is starting."); } } public class Main { public static void main(String[] args) { Car myCar = new Car("Toyota", 2020); myCar.start(); // Output: The Toyota is starting. } }