0% found this document useful (0 votes)
3 views19 pages

Introduction To Java Programming

The document is a comprehensive beginner's guide to core Java programming concepts, covering topics such as variables, data types, naming conventions, mathematical operators, expression conversion, and output statements. It includes detailed explanations, examples, and best practices for each topic to aid beginners in understanding Java programming. The guide is structured into sections with a table of contents for easy navigation and reference.

Uploaded by

m.aarizrao.uk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Introduction To Java Programming

The document is a comprehensive beginner's guide to core Java programming concepts, covering topics such as variables, data types, naming conventions, mathematical operators, expression conversion, and output statements. It includes detailed explanations, examples, and best practices for each topic to aid beginners in understanding Java programming. The guide is structured into sections with a table of contents for easy navigation and reference.

Uploaded by

m.aarizrao.uk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

J

Introduction to

Java Programming
A Comprehensive Beginner's Guide to Core Java Concepts

Topics Covered: Variables & Data Types • Naming Conventions • Mathematical Operators
Expression Conversion • Operator Precedence • Output Statements

2025 Edition | Designed for Absolute Beginners

Introduction to Java Programming | Beginner's Edition | 2025


Introduction to Java Programming Beginner's Edition

Table of Contents

1. Variables – Definition and Data Types 3

1.1 What Is a Variable? 3

1.2 Primitive Data Types 3

1.3 Declaring and Initializing Variables 4

2. Naming Rules and Conventions 5

2.1 Legal Identifier Rules 5

2.2 CamelCase Convention 5

2.3 Best Practices 6

3. Mathematical Operators 7

3.1 The Five Core Operators 7

3.2 Integer Division vs. Floating-Point 8

3.3 The Modulo Operator 8

4. Expression Conversion 9

4.1 Translation Rules 9

4.2 Worked Examples 9

5. Expression Evaluation – Operator Precedence 11

5.1 Precedence Table 11

5.2 Step-by-Step Evaluation 11

6. Output Statements 13

6.1 [Link]() 13

6.2 [Link]() 14

6.3 Escape Sequences 15

6.4 String Concatenation in Output 15

7. Quick Reference Summary 16

© 2025 | All rights reserved Page 2


Introduction to Java Programming Beginner's Edition

1. Variables – Definition and Data Types

1.1 What Is a Variable?


A variable is a named storage location in a computer's memory that holds a value which can be used and
modified during the execution of a program. Think of it as a labelled box: the label is the variable's name,
and whatever is inside the box is its current value.

In Java, every variable must be declared with a specific data type before it can be used. The data type
tells the Java compiler how much memory to allocate and what kind of data the variable may store.

1.2 Primitive Data Types


Java provides eight built-in primitive data types. These are the most fundamental data types in the
language and are not objects. The four most commonly used by beginners are shown below:

Data Type Size Default Value Description & Example Value

int 32-bit 0 Whole numbers: -2,147,483,648 to 2,147,483,647

double 64-bit 0.0 Decimal numbers with double precision: 3.14159

char 16-bit \u0000 A single character enclosed in single quotes: 'A'

boolean 1-bit false Logical value — only true or false

long 64-bit 0L Very large whole numbers: up to 9.2 × 10¹■

float 32-bit 0.0f Decimal numbers with single precision: 3.14f

short 16-bit 0 Small whole numbers: -32,768 to 32,767

byte 8-bit 0 Tiny whole numbers: -128 to 127

1.3 Declaring and Initializing Variables


A variable declaration introduces the variable to the compiler. An initialization assigns it an initial value.
Both can be done in a single statement:

© 2025 | All rights reserved Page 3


Introduction to Java Programming Beginner's Edition

// ■■ Syntax ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■
dataType variableName; // Declaration only
dataType variableName = value; // Declaration + Initialization
// ■■ Integer examples ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■
int age; // Declared; not yet initialized
int score = 95; // Declared and initialized
int x = 10, y = 20, z = 30; // Multiple on one line
// ■■ Floating-point examples ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■
double price = 19.99;
double pi = 3.14159265358979;
float gpa = 3.75f; // Note the 'f' suffix for float
// ■■ Character and Boolean examples ■■■■■■■■■■■■■■■■■■■■■■■■■■

