Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Fundamental Programming S...
  5. JAVA Basics

JAVA Basics

Java syntax refers to the set of rules that define how a Java program is written and interpreted.

Basic structure:

public class ClassName {
    public static void main(String[] args) {
        // Code goes here
    }
}
  • Java programs are class-based.
  • Every statement ends with a semicolon (;).
  • The file name must match the public class name (e.g., ClassName.java).

Comments in Java are non-executable statements used to explain and document the code. The Java compiler ignores them during compilation.

They help:

  • Make code easier to understand
  • Explain logic
  • Disable code temporarily
  • Document APIs (especially with JavaDoc)

Types of Java Comments:

  1. Single-line Comment: Starts with //
  2. Multi-line Comment: Starts with /* and ends with */
// Single-line comment

/* 
   Multi-line comment
*/
  • System.out.print() prints text without moving to a new line.
  • System.out.println() prints text and moves to the next line.
public class OutputExample {
    public static void main(String[] args) {
        System.out.print("Hello");
        System.out.print(" World");
        System.out.println("!");
        System.out.println("This is on a new line.");
    }
}

A variable in Java is a named storage location in memory that holds a value which can be changed during program execution.

Rules for Naming Variables:

  • Must begin with a letter (A–Z or a–z), _, or $.
  • Cannot begin with a digit.
  • Cannot use Java reserved keywords (int, class, etc.).
  • Use camelCase for naming (e.g., studentName).

Syntax:

dataType variableName = value;

Examples:

int age = 25;
double salary = 45000.50;
String name = "Alice";

A constant is a variable whose value cannot be changed after it’s assigned. Use the final keyword.

Syntax:

final dataType CONSTANT_NAME = value;

Example:

final double PI = 3.14159;

The main() method is the starting point of every Java application.

Syntax:

public static void main(String[] args) {
    // Statements
}
  • public: Accessible by JVM from anywhere.
  • static: Runs without creating an object.
  • void: Doesn’t return a value.
  • String[] args: Accepts command-line arguments.

Complete Example:

public class BasicsExample {
    public static void main(String[] args) {
        // Display a message
        System.out.println("Welcome to Java!");

        // Variables
        int age = 20;
        String name = "Bob";

        // Constant
        final double PI = 3.14;

        // Output
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Value of PI: " + PI);
    }
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *