java chapter 2

🔹 1. Building Blocks of Java Program

Every Java program is made up of:

  • Keywords – Reserved words with special meaning (e.g., int, class, if, for).
  • Identifiers – Names for variables, methods, classes, etc.
    ✅ Must start with a letter, _, or $; can’t use spaces or keywords.
  • Literals – Constant values (like 10, 'A', "Hello").
  • Operators – Symbols to perform operations (like +, -, ==).
  • Separators – (), {}, [], ;, ,, . etc.

🔹 2. Data Types in Java

Java is a strongly typed language — every variable must have a declared type.

A. Primitive Data Types

TypeSizeExampleDescription
byte1 byte127small integers
short2 bytes32000medium integers
int4 bytes100000default integer type
long8 bytes10000000000Llarge integers
float4 bytes10.5fdecimal numbers (less precision)
double8 bytes12.345decimal numbers (more precision)
char2 bytes‘A’single character
boolean1 bittrue / falselogical value

B. Non-Primitive Data Types

  • String, Arrays, Classes, Interfaces, Objects etc.

🔹 3. Variables

variable is a name that refers to a memory location storing data.

Syntax:

int age = 18;

Types of Variables:

  1. Local Variable – Declared inside a method.
  2. Instance Variable – Declared inside a class but outside any method.
  3. Static Variable – Declared using static keyword; shared by all objects.

Rules for Naming:

  • Must start with letter, $, or _.
  • No spaces or keywords.
  • Case-sensitive (Age ≠ age).

🔹 4. Constants

  • Declared using the final keyword.
    Example:final double PI = 3.14159;
  • Once assigned, their value cannot be changed.

🔹 5. Type Casting

Changing one data type into another.

Types:

  1. Implicit (Automatic) – Smaller → larger type
    Example:int a = 10; double b = a; // int to double
  2. Explicit (Manual) – Larger → smaller type
    Example:double x = 9.8; int y = (int) x; // double to int

🔹 6. Operators in Java

A. Arithmetic Operators

+-*/%

B. Relational Operators

==!=><>=<=

C. Logical Operators

&&||!

D. Assignment Operators

=+=-=*=/=%=

E. Unary Operators

++ (increment), -- (decrement)

F. Conditional (Ternary) Operator

condition ? value_if_true : value_if_false

Example:

int max = (a > b) ? a : b;

G. Bitwise Operators

Operate on bits: &|^~<<>>>>>


🔹 7. Expressions and Type Promotion

  • If different data types are used in an expression, Java promotes smaller types to a larger type automatically.
    Example:
int a = 5;
float b = 6.2f;
float c = a + b;   // a converted to float

🔹 8. Comments in Java

Used to improve readability.

// Single-line comment
/* Multi-line
   comment */

Leave a Comment

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