Showing posts with label Java Programming Notes - Class 2: Control Flow. Show all posts
Showing posts with label Java Programming Notes - Class 2: Control Flow. Show all posts

Thursday, October 8, 2026

Java Programming Notes - Class 2: Control Flow, Methods & OOP CSC102S3 Course Title: Computer Programming I Online Class English and Tamil Medium

☕ Java Programming – Class 2 Notes

Control Flow • Methods • OOP Fundamentals • Problem Solving Exercises

Selection (if/switch) Loops (for/while) Methods Classes & Objects Mini Project
🔀 Part A – Selection Statements (Making Decisions) ▼

Normally Java runs statements top-to-bottom (sequence). Selection statements change that order by checking a boolean condition (true/false).

A.1 The if Statement

Runs a block only when the condition is true.

int age = 20; if (age >= 18) { System.out.println("You are eligible to vote."); } System.out.println("Program finished.");
⚠️ Common Mistakes:
• if (x = 5) is an error. Use == to compare.
• Never put a semicolon after the condition: if (age >= 18); creates an empty body.

A.2 The if...else Statement

Chooses between two paths. Exactly one block always executes.

if (n % 2 == 0) { System.out.println(n + " is Even"); } else { System.out.println(n + " is Odd"); }

A.3 The else if Ladder

For more than two possibilities. Java checks top-to-bottom and runs the first true branch.

if (marks >= 75) System.out.println("A"); else if (marks >= 65) System.out.println("B"); else if (marks >= 55) System.out.println("C"); else System.out.println("Fail");
💡 Order matters! Always test the most restrictive condition first. If you wrote marks >= 55 first, a student with 90 marks would incorrectly get "C".

A.4 Nested if

An if inside another if. Used when a second decision depends on the first.

if (age >= 18) { if (hasTestPassed) { System.out.println("Licence issued."); } else { System.out.println("Please pass the driving test first."); } } else { System.out.println("You are too young to apply."); }

A.5 The switch Statement

Cleaner than else if when comparing one variable against exact constant values.

switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); }
⚠️ Without break, execution "falls through" into the next case. Fall-through can be used intentionally to group cases (e.g., case 6 and case 7 both printing "Weekend").
💡 Ternary Operator (one-line if/else):
String result = (marks >= 40) ? "Pass" : "Fail";
🔁 Part B – Repetition (Loops) ▼

Every loop needs three things: (1) Initialisation, (2) Condition, and (3) Update. Forgetting the update causes an infinite loop.

Loop Comparison

LoopCondition CheckedMin RunsBest Used When
forBefore each iteration0Number of repetitions is known
whileBefore each iteration0Repeat until something happens
do...whileAfter each iteration1Must run at least once (menus, validation)

B.1 The for Loop

// Print 1 to 10 for (int i = 1; i <= 10; i++) { System.out.println(i); } // Count down for (int i = 10; i >= 1; i--) { ... } // Step by 2 (even numbers) for (int i = 2; i <= 20; i += 2) { ... }

B.2 The while Loop