char grade = 'A'; // Single quotes for char
boolean isPassed = true;
// ■■ String (reference type – not primitive) ■■■■■■■■■■■■■■■■■■
String studentName = "Alice Johnson"; // Double quotes for String

Code Snippet 1.1 – Variable declarations and initializations

■ Note: Constants with final

Use the final keyword to declare a constant — a variable whose value cannot be changed after
it has been assigned. Example: final double TAX_RATE = 0.085; By convention, constant
names are written in ALL_CAPS_WITH_UNDERSCORES.

© 2025 | All rights reserved Page 4


Introduction to Java Programming Beginner's Edition

2. Naming Rules and Conventions

2.1 Legal Identifier Rules


An identifier is any name you give to a variable, method, class, or other element in your program. Java
enforces the following hard rules — breaking them causes a compile-time error:

• Must begin with a letter (A–Z or a–z), an underscore ( _ ), or a dollar sign ( $ ).


• After the first character, digits (0–9) are also permitted.
• Cannot contain spaces or special characters such as @, #, !, %, etc.
• Cannot be a Java reserved keyword (e.g., int, class, if, while, return, void).
• Are case-sensitive — myScore, MyScore, and MYSCORE are three different identifiers.
• Have no enforced maximum length (practical limit: keep them readable).

// ■ Legal identifiers
int studentAge;
double _salary;
String $currency;
int totalScore2024;
// ■ Illegal identifiers (compile-time errors)
// int 2ndPlace; → Cannot start with a digit
// double my salary; → Spaces are not allowed
// int class; → 'class' is a reserved keyword
// float profit@margin; → '@' is not permitted

Code Snippet 2.1 – Legal vs. illegal identifiers

2.2 CamelCase Convention


While the legal rules define what Java allows, naming conventions define what professional developers
actually use. Java follows the camelCase convention for variable and method names:

Convention Used For Rule Example

lowerCamelCase Variables & Methods First word lowercase; each subsequent


totalScore,
word capitalized
calculateArea()

UpperCamelCase
(PascalCase) Classes & Interfaces Every word starts with a capital letter BankAccount, StudentRecord

ALL_CAPS Constants (final) All uppercase; words separated by underscores


MAX_SIZE, PI_VALUE

lowercase Packages All lowercase; use dots for hierarchy [Link].cs101

© 2025 | All rights reserved Page 5


Introduction to Java Programming Beginner's Edition

2.3 Best Practices


Following consistent naming conventions makes your code dramatically easier to read, debug, and
maintain — both for yourself and for others:

• Be descriptive, not cryptic. Write studentAge instead of sa, or calculateTotalPrice instead of ctp.
• Avoid single-letter names except in short loops (i, j, k are acceptable loop counters).
• Use nouns for variables (userName, accountBalance) and verb phrases for methods
(printReport(), getUserInput()).
• Boolean variables should read as true/false questions: isLoggedIn, hasPermission, isPassed.
• Be consistent throughout your entire codebase — mixing styles creates confusion.

// ■■ Applying conventions in practice ■■■■■■■■■■■■■■■■■■■■■■■■


// Variables (lowerCamelCase)
int studentAge = 20;
double accountBalance = 1500.75;
String firstName = "Carlos";
boolean isEnrolled = true;
// Constants (ALL_CAPS)
final int MAX_STUDENTS = 30;
final double TAX_RATE = 0.085;
final String SCHOOL_NAME = "Java Academy";
// Class name (UpperCamelCase) — shown for reference
// class StudentRecord { ... }

Code Snippet 2.2 – Naming conventions applied consistently

■ Why Conventions Matter

Java is case-sensitive, so studentAge and StudentAge are different variables. Following


