☕ Java Programming – Class 2 Notes
Control Flow • Methods • OOP Fundamentals • Problem Solving Exercises
Selection (if/switch) Loops (for/while) Methods Classes & Objects Mini ProjectPart 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.
•
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.
A.3 The else if Ladder
For more than two possibilities. Java checks top-to-bottom and runs the first true branch.
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.
A.5 The switch Statement
Cleaner than else if when comparing one variable against exact constant values.
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").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
| Loop | Condition Checked | Min Runs | Best Used When |
|---|---|---|---|
for | Before each iteration | 0 | Number of repetitions is known |
while | Before each iteration | 0 | Repeat until something happens |
do...while | After each iteration | 1 | Must run at least once (menus, validation) |
B.1 The for Loop
B.2 The while Loop
B.3 The do...while Loop
B.4 Nested Loops
A loop inside another loop. The inner loop completes fully for each outer iteration.
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.
• Infinite loop: forgetting
i++• Off-by-one: using
< instead of <=• Semicolon after header:
for(...); creates an empty bodyProblem-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 4: Multiplication Table
Ex 5: Sum of Numbers (Accumulator)
Ex 6: Factorial
Ex 7: Largest of 3 Numbers
Ex 8: Prime Number Check
Ex 9: Reverse a Number
Ex 10: Palindrome Check
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
| Part | Example | Meaning |
|---|---|---|
| Access modifier | public | Who can call it |
| static | static | Belongs to class (callable from main) |
| Return type | int | Type of value returned (void = nothing) |
| Name | add | camelCase verb |
| Parameters | int a, int b | Inputs (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.
Part D – OOP Fundamentals (Classes & Objects) ▼
OOP organises programs around objects that combine data (fields) and behaviour (methods).
D.1 Class Definition
D.2 Creating Objects
D.3 Constructors
Special method that runs automatically when new is used. Same name as class, no return type.
name = name; assigns the parameter to itself (field stays null). Always use this.name = name;D.4 Instance vs Static Variables
| Instance Variable | Static (Class) Variable |
|---|---|
Declared without static | Declared with static |
| Separate copy per object | ONE copy shared by all objects |
Accessed via object: s1.name | Accessed 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
Main.java
Expected Output
isAdult(), birthday(), isPass() methods. Add keyboard input with Scanner + loop. Add a second constructor.Quick Revision Summary & Practice Questions ▼
Key Takeaways
if,else if,switchmake decisions.switchneedsbreak.for= known count.while= unknown (may run 0×).do...while= at least once.breakexits loop.continueskips to next iteration.- Method = return type + name + parameters + body.
voidreturns nothing. - Class = blueprint. Object = instance created with
new. this= current object. Instance vars = per object. Static vars = shared.
Practice Questions
- Read marks and print grade using
if...else ifAND usingswitch(marks/10). - Print pattern with nested loops: row 1=1, row 2=1 2, row 3=1 2 3, up to row 5.
- What is the difference between
whileanddo...while? Give a case wheredo...whileis better. - Write
static double average(int a, int b, int c)and call it from main. - Output of:
for(int i=1; i<=5; i++){ if(i==3) continue; System.out.print(i); }? - Create class
Bookwith title, price, constructor, anddisplay(). Create 3 books. - Explain instance vs static variable with an example.
- Why does
name = name;in a constructor fail? How do you fix it?
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 GuidanceTechnical guidance for university assignments and final-year IT projects.
|
🤖 AI, Coding & SoftwareDevelop programming knowledge and practical software development skills.
|
🏫 School ICT ClassesInteractive ICT and Computer Science lessons for school students.
|
🌐 Web Design & DevelopmentBuild websites and database-driven applications for individuals and businesses.
|
📢 Digital MarketingGrow your brand online with social media and digital marketing support.
|
💻 Computer & IT SkillsBuild essential computer skills from absolute beginner to advanced level.
|
📚 Learn With Your Curriculum
Support for Sri Lankan Local Curriculum, Cambridge and Pearson Edexcel programs.
🇱🇰 Sri Lankan Local Curriculum
|
📘 Pearson Edexcel
|
📗 Cambridge Curriculum
|
💻 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
|
📄 Documentation & Practical
|
🧠 AI & Smart Applications
|
📊 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.
ITClassSL — ICT Training | Computer Classes | Programming | University Project Guidance | Digital Marketing
Learn • Practice • Build • Grow 🚀