int i = 1; while (i <= 5) { System.out.println(i); i++; // Don't forget this! }

B.3 The do...while Loop

do { System.out.print("Enter a positive number: "); number = input.nextInt(); } while (number <= 0); // Note the semicolon!

B.4 Nested Loops

A loop inside another loop. The inner loop completes fully for each outer iteration.

// Triangle pattern for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } // Output: * ** *** **** *****

B.5 break vs continue

break

Immediately terminates the entire loop. Control goes to the statement after the loop.

continue

Skips the rest of the current iteration and jumps to the next one. The loop itself continues.

⚠️ Common Loop Mistakes:
• Infinite loop: forgetting i++
• Off-by-one: using < instead of <=
• Semicolon after header: for(...); creates an empty body
✏️ Problem-Solving Exercises (1–10) ▼

Combine selection and repetition. Add import java.util.Scanner; and create Scanner input = new Scanner(System.in); where needed.

Ex 1–3: Numbers, Even, Odd

// Ex 1: Print 1-100 for (int i = 1; i <= 100; i++) System.out.print(i + " "); // Ex 2: Even numbers (efficient - step by 2) for (int i = 2; i <= 100; i += 2) System.out.print(i + " "); // Ex 3: Odd numbers for (int i = 1; i <= 100; i += 2) System.out.print(i + " ");

Ex 4: Multiplication Table

int n = input.nextInt(); for (int i = 1; i <= 10; i++) { System.out.println(n + " x " + i + " = " + (n * i)); }

Ex 5: Sum of Numbers (Accumulator)

int sum = 0; for (int i = 1; i <= n; i++) sum += i; System.out.println("Sum = " + sum);

Ex 6: Factorial

long fact = 1; // Use long! int overflows after 12! for (int i = 2; i <= n; i++) fact *= i; System.out.println(n + "! = " + fact);

Ex 7: Largest of 3 Numbers

int largest = a; // Assume a is largest if (b > largest) largest = b; if (c > largest) largest = c; System.out.println("Largest = " + largest);

Ex 8: Prime Number Check

boolean isPrime = true; if (n <= 1) isPrime = false; else { for (int i = 2; i * i <= n; i++) { if (n % i == 0) { isPrime = false; break; } } }

Ex 9: Reverse a Number

int rev = 0; while (n > 0) { int digit = n % 10; // Get last digit rev = rev * 10 + digit; // Build reversed n = n / 10; // Drop last digit }

Ex 10: Palindrome Check

int original = n; // Keep a copy! // ... reverse logic from Ex 9 ... if (original == rev) System.out.println("Palindrome"); else System.out.println("NOT a Palindrome");
⚙️ Part C – Methods (Reusable Code Blocks) ▼

Methods let you reuse code, break problems into parts, and make programs easier to read and test.

Method Anatomy

public static int add(int a, int b) { return a + b; }
PartExampleMeaning
Access modifierpublicWho can call it
staticstaticBelongs to class (callable from main)
Return typeintType of value returned (void = nothing)
NameaddcamelCase verb
Parametersint a, int bInputs (type + name)
Body{ return a+b; }The code that runs

Key Concepts

Parameters vs Arguments

Parameters are in the definition. Arguments are actual values passed in the call.

Pass by Value

Java passes a copy. Changing a parameter inside a method does NOT change the original variable.

void Methods

Return nothing. Just perform an action. Cannot be assigned to a variable.

Local Variables

Declared inside a method. Exist only during that method's execution. Not visible outside.

Overloading

Same name, different parameters. Java picks the right one based on arguments.

Calling Methods

Methods can call other methods. E.g., sumOfSquares() calls square() twice.

⚠️ A non-void method MUST return a value on every path. Missing return = compile error.
🏗️ Part D – OOP Fundamentals (Classes & Objects) ▼

OOP organises programs around objects that combine data (fields) and behaviour (methods).

💡 Analogy: A class is like an architect's blueprint. An object is an actual house built from that blueprint. One blueprint → many houses.

D.1 Class Definition

class Student { String name; // Field (instance variable) int age; // Field }

D.2 Creating Objects

Student s1 = new Student(); s1.name = "Kamal"; s1.age = 20; Student s2 = new Student(); // Independent object s2.name = "Nimali";

D.3 Constructors

Special method that runs automatically when new is used. Same name as class, no return type.

Student(String name, int age) { this.name = name; // 'this' refers to the field this.age = age; // Without 'this', parameter assigns to itself! }
⚠️ name = name; assigns the parameter to itself (field stays null). Always use this.name = name;

D.4 Instance vs Static Variables

Instance VariableStatic (Class) Variable
Declared without staticDeclared with static
Separate copy per objectONE copy shared by all objects
Accessed via object: s1.nameAccessed via class: Student.count
For object data (name, age)For shared data (counters, constants)

D.5 State & Behaviour

State (Fields)

The data stored: name="Kamal", age=20

Behaviour (Methods)

What it can do: display(), isAdult(), birthday()

Calling a method can change the object's state: s1.birthday() increases age.

🎓 Mini Project – Student Management v1 ▼

A complete example combining classes, constructors, methods, and static variables.

Student.java

public class Student { String name; int age; double marks; static int count = 0; // Shared counter Student(String name, int age, double marks) { this.name = name; this.age = age; this.marks = marks; count++; } String getGrade() { if (marks >= 75) return "A"; else if (marks >= 65) return "B"; else if (marks >= 55) return "C"; else return "Fail"; } void display() { System.out.println("Name : " + name); System.out.println("Age : " + age); System.out.println("Marks: " + marks); System.out.println("Grade: " + getGrade()); System.out.println("-------------------"); } }

Main.java

public class Main { public static void main(String[] args) { Student s1 = new Student("Kamal", 20, 78.5); Student s2 = new Student("Nimali", 19, 66); Student s3 = new Student("Sunil", 21, 48); s1.display(); s2.display(); s3.display(); System.out.println("Total students: " + Student.count); } }

Expected Output

Name : Kamal Age : 20 Marks: 78.5 Grade: A ------------------- Name : Nimali Age : 19 Marks: 66.0 Grade: B ------------------- Name : Sunil Age : 21 Marks: 48.0 Grade: Fail ------------------- Total students: 3
💡 Extension Ideas: Add isAdult(), birthday(), isPass() methods. Add keyboard input with Scanner + loop. Add a second constructor.
📋 Quick Revision Summary & Practice Questions ▼

Key Takeaways

  • if, else if, switch make decisions. switch needs break.
  • for = known count. while = unknown (may run 0×). do...while = at least once.
  • break exits loop. continue skips to next iteration.
  • Method = return type + name + parameters + body. void returns nothing.
  • Class = blueprint. Object = instance created with new.
  • this = current object. Instance vars = per object. Static vars = shared.

Practice Questions

  1. Read marks and print grade using if...else if AND using switch(marks/10).
  2. Print pattern with nested loops: row 1=1, row 2=1 2, row 3=1 2 3, up to row 5.
  3. What is the difference between while and do...while? Give a case where do...while is better.
  4. Write static double average(int a, int b, int c) and call it from main.
  5. Output of: for(int i=1; i<=5; i++){ if(i==3) continue; System.out.print(i); }?
  6. Create class Book with title, price, constructor, and display(). Create 3 books.
  7. Explain instance vs static variable with an example.
  8. Why does name = name; in a constructor fail? How do you fix it?
🎓 SRI LANKA ONLINE ICT TRAINING

Expert ICT, Computer Science, Coding & Digital Marketing Classes

Learn ICT, Computer Science, Programming, Web Development and Digital Marketing with practical, career-focused guidance.

💬 Join WhatsApp ▶ Watch Tutorials

🚀 Learn Today. Build Tomorrow.

Welcome to our Sri Lanka Online ICT & Computer Classes community! We provide Online Tuition Classes, Home Visit Classes and Individual / Group Classes for students and professionals. Whether you are a school student, university student, beginner programmer or entrepreneur, we help you develop practical IT skills for education and career growth.

💡 Explore Our Training & Services

🎓 University Project Guidance

Technical guidance for university assignments and final-year IT projects.

  • BIT / BSc / IT / ICT Projects
  • Final Year Project Guidance
  • PHP & MySQL Projects
  • Python & Java Projects
  • Database & Web Applications
  • Project Ideas & Documentation

🤖 AI, Coding & Software

Develop programming knowledge and practical software development skills.

  • Python Programming
  • C & Java Programming
  • PHP & JavaScript
  • HTML & CSS
  • jQuery & AJAX
  • AI & Smart Applications

🏫 School ICT Classes

Interactive ICT and Computer Science lessons for school students.

  • Grade 1 – Grade 11
  • G.C.E. O/L ICT
  • G.C.E. A/L ICT
  • GIT Classes
  • School ICT & Internal Tests
  • Past Papers & Revision

🌐 Web Design & Development

Build websites and database-driven applications for individuals and businesses.

  • Website Design
  • Website Development
  • WordPress Development
  • PHP & MySQL
  • HTML / CSS / JavaScript
  • Website SEO & Maintenance

📢 Digital Marketing

Grow your brand online with social media and digital marketing support.

  • Digital Marketing
  • Facebook Page Management
  • Instagram Marketing
  • TikTok & YouTube
  • Content Creation & SEO
  • Facebook Ads & Reels

💻 Computer & IT Skills

Build essential computer skills from absolute beginner to advanced level.

  • Computer Fundamentals
  • MS Word, Excel & PowerPoint
  • Excel Formulas & Macros
  • Oracle / MySQL / MS SQL
  • AWS, Linux & DevOps
  • Freelancing & IT Skills

📚 Learn With Your Curriculum

Support for Sri Lankan Local Curriculum, Cambridge and Pearson Edexcel programs.

🇱🇰 Sri Lankan Local Curriculum

  • Grade 01 – Grade 11 ICT
  • G.C.E. O/L ICT
  • G.C.E. A/L ICT
  • GIT Classes
  • Term Test Preparation
  • Model Papers & Notes
  • English / Sinhala / Tamil Medium

📘 Pearson Edexcel

  • iPrimary Computing
  • iLowerSecondary Computing
  • International GCSE ICT
  • International GCSE Computer Science
  • GCSE Computer Science
  • International A Level IT
  • International A Level Computer Science

📗 Cambridge Curriculum

  • Cambridge Primary Computing
  • Cambridge Lower Secondary Computing
  • Cambridge IGCSE ICT
  • Cambridge IGCSE Computer Science
  • Cambridge O Level Computer Science
  • AS & A Level IT
  • AS & A Level Computer Science

💻 Programming & Software Development

🛠️ Programming Languages & Technologies

✅ Python Programming ✅ C Programming ✅ Java Programming
✅ PHP Programming ✅ JavaScript ✅ HTML & CSS
✅ jQuery & AJAX ✅ ASP.NET ✅ VB.NET
✅ VB6 ✅ MySQL ✅ MS SQL Server
✅ MS Access ✅ Oracle Database ✅ Database Design
✅ SQL Queries ✅ Database Programming ✅ Software Development

🌐 Web Design & Development

  • ✅ Website Design
  • ✅ Website Development
  • ✅ WordPress Website Development
  • ✅ HTML / CSS / JavaScript
  • ✅ PHP & MySQL
  • ✅ WordPress SEO
  • ✅ Website Maintenance
  • ✅ Web Applications
  • ✅ Database-Driven Websites

🎓 University & Final Year IT Projects

🧑‍💻 Project Development

  • BIT / BSc / IT / ICT Projects
  • PHP & MySQL Projects
  • Python Projects
  • Java Projects
  • Web Application Projects
  • Database Projects

📄 Documentation & Practical

  • Project Ideas
  • System Architecture
  • Database Design
  • Assignments Guidance
  • Practical Implementation
  • Technical Documentation

🧠 AI & Smart Applications

  • AI Application Concepts
  • Machine Learning Modules
  • Automation Applications
  • Step-by-Step Coding
  • System Implementation
  • Project Learning Support

📊 Database, Cloud & IT Training

✅ Oracle Database ✅ MySQL ✅ Microsoft SQL Server
✅ Microsoft Access ✅ Database Design ✅ SQL Queries
✅ AWS Cloud ✅ Linux ✅ UNIX
✅ Windows Server ✅ DevOps ✅ SRE
✅ Automation ✅ Software Testing ✅ Freelancing Skills

📱 Digital Marketing & Social Media

✅ Digital Marketing ✅ Facebook Page Setup & Management
✅ Instagram Marketing ✅ TikTok Marketing
✅ YouTube Channel Setup ✅ Social Media Management
✅ Content Creation ✅ SEO
✅ Facebook Ads ✅ Instagram Reels
✅ LinkedIn Branding ✅ Social Media Campaign Planning
✅ Hashtag Strategy ✅ Insights & Engagement

🖥️ Microsoft Office & Digital Skills

  • ✅ MS Word
  • ✅ MS Excel
  • ✅ MS PowerPoint
  • ✅ Excel Formulas
  • ✅ Excel Automation & Macros
  • ✅ Computer Fundamentals
  • ✅ Digital Literacy
  • ✅ Multimedia Presentations

⭐ Why Join Our Classes?

🌍
Online & Home Visit Classes
👥
Individual & Group Classes
🗣️
English / Sinhala / Tamil
📚
School & University Support
📝
Past Papers & Model Papers
💻
Practical Programming
🚀
Beginner to Advanced Skills
🎯
Career-Focused Learning

📞 Ready to Start Learning?

Book your online class or contact us for ICT training, programming courses, university project guidance and digital marketing services.

📱 Call / WhatsApp: +94 729622034

📧 Email: itclasssl@gmail.com

💻 Skype: ITClassSL

💬 Contact Us on WhatsApp

🌐 Our Online Learning Platforms

Explore tutorials, notes, project guides and learning resources.

📺 YouTube Tutorials
Watch ICT & programming videos
💬 WhatsApp Community
Join our learning community
✍️ ICT Blog
Computer classes and tutorials
📰 WordPress
Notes and learning resources
📘 Facebook
Follow our official page
🌐 Wix Website
Explore our training services
💻 eTeacher Website
Online learning platform
📝 Medium
Read technology articles
❓ Quora
Project guidance and Q&A
🎓 Strikingly Portfolio
University project resources
🗣️ ElaKiri Forum
Join the project discussion
🎵 TikTok
Follow our learning videos
🛒 Payhip
Explore our digital resources
🌐 Weebly
Project and IT resources

ITClassSL — ICT Training | Computer Classes | Programming | University Project Guidance | Digital Marketing

Learn • Practice • Build • Grow 🚀