Introduction to Java Syntax
• Java is a robust, strongly typed programming
language.
• Core components of Java syntax include:
• - Whitespace: Spaces, tabs, and newlines for
readability.
• - Identifiers: Names for variables, methods,
classes.
• - Keywords: Reserved words that cannot be
used as identifiers.
• Example:
Whitespace and Blocks
• Whitespace improves code readability but is
not required for functionality.
• Example:
• int a = 5; // Spaces make code easier to read.
• Blocks: Used to group statements logically.
• Example of a block:
• if (x > 0) {
• System.out.println("Positive number");
• }
Java Identifiers
• Rules for Java Identifiers:
• - Must start with a letter, underscore (_), or
dollar sign ($).
• - Cannot use Java keywords.
• - Case-sensitive: myVariable != MyVariable.
• Examples:
• Valid: myVar, _count, $price.
• Invalid: 2count, high-temp, class.
Java Keywords
• Java has 50 reserved keywords that serve
specific purposes.
• Examples include:
• - Data types: int, double, boolean.
• - Control flow: if, else, switch, for, while.
• - Access modifiers: public, private, protected.
• Note: Keywords such as goto and const are
reserved but not used.
Primitive Data Types
• Java provides eight primitive types:
• - Integers: byte, short, int, long (whole
numbers).
• - Floating-point: float, double (numbers with
decimals).
• - char: 16-bit Unicode characters.
• - boolean: Logical values true or false.
• Example:
• int age = 25;
Literals in Java
• Literals are fixed values assigned to variables:
• - Integer literals: 10, 0xA (hex), 012 (octal).
• - Floating-point literals: 3.14, 1.5e3 (scientific
notation).
• - Boolean literals: true, false.
• - Character literals: 'a', '\n' (escape sequence).
• - String literals: "Hello World".
• Example:
• String message = "Welcome to Java!";
Comments in Java
• Three types of comments in Java:
• - Single-line: // This is a comment.
• - Multi-line: /* This is a block comment. */
• - Documentation: /** Used to generate HTML
docs. */
• Example:
• /**
• * This is a documentation comment.
• * @param args Command-line arguments.
Variables and Scope
• Variables: Containers for storing data values.
• - Must be declared with a type: int x = 10;
• - Dynamic initialization: double c =
Math.sqrt(a*a + b*b);
• Scope: Determines visibility and lifetime of
variables.
• - Variables declared in a block {} are local to
that block.
• Example:
Type Conversion and Casting
• Automatic conversion (widening):
• - When types are compatible and target type
is larger.
• - Example: int x = 10; double y = x;
• Explicit casting (narrowing):
• - Converts a larger type to a smaller type
explicitly.
• - Example: double pi = 3.14; int truncatedPi =
(int) pi;