Acadezi branded
Acadezi logo

☕ Object Oriented Programming

Unit 2: Java Program Structure – complete with problems & solutions

📄 SLIDE 1 – Anatomy of a Java Program
College of IT – AI

🧩 Java Program Structure

  • A program is made up of one or more classes.
  • A class contains one or more methods.
  • A method contains program statements.
  • A Java application always contains a method called main.

يتكون البرنامج من كلاس واحد أو أكثر. الكلاس يحتوي على دوال (methods). الدوال تحتوي على أوامر (statements). أي تطبيق جافا يحتوي على دالة اسمها main.

📄 SLIDE 2 – Class Name

📛 Class Name

Every Java program must have at least one class. Each class has a name. By convention, class names start with an uppercase letter.

// This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

كل برنامج جافا يحتوي كلاس واحد على الأقل. اسم الكلاس يبدأ بحرف كبير حسب convention. مثال: Welcome.

📄 SLIDE 3 – Main Method

▶️ main Method

In order to run a class, the class must contain one method named main. The program begins execution from the main method.

public static void main(String[] args) { System.out.println("Welcome to Java!"); }

لكي يتم تشغيل الكلاس، يجب أن يحتوي على دالة اسمها main. البرنامج يبدأ التنفيذ من أول سطر داخل main.

📄 SLIDE 4 – Filename for a public Class

📁 Filename rule

A public class must be placed in a file that has a name of the form ClassName.java. So class Welcome is stored in file Welcome.java.

الكلاس المعرّف بـ public يجب أن يكون في ملف بنفس اسم الكلاس + امتداد .java. مثلاً Welcome.java.

📄 SLIDE 5 – Naming Conventions

📐 Naming Conventions

  • Class names: Capitalize first letter of each word. Example: ComputeArea.
  • Variable and method names: Use lowercase for first word, then capitalize subsequent words (camelCase). Example: radius, computeArea.
  • Constants: All uppercase, words separated by underscore. Example: PI, MAX_VALUE.

أسماء الكلاسات: تبدأ بحرف كبير لكل كلمة. المتغيرات والدوال: camelCase (أول كلمة صغيرة). الثوابت: كلها كبيرة مع underscores.

📄 SLIDE 6 – Statement & Terminator

📝 Statement

A statement represents an action or a sequence of actions. Every statement in Java ends with a semicolon (;).

System.out.println("Welcome to Java!");

الأمر (statement) هو إجراء أو مجموعة إجراءات. كل أمر في جافا ينتهي بفاصلة منقوطة ;

📄 SLIDE 7 – Reserved words (common)

🔑 Common Reserved Words (Keywords)

Reserved words have a specific meaning to the compiler and cannot be used for other purposes.

abstract boolean break byte case catch char class continue default do double else enum extends final finally float for if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient try void volatile while

... and many more (over 50 total).

الكلمات المحجوزة (keywords) لها معنى محدد للمترجم ولا يمكن استخدامها كأسماء متغيرات أو كلاسات. هذه أشهرها.

📄 SLIDE 8 – Comments

💬 Comments

Comments are inline documentation. Compiler ignores them. Three forms:

// this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */

التعليقات تستخدم لتوثيق الكود. المترجم يتجاهلها. ثلاثة أنواع: // سطر واحد، /* */ عدة أسطر، /** */ javadoc.

📄 SLIDE 9 – Identifiers

🏷️ Identifiers

An identifier is any name you give to program elements.

Rules:

  • Must begin with a letter, underscore (_), or dollar sign ($).
  • Cannot start with a digit.
  • After first character, digits (0–9) can be used.
  • Case-sensitive → Age and age are different.
  • Cannot be a Java keyword.
  • No spaces or special characters like @, #, %.

Valid identifiers: hello, _Name, valid_$1, $23

Invalid: 123Here, exam-, class, student ID, not@valid

المعرف (identifier) هو اسم تختاره لعناصر البرنامج. يبدأ بحرف أو _ أو $، لا يبدأ برقم، حساس لحالة الأحرف، لا يمكن أن يكون كلمة محجوزة.