conventions prevents subtle bugs and ensures that anyone reading your code immediately
understands whether an identifier is a variable, a constant, or a class.

© 2025 | All rights reserved Page 6


Introduction to Java Programming Beginner's Edition

3. Mathematical Operators

3.1 The Five Core Operators


Java supports all standard arithmetic operations through five fundamental operators. These operators
work on numeric data types (int, long, float, double, etc.).

Operator Symbol Operation Example Expression Result

Addition + Adds two values 7+3 10

Subtraction - Subtracts right from left 10 - 4 6

Multiplication * Multiplies two values 6*5 30

Division / Divides left by right 15 / 4 3 (int)

Modulo % Remainder after integer division15 % 4 3

int a = 15;
int b = 4;
int sum = a + b; // 19
int difference = a - b; // 11
int product = a * b; // 60
int quotient = a / b; // 3 ← integer division truncates
int remainder = a % b; // 3 ← 15 = (4 × 3) + 3
[Link]("Sum : " + sum);
[Link]("Difference : " + difference);
[Link]("Product : " + product);
[Link]("Quotient : " + quotient);
[Link]("Remainder : " + remainder);

Code Snippet 3.1 – All five arithmetic operators in action

3.2 Integer Division vs. Floating-Point Division


When both operands are integers, Java performs integer division — the fractional part is discarded
(truncated, not rounded). To obtain a decimal result, at least one operand must be a double or float:

© 2025 | All rights reserved Page 7


Introduction to Java Programming Beginner's Edition

// Integer division — fractional part is DROPPED


int result1 = 7 / 2; // result1 = 3 (not 3.5)
// Floating-point division — decimal result preserved
double result2 = 7.0 / 2; // result2 = 3.5
double result3 = 7 / 2.0; // result3 = 3.5
double result4 = (double) 7 / 2; // result4 = 3.5 ← casting
// Casting an int variable to double before dividing
int x = 7, y = 2;
double result5 = (double) x / y; // result5 = 3.5

Code Snippet 3.2 – Integer vs. floating-point division

3.3 The Modulo Operator in Depth


The modulo operator ( % ) returns the remainder of a division. It is one of the most useful operators in
programming, appearing in tasks such as checking whether a number is even or odd, cycling through
arrays, or determining if a value is divisible by another:

// ■■ Basic modulo ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


■■■■■
[Link](10 % 3); // 1 → 10 = (3×3) + 1
[Link](20 % 5); // 0 → 20 = (5×4) + 0 (divisible)
[Link](7 % 2); // 1 → odd number check
// ■■ Practical: even/odd check ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■
int number = 42;
if (number % 2 == 0) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}
// Output: 42 is even.

Code Snippet 3.3 – Modulo operator uses

■■ Compound Assignment Operators

Java provides shorthand operators that combine arithmetic with assignment: x += 5 is


equivalent to x = x + 5. Similarly, -=, *=, /=, and %= are available. The increment (++) and
decrement (--) operators add or subtract 1: x++ is equivalent to x = x + 1.

© 2025 | All rights reserved Page 8


Introduction to Java Programming Beginner's Edition

4. Expression Conversion
Mathematical notation uses symbols and formatting conventions that differ from what Java (or any
programming language) accepts. This section teaches you how to systematically translate standard
algebraic expressions into valid Java code.

4.1 Translation Rules


• Multiplication must be explicit. In algebra, writing 2x means 2 × x. In Java you must write: 2 * x
• Division uses the / operator — not the fraction bar (—) or ÷ symbol. Wrap
numerators/denominators in parentheses as needed.
• Exponentiation (powers) is not a built-in operator. Use [Link](base, exp).
• Square roots use [Link](value).
• Absolute value uses [Link](value).
• Parentheses enforce grouping — use them liberally to make precedence explicit.
• Spaces around operators are optional but strongly recommended for readability.

4.2 Worked Examples

Example 1 – Quadratic Formula Numerator


Algebraic: result = (a + b) ÷ 2c

