CodeWithAbdessamad

Syntax And Structure

Java Basics: Syntax and Structure

Variables

In Java, variables act as named containers for storing data values that can change during program execution. They are the foundational building blocks for any Java application, allowing you to manipulate and track information dynamically. Before using a variable, you must declare it by specifying its data type and name.

Declaring Variables

To declare a variable, use the following syntax:

<code class="language-java">dataType variableName;</code>

For example:

<code class="language-java">int age;        // Integer variable
<p>double price;   // Double-precision floating-point variable</p>
<p>boolean isActive; // Boolean variable</p>
<p>String username; // String reference variable</code>

Variable Naming Rules

Variables follow specific naming conventions to ensure clarity and prevent errors:

  • Must start with a letter, underscore (_), or dollar sign ($)
  • Subsequent characters can be letters, digits, underscores, or dollar signs
  • Cannot be a reserved keyword (e.g., int, if, while)
  • Case-sensitive (e.g., userAgeUserAge)
  • Example: userAge = 25 is valid, but 2userAge is invalid

Variable Initialization

You can initialize variables at declaration time:

<code class="language-java">int count = 0;        // Initialized to 0
<p>double pi = 3.14159;  // Initialized to 3.14159</p>
<p>String greeting = "Hello"; // Initialized to "Hello"</code>

Practical Example: Calculate a user’s age from their birth year

<code class="language-java">int birthYear = 1990;
<p>int currentYear = 2023;</p>
<p>int age = currentYear - birthYear;</p>
<p>System.out.println("Age: " + age); // Output: Age: 33</code>

Data Types

Java defines two primary categories of data types: primitive types (built-in values) and reference types (objects).

Primitive Data Types

Primitive types store raw values directly in memory. They include:

Type Size (Bytes) Range/Description Example Usage
int 4 -2,147,483,648 to 2,147,483,647 int age = 30;
double 8 ~±1.7e308 (floating-point) double pi = 3.14159;
boolean 1 true or false boolean isStudent = true;
char 2 Unicode character (e.g., 'A') char letter = 'A';
float 4 ~±3.4e38 (floating-point) float price = 19.99f;
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long population = 1000000000L;

Key Notes:

  • Use L suffix for long (e.g., 1000000000L)
  • Use f suffix for float (e.g., 19.99f)
  • double offers higher precision than float for fractional values

Reference Data Types

Reference types store memory addresses pointing to objects. All classes and interfaces are reference types:

<code class="language-java">String name = "Alice"; // String is a reference type
<p>Person user = new Person(); // Person is a reference type</code>

  • String is a special reference type for text
  • Objects are created via new keyword
  • Example: name holds a reference to a String object

Practical Example: Using double for precise calculations

<code class="language-java">double radius = 3.0;
<p>double area = 3.14159 <em> radius </em> radius;</p>
<p>System.out.println("Area: " + area); // Output: Area: 28.27433</code>

Operators

Operators manipulate variables and values to perform computations. Java supports multiple operator categories:

Arithmetic Operators

Perform basic math operations:

<code class="language-java">int a = 10;
<p>int b = 3;</p>
<p>int sum = a + b;   // 13</p>
<p>int diff = a - b;  // 7</p>
<p>int product = a * b; // 30</p>
<p>int quotient = a / b; // 3 (integer division)</p>
<p>int remainder = a % b; // 1</code>

Assignment Operators

Assign values to variables:

<code class="language-java">int count = 0;
<p>count += 1; // Equivalent to count = count + 1</p>
<p>count <em>= 2; // Equivalent to count = count </em> 2</code>

Comparison Operators

Compare values and return boolean results:

<code class="language-java">int x = 5;
<p>boolean isEven = (x % 2 == 0); // true</p>
<p>boolean greaterThanZero = (x > 0); // true</p>
<p>boolean lessThanTen = (x < 10); // true</code>

Logical Operators

Combine boolean expressions:

<code class="language-java">boolean hasAccess = true;
<p>boolean isAuthorized = hasAccess && (x > 0); // true</p>
<p>boolean isUserValid = hasAccess || (x < 0); // true</p>
<p>boolean isNotActive = !(x > 0); // false</code>

Ternary Operator

Conditional expression for single-line conditionals:

<code class="language-java">int result = (x > 0) ? x : -x; // Returns x if positive, else -x</code>

Practical Example: Determine if a number is even using modulus

<code class="language-java">int number = 12;
<p>boolean isEven = (number % 2 == 0);</p>
<p>System.out.println("Is " + number + " even? " + isEven); // Output: Is 12 even? true</code>

Operators are the building blocks of logic. 🔢