📄 SLIDE 10 – Variables

📦 Variables

A variable must be declared by specifying its name and type.

int total; int count, temp, result; // multiple in one line

Always choose meaningful and descriptive variable names.

المتغير يُصرّح بتحديد اسمه ونوعه. يمكن التصريح عن عدة متغيرات من نفس النوع في سطر واحد.

📄 SLIDE 11 – Constants

🔒 Constants (final)

A constant holds the same value during its entire existence. Declared using final keyword. By convention, constants are ALL_UPPER_CASE.

final int STUDENT_COUNT = 10; final double CAL_SALES_TAX = 0.725;

الثابت (constant) يحتفظ بنفس القيمة طوال عمره. يُصرّح باستخدام final. التسمية كلها uppercase مع underscores.

📄 SLIDE 12 – Assignment

✍️ Assignment Statement

Changes the value of a variable using the = operator.

total = 55; // overwrites previous value

You can only assign a value of the same declared type.

جملة الإسناد تغير قيمة المتغير باستخدام =. يجب أن تكون القيمة من نفس النوع المصرّح به.

📄 SLIDE 13 – print & println

🖨️ Output Methods

System.out.println() prints and moves to next line. System.out.print() prints without advancing line.

System.out.print("Three... "); System.out.print("Two... "); System.out.println("Liftoff!"); System.out.println("Houston, we have a problem.");

Output: Three... Two... One... Zero... Liftoff!
Houston, we have a problem.

println تطبع وتنتقل لسطر جديد. print تطبع وتبقى في نفس السطر.

📄 SLIDE 14 – Escape sequences

🔣 Escape Sequences

Start with backslash \ to represent special characters.

EscapeMeaning
\nnewline
\ttab
\"double quote
\\backslash

تسلسلات الهروب تبدأ بـ \ وتمثل محارف خاصة: \n سطر جديد، \t tab، إلخ.

📄 SLIDE 15 – The + Operator

➕ Concatenation vs Addition

+ can be used for string concatenation or numeric addition. Use parentheses for addition inside strings.

System.out.println("Hello " + "World"); // concatenation System.out.println("The value is: " + 5); System.out.println("Sum = " + (5 + 3)); // addition first

+ يستخدم للجمع العددي أو لضم النصوص. إذا أردت الجمع مع نص، استخدم أقواس.

📄 SLIDE 16 – Java Data Types

📊 Two Groups

  • Primitive data types (8 types)
  • Reference data types (objects, arrays, etc.)

تنقسم أنواع البيانات في جافا إلى: أنواع بدائية (primitive) و 8 أنواع، وأنواع مرجعية (reference) مثل الكائنات.

📄 SLIDE 17 – Primitive Data Types

🔢 8 Primitive Types

TypeSizeExample
byte1 byte127
short2 bytes32767
int4 bytes2147483647
long8 bytes9223372036854775807L
float4 bytes3.14f
double8 bytes3.14159
char2 bytes'A'
boolean1 bit (JVM dependent)true/false

الأنواع البدائية الثمانية: byte, short, int, long (للأعداد الصحيحة)، float, double (للأعداد العشرية)، char (حرف)، boolean (صحيح/خطأ).

📄 SLIDE 18 – Integers & Floating Point

📌 Integer & Floating Details

Integer types: byte, short, int, long – hold whole numbers only.

Floating-point: float (7 decimal digits), double (15 decimal digits).

Floating-point can store integer values, but integer types cannot store floating-point values.

الأنواع الصحيحة تخزن أعداداً بدون كسور. الأنواع العشرية تخزن كسوراً. float دقة أقل، double دقة أعلى.

📄 SLIDE 19 – boolean

✅ boolean

Can have two values: true or false. Used in conditions.

boolean isJavaFun = true; boolean isFishTasty = false;

النوع boolean له قيمتان: true أو false. يستخدم في الشروط.

📄 SLIDE 20 – char

🔤 char

Stores a single 16-bit Unicode character. Use single quotes.