// Math: result = (a + b) / (2 × c)
double a = 6.0, b = 4.0, c = 2.0;
double result = (a + b) / (2 * c); // result = 10.0 / 4.0 = 2.5

Code Snippet 4.1 – Translating a simple division expression

Example 2 – Area of a Triangle


Algebraic: Area = (base × height) ÷ 2

double base = 10.0;


double height = 5.0;
double area = (base * height) / 2.0; // area = 25.0

Code Snippet 4.2 – Area of a triangle

Example 3 – Hypotenuse (Pythagorean Theorem)


Algebraic: c = √(a² + b²)

© 2025 | All rights reserved Page 9


Introduction to Java Programming Beginner's Edition

double a = 3.0;
double b = 4.0;
// c = sqrt(a^2 + b^2)
double c = [Link]([Link](a, 2) + [Link](b, 2));
// c = [Link](9.0 + 16.0) = [Link](25.0) = 5.0
[Link]("Hypotenuse = " + c); // Hypotenuse = 5.0

Code Snippet 4.3 – Pythagorean theorem using [Link] and [Link]

Example 4 – Celsius to Fahrenheit Conversion


Algebraic: F = (9 ÷ 5) × C + 32

double celsius = 100.0;


double fahrenheit = (9.0 / 5.0) * celsius + 32.0;
// fahrenheit = 1.8 * 100.0 + 32.0 = 212.0
[Link](celsius + "°C = " + fahrenheit + "°F");
// Output: 100.0°C = 212.0°F

Code Snippet 4.4 – Temperature conversion

Example 5 – Compound Expression


Algebraic: y = 3x² + 2x − 5 where x = 4

double x = 4.0;
// y = 3(x^2) + 2x - 5
double y = 3 * [Link](x, 2) + 2 * x - 5;
// y = 3 * 16.0 + 8.0 - 5.0
// y = 48.0 + 8.0 - 5.0
// y = 51.0
[Link]("y = " + y); // y = 51.0

Code Snippet 4.5 – Polynomial expression

■ Math Class Quick Reference

[Link](x, n) → x raised to the power n | [Link](x) → square root of x | [Link](x) →


absolute value of x | [Link] → 3.14159… | [Link](x) → rounds to nearest integer |
[Link](a,b) / [Link](a,b) → larger/smaller of two values

© 2025 | All rights reserved Page 10


Introduction to Java Programming Beginner's Edition

5. Expression Evaluation – Operator Precedence


When Java evaluates an expression containing multiple operators, it does not simply process them from
left to right. Instead, it follows a strict set of precedence rules — similar to the PEMDAS/BODMAS rules
you learned in mathematics — to determine the order in which operations are performed.

5.1 Operator Precedence Table


The table below lists Java's arithmetic operators from highest precedence (evaluated first) to lowest
precedence (evaluated last). Operators at the same level are evaluated left to right (left associativity).

Precedence Operator(s) Description Associativity

1 (Highest) () Parentheses — grouping Inside-out

2 [Link]() Exponentiation (via Math class) Left → Right

3 *, /, % Multiplication, Division, Modulo Left → Right

4 (Lowest) +, - Addition, Subtraction Left → Right

■ Golden Rule

When in doubt about precedence, use parentheses. Parentheses always take the highest
priority and make your intent explicit to both the compiler and the human reader.

5.2 Step-by-Step Evaluation Examples

Example A – Mixed Arithmetic (No Parentheses)


Expression: result = 10 + 3 * 2 - 8 / 4

© 2025 | All rights reserved Page 11


Introduction to Java Programming Beginner's Edition

int result = 10 + 3 * 2 - 8 / 4;
// Step 1 — Multiplication: 3 * 2 = 6
// Becomes: 10 + 6 - 8 / 4
// Step 2 — Division: 8 / 4 = 2
// Becomes: 10 + 6 - 2
// Step 3 — Addition: 10 + 6 = 16
// Becomes: 16 - 2
// Step 4 — Subtraction: 16 - 2 = 14
// result = 14
[Link](result); // 14

