TutorialsJavaJava Syntax
Share:

Java Syntax

beginner

Part of Java Basics

Theory

Java syntax is clean and consistent. Every Java program is built from classes, and execution starts in the main method.

Class Structure and Main Method

public class ClassName {
    public static void main(String[] args) {
        // Program starts here
    }
}
  • public — accessible from anywhere
  • class — keyword to define a class
  • static — belongs to the class, not an instance
  • void — no return value
  • String[] args — command-line arguments

Variables and Data Types

Java is statically typed — every variable must have a declared type:

| Type | Size | Example | |------|------|---------| | int | 4 bytes | int age = 25; | | double | 8 bytes | double pi = 3.14; | | char | 2 bytes | char grade = 'A'; | | boolean | 1 bit | boolean flag = true; | | String | object | String name = "Alice"; |

int count = 10;
double price = 19.99;
boolean isActive = true;
String message = "Hello";

Type Casting

Widening (automatic): int → double, float → double Narrowing (explicit): (int) 3.14, (float) 10.5

Operators

  • Arithmetic: +, -, *, /, %
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !
  • Assignment: =, +=, -=, *=, /=

Scanner Input

Reading User Input with Scanner
java

Practical Examples

Example: Calculator with Operators
java

Exercises

Temperature Converter

easy

Write a Java program that reads a temperature in Celsius using Scanner, converts it to Fahrenheit using F = C * 9/5 + 32, and prints both values.

Expected Output:

Enter Celsius: 25\n25.0°C = 77.0°F

Mini Quiz

Mini Quiz