char letter = 'A'; char digit = '9'; char symbol = '$';

char يخزن حرفاً واحداً بترميز Unicode. يوضع بين علامتي اقتباس مفردة.

📄 SLIDE 21 – var (Java 10+)

🔮 Implicit type with var

Use var to let Java infer the type from the initial value.

var str = "Java"; // String var number = 42; // int var pi = 3.14; // double

var يخبر المترجم أن يستنتج النوع من القيمة المعطاة. متاح من Java 10.

📄 SLIDE 22 – Arithmetic Operations

🧮 Arithmetic

OperatorMeaningExample
+Addition5 + 2 = 7
-Subtraction5 - 2 = 3
*Multiplication5 * 2 = 10
/Division5 / 2 = 2 (int) / 5.0/2 = 2.5
%Remainder (modulo)5 % 2 = 1

العمليات: + جمع، - طرح، * ضرب، / قسمة (تحذير: قسمة عددين صحيحين تعطي عدداً صحيحاً)، % باقي القسمة.

📄 SLIDE 23 – Combined Assignment

⚡ Combined Assignment Operators

OperatorExampleEquivalent
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5

عوامل مثل += تختصر عملية الجمع مع الإسناد. مثال: x += 5 تعني x = x + 5.

📄 SLIDE 24 – Java Math Library

📐 Math class

  • Math.sqrt(x) – square root
  • Math.pow(a,b) – a to the power b
  • Math.abs(x) – absolute value
  • Math.max(a,b) – maximum
  • Math.min(a,b) – minimum
  • Math.random() – random double 0.0–1.0

كلاس Math يوفر دوال رياضية: جذر تربيعي، أس، قيمة مطلقة، أكبر، أصغر، رقم عشوائي.

📄 SLIDE 25 – Trace a Program Execution

🔍 Variable Tracing