Code Snippet 5.1 – Evaluating operator precedence step by step

Example B – Parentheses Override Precedence


Expression: result = (10 + 3) * (2 - 8) / 4

int result = (10 + 3) * (2 - 8) / 4;


// Step 1 — Left parentheses: 10 + 3 = 13
// Becomes: 13 * (2 - 8) / 4
// Step 2 — Right parentheses: 2 - 8 = -6
// Becomes: 13 * (-6) / 4
// Step 3 — Multiplication (left to right): 13 * (-6) = -78
// Becomes: -78 / 4
// Step 4 — Integer Division: -78 / 4 = -19 (truncated)
// result = -19
[Link](result); // -19

Code Snippet 5.2 – Parentheses changing evaluation order

Example C – Modulo Within a Larger Expression


Expression: result = 5 + 17 % 3 * 2

int result = 5 + 17 % 3 * 2;
// Step 1 — Modulo (left to right): 17 % 3 = 2
// Becomes: 5 + 2 * 2
// Step 2 — Multiplication: 2 * 2 = 4
// Becomes: 5 + 4
// Step 3 — Addition: 5 + 4 = 9
// result = 9
[Link](result); // 9

© 2025 | All rights reserved Page 12


Introduction to Java Programming Beginner's Edition

Code Snippet 5.3 – Modulo within a compound expression

Example D – Verifying with Parentheses


Always use parentheses to verify your understanding. The two expressions below produce identical
results, but the second is self-documenting:

int a = 2 + 3 * 4 - 6 / 2; // Relies on precedence rules


int b = 2 + (3 * 4) - (6 / 2); // Explicit — preferred in productio
n code
// Both evaluate to: 2 + 12 - 3 = 11
[Link](a); // 11
[Link](b); // 11

Code Snippet 5.4 – Using parentheses for clarity

© 2025 | All rights reserved Page 13


Introduction to Java Programming Beginner's Edition

6. Output Statements
Displaying information to the user is one of the most fundamental tasks in any program. Java provides the
[Link] object to write output to the standard output stream — typically the terminal or console
window. The two most commonly used methods are println() and print().

6.1 [Link]()
The println() method (short for print line) prints its argument to the console and then automatically moves
the cursor to the next line. Each call to println() produces output on its own line.

// ■■ Printing string literals ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


■■
[Link]("Hello, World!");
[Link]("Welcome to Java Programming.");
// ■■ Printing numeric values ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■
[Link](42);
[Link](3.14159);
// ■■ Printing variables ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■
int age = 21;
double gpa = 3.85;
String name = "Diana";
[Link](age); // 21
[Link](gpa); // 3.85
[Link](name); // Diana
// ■■ Printing a blank line ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■
[Link](); // Outputs an empty line

Code Snippet 6.1 – [Link]() usage

Output produced by the above snippet:

© 2025 | All rights reserved Page 14


Introduction to Java Programming Beginner's Edition

Hello, World!
Welcome to Java Programming.
42
3.14159
21
3.85
Diana

Console Output 6.1

6.2 [Link]()
The print() method works identically to println() except that it does not append a newline character at the
end. Subsequent output continues on the same line. This is useful for building output piece by piece.

[Link]("First ");
[Link]("Second ");
[Link]("Third");
[Link](); // Move to the next line
[Link]("Done.");
// Output:
// First Second Third
// Done.

Code Snippet 6.2 – print() vs. println()

Method Newline at End? Typical Use Case

[Link](text) Yes Most general output; each item on its own line

[Link](text) No Building output across multiple statements

[Link]() Yes Printing a blank line (no argument)

6.3 Escape Sequences


Escape sequences allow you to embed special characters inside a string literal. They begin with a
backslash ( \ ) followed by a specific character:

Escape Sequence
Meaning Example Output

\n New line "Line1\nLine2" Line1 (then newline) Line2