public class ComputeArea { public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

Step by step: memory allocation → assign 20 → compute area → print.

يتم تخصيص مساحة للمتغيرات radius و area، ثم تعطى radius القيمة 20، ثم تحسب area، ثم تطبع.

📄 SLIDE 26 – Packages & import

📦 Packages

A package is a way to categorize classes and interfaces. Package name comes first in the file. Import statements tell the compiler where to find classes.

Built-in packages: java.lang (auto-imported), java.io, java.util, etc.

import java.util.Scanner; // must be at top

الحزم (packages) تنظم الكلاسات. import تخبر المترجم بمكان الكلاس. java.lang مستوردة تلقائياً.

📄 SLIDE 27 – User Input (Scanner)

⌨️ Scanner Class

To read input from keyboard, use Scanner from java.util.

import java.util.Scanner; Scanner myObj = new Scanner(System.in); System.out.print("Enter username: "); String userName = myObj.nextLine(); // read string int age = myObj.nextInt(); // read int double salary = myObj.nextDouble(); // read double myObj.close();

كلاس Scanner يستخدم لقراءة المدخلات من لوحة المفاتيح. nextLine() لقراءة نص، nextInt() لعدد صحيح، nextDouble() لعدد عشري.

📄 SLIDE 28 – Example: Fahrenheit to Celsius

🌡️ Temperature Conversion

import java.util.Scanner; public class FahrenheitToCelsius { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter temperature in Fahrenheit: "); double fahrenheit = input.nextDouble(); double celsius = (5.0 / 9) * (fahrenheit - 32); System.out.println("The equivalent in Celsius is " + celsius); input.close(); } }

هذا البرنامج يطلب من المستخدم درجة حرارة بالفهرنهايت ويحولها إلى سيلسيوس باستخدام المعادلة.

📄 SLIDE 29 – BMI Calculator

⚖️ BMI Example

import java.util.Scanner; public class BMICalc { public static void main(String[] args) { double weight, height, BMI; Scanner input = new Scanner(System.in); System.out.print("Enter weight in KGs: "); weight = input.nextDouble(); System.out.print("Enter height in meters: "); height = input.nextDouble(); BMI = weight / (height * height); System.out.println("Your BMI = " + BMI); input.close(); } }

يحسب BMI بقسمة الوزن على مربع الطول.

📄 SLIDE 30 – Complete I/O Example

📋 Input/Output Demo

import java.util.Scanner; public class InputOutput { public static void main(String[] args) { String name; int age; double income; Scanner input = new Scanner(System.in); System.out.print("What is your name? "); name = input.nextLine(); System.out.print("What is your age? "); age = input.nextInt(); System.out.print("What is your annual income? "); income = input.nextDouble(); System.out.println("Hello, " + name + ". Your age is " + age + " and your income is QR" + income); input.close(); } }

هذا المثال يقرأ اسم، عمر، دخل ثم يعرضهم.

📄 END-OF-SLIDE PROBLEMS

📝 Practice Problems with Solutions

Problem 1: Identifier Validation

Which of the following are valid Java identifiers? Explain why invalid ones are wrong.

  • hello
  • exam-
  • class
  • _Name
  • 123Here
  • valid_$1
  • student ID
  • not@valid
  • $23
Solution 1

Valid: hello, _Name, valid_$1, $23

Invalid:

  • exam- – contains hyphen (-), not allowed
  • class – reserved keyword
  • 123Here – starts with digit
  • student ID – contains space
  • not@valid – contains @ symbol
Problem 2: Output Prediction (print vs println)

What is the output of the following code?

public class Countdown { public static void main(String[] args) { System.out.print("Three... "); System.out.print("Two... "); System.out.print("One... "); System.out.print("Zero... "); System.out.println("Liftoff!"); System.out.println("Houston, we have a problem."); } }
Solution 2

Output:

Three... Two... One... Zero... Liftoff! Houston, we have a problem.

Explanation: print stays on same line, println moves to next line after printing.

Problem 3: Arithmetic and Concatenation

What is the output of this statement?

System.out.println("The following will be printed " + "in a tabbed format: " + "\n\tFirst = " + 5 * 6 + ", " + "\n\tSecond = " + (5 * 6) + ", " + "\n\tThird = " + 16.7 + ".");
Solution 3

Output:

The following will be printed in a tabbed format: First = 30, Second = 30, Third = 16.7.

Explanation: \n newline, \t tab. 5 * 6 is calculated first (multiplication higher precedence), then concatenated. Parentheses in (5 * 6) are optional but clarify.

Problem 4: Division and Remainder

Evaluate the following expressions in Java:

  • 5 / 2
  • 5.0 / 2
  • 5 % 2
  • 17 % 5
Solution 4
  • 5 / 2 = 2 (integer division truncates)
  • 5.0 / 2 = 2.5 (floating-point division)
  • 5 % 2 = 1 (remainder)
  • 17 % 5 = 2 (remainder)
Problem 5: Combined Assignment

What are the values of x, y, and z after the following code?

int x = 10; int y = 5; int z = 2; x += y; // x = x + y y *= z; // y = y * z z %= 3; // z = z % 3
Solution 5
  • x += y → x = 10 + 5 = 15
  • y *= z → y = 5 * 2 = 10
  • z %= 3 → z = 2 % 3 = 2

Final: x = 15, y = 10, z = 2

Problem 6: Math Library

Write Java expressions for:

  • Square root of 25
  • 2 raised to the power 8
  • Absolute value of -10
  • Maximum of 15 and 20
Solution 6
  • Math.sqrt(25) → 5.0
  • Math.pow(2, 8) → 256.0
  • Math.abs(-10) → 10
  • Math.max(15, 20) → 20
Problem 7: Variable Tracing

Trace the ComputeArea program and show the values of radius and area after each step.

Solution 7

Step by step:

  1. double radius; → radius: uninitialized
  2. double area; → area: uninitialized
  3. radius = 20; → radius = 20.0
  4. area = radius * radius * 3.14159; → area = 20 * 20 * 3.14159 = 1256.636
  5. Print: "The area for the circle of radius 20.0 is 1256.636"
Problem 8: Scanner Input

Write a program that asks the user for two integers and prints their sum.

Solution 8
import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter first integer: "); int num1 = input.nextInt(); System.out.print("Enter second integer: "); int num2 = input.nextInt(); int sum = num1 + num2; System.out.println("Sum = " + sum); input.close(); } }
Problem 9: Fahrenheit to Celsius (already given) – modify to ask for Celsius and convert to Fahrenheit

Write a program that converts Celsius to Fahrenheit using formula: F = (C * 9/5) + 32.

Solution 9
import java.util.Scanner; public class CelsiusToFahrenheit { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter temperature in Celsius: "); double celsius = input.nextDouble(); double fahrenheit = (celsius * 9.0/5) + 32; System.out.println("Equivalent in Fahrenheit: " + fahrenheit); input.close(); } }
Problem 10: BMI Calculator (already given) – add health category

Extend the BMI calculator to also display category: Underweight (<18.5), Normal (18.5–24.9), Overweight (25–29.9), Obese (≥30).

Solution 10
import java.util.Scanner; public class BMICategory { public static void main(String[] args) { double weight, height, bmi; Scanner input = new Scanner(System.in); System.out.print("Enter weight in KGs: "); weight = input.nextDouble(); System.out.print("Enter height in meters: "); height = input.nextDouble(); bmi = weight / (height * height); System.out.println("Your BMI = " + bmi); System.out.print("Category: "); if (bmi < 18.5) System.out.println("Underweight"); else if (bmi < 25) System.out.println("Normal"); else if (bmi < 30) System.out.println("Overweight"); else System.out.println("Obese"); input.close(); } }
📋 COMPREHENSIVE SUMMARY

📌 Java Structure – All Key Points

  • Java program: one or more classes, each with methods, one method named main.
  • Class name: uppercase start, file name = ClassName.java.
  • Naming: classes PascalCase, variables/methods camelCase, constants UPPER_SNAKE.
  • Reserved words: 50+ keywords (common ones listed) cannot be used as identifiers.
  • Comments: //, /* */, /** */.
  • Identifiers: start with letter, _, $; case-sensitive.
  • Variables: declared with type; constants with final.
  • Output: System.out.print() and println().
  • Escape sequences: \n, \t, \", \\.
  • Data types: 8 primitive (byte, short, int, long, float, double, char, boolean) and reference.
  • var: implicit type inference (Java 10+).
  • Arithmetic: + - * / %, combined assignments (+= etc.).
  • Math class: sqrt, pow, abs, max, min, random.
  • Packages: organize classes; import statement.
  • Scanner: read input: nextLine(), nextInt(), nextDouble().
  • Problems: 10 practice problems with solutions included.

ملخص تركيب برنامج جافا:

  • برنامج جافا: كلاسات تحتوي دوال، وأحدها main.
  • اسم الكلاس يبدأ بحرف كبير، الملف بنفس الاسم.
  • قواعد التسمية: كلاسات PascalCase، متغيرات/دوال camelCase، ثوابت UPPER_SNAKE.
  • الكلمات المحجوزة (keywords) لا يمكن استخدامها كأسماء.
  • التعليقات: // سطر، /* */ عدة أسطر، /** */ javadoc.
  • المعرفات: تبدأ بحرف أو _ أو $، حساسة لحالة الأحرف.
  • المتغيرات: تُصرّح بنوعها. الثوابت: final.
  • الإخراج: print() و println().
  • تسلسلات الهروب: \n سطر جديد، \t tab، إلخ.
  • الأنواع البدائية: 8 أنواع (byte, short, int, long, float, double, char, boolean).
  • var: استدلال النوع من القيمة (من Java 10).
  • العمليات الحسابية: + - * / %، وعوامل الإسناد المركبة.
  • كلاس Math: دوال رياضية.
  • الحزم: تنظيم الكلاسات، import لاستيرادها.
  • Scanner: لقراءة المدخلات nextLine(), nextInt(), nextDouble().
  • المسائل: 10 مسائل مع الحلول.

نتمنى لكم التوفيق والنجاح

جميع الحقوق محفوظة ACADEZI 2026 ©