\t Tab (8 spaces) "Name:\tAlice" Name: Alice

© 2025 | All rights reserved Page 15


Introduction to Java Programming Beginner's Edition

\" Double quote "He said \"Hi\"" He said "Hi"

\' Single quote '\'' ' character

\\ Backslash "C:\\Users\\me" C:\Users\me

\r Carriage return "text\rstart" Overwrites from start

// ■■ Escape sequences in action ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■



[Link]("Student\tGrade\tGPA");
[Link]("Alice\t\tA\t\t3.95");
[Link]("Bob\t\tB+\t\t3.40");
// Output:
// Student Grade GPA
// Alice A 3.95
// Bob B+ 3.40

Code Snippet 6.3 – Using \t for tabular output

6.4 String Concatenation in Output


The + operator, when used with strings, acts as a concatenation operator — it joins strings and values
together into a single string for output. Java automatically converts numeric values to their string
representation when they appear alongside a String in a + expression:

String name = "Maria";


int age = 19;
double tuition = 7500.50;
// Concatenating strings and variables
[Link]("Student : " + name);
[Link]("Age : " + age);
[Link]("Tuition : $" + tuition);
// Concatenation with expressions
int x = 5, y = 3;
[Link]("Sum of " + x + " and " + y + " is " + (x + y));
// ■■ Without parentheses: 5 + 3 would concatenate as "53" in some co
ntexts
// Output:
// Student : Maria
// Age : 19
// Tuition : $7500.5
// Sum of 5 and 3 is 8

© 2025 | All rights reserved Page 16


Introduction to Java Programming Beginner's Edition

Code Snippet 6.4 – String concatenation in println()

■■ Concatenation Pitfall

Be careful with the + operator: [Link]("Result: " + 2 + 3) prints Result: 23 (string


concatenation), NOT Result: 5. To force arithmetic, wrap the expression in parentheses:
[Link]("Result: " + (2 + 3)) prints Result: 5.

© 2025 | All rights reserved Page 17


Introduction to Java Programming Beginner's Edition

7. Quick Reference Summary


The table below consolidates the essential syntax covered in this guide into a single at-a-glance reference
card.

Topic Syntax / Rule Example

Variable Declaration dataType name = value; int score = 95;

Integer type int name = value; int count = 0;

Decimal type double name = value; double pi = 3.14;

Character type char name = 'X'; char grade = 'A';

Boolean type boolean name = true/false; boolean done = false;

String type String name = "text"; String s = "Hi";

Constant final TYPE NAME = value; final int MAX = 100;

Legal identifier Letter / _ / $ first, then digits OK totalScore2024

lowerCamelCase First word lower; rest capitalized studentAge

UpperCamelCase Every word capitalized BankAccount

ALL_CAPS constant All upper, underscores between words


TAX_RATE

Addition a+b 5+3 =8

Subtraction a-b 10 - 4 = 6

Multiplication a*b 6 * 7 = 42

Division a/b 15 / 4 = 3 (int)

Modulo a%b 15 % 4 = 3

Exponentiation [Link](base, exp) [Link](2,3)=8.0

Square root [Link](value) [Link](16)=4.0

Precedence order () → */% → +- (2+3)*4 = 20

Print with newline [Link](value); println("Hi")

Print without newline [Link](value); print("A")

New line in string \n escape sequence "A\nB" = 2 lines

Tab in string \t escape sequence "A\tB"

© 2025 | All rights reserved Page 18


Introduction to Java Programming Beginner's Edition

Concatenation str + var or str + (expr) "x=" + (a+b)

■ Next Steps

Now that you have mastered variables, naming conventions, arithmetic operators, expression
evaluation, and output statements, you are ready to explore: (1) Taking user input with the
Scanner class, (2) Conditional statements — if, else if, else, and switch, (3) Loops — for, while,
and do-while, and (4) Methods (functions) for code reuse. Keep practising by writing small
programs that combine all the concepts from this guide.

© 2025 | All rights reserved Page 19

You might also like