[Go to site: main page, start]

0% found this document useful (0 votes)
9 views15 pages

Java Programming Study Notes

The document provides comprehensive Java programming study notes covering key topics such as Scanner input, switch statements, loops (while, do-while, for), and methods. Each section includes explanations, examples, and common mistakes to help beginners understand and implement these concepts effectively. The notes emphasize the importance of code organization and reusability through methods.

Uploaded by

junior7benzy
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)
9 views15 pages

Java Programming Study Notes

The document provides comprehensive Java programming study notes covering key topics such as Scanner input, switch statements, loops (while, do-while, for), and methods. Each section includes explanations, examples, and common mistakes to help beginners understand and implement these concepts effectively. The notes emphasize the importance of code organization and reusability through methods.

Uploaded by

junior7benzy
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

Java Programming Study Notes

Topics covered: switch, while loops, do-while loops, for loops, methods, static keyword, and
Scanner input

Student-friendly notes with detailed explanations and lots of Scanner-based examples

Section What you will learn

How to read input from the keyboard and why Java needs an object
Scanner
for input.

How to choose between many exact values like menu options,


switch
grades, or day numbers.

while How to repeat code while a condition stays true.

do-while How to run code at least once before checking the condition.

for How to repeat code a known number of times using a counter.

How to organize code into reusable blocks with parameters and


Methods
return values.

static What static means and why main must be static.


1. Scanner and user input
A Scanner is a class from [Link] that lets your program read input typed by the user. Without
Scanner, your program can print output, but it cannot easily ask the user for values during
execution.

In almost every beginner program, the first input steps are the same: import Scanner, create a
Scanner object, prompt the user, and then store the value in a variable.

Remember: You must import Scanner before using it: import [Link];

Basic pattern
import [Link];

public class InputDemo {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello " + name + ". You are " + age + " years old.");
}
}
 Scanner input = new Scanner([Link]); creates a Scanner object connected to the keyboard.
 nextLine() reads a full line of text.
 nextInt() reads an integer.
 nextDouble() reads a decimal number.
 Always display a clear prompt before asking for input.

Common Scanner methods


Method Reads Example use

nextInt() whole number int age = [Link]();

nextDouble() decimal number double price = [Link]();

next() one word String city = [Link]();

nextLine() whole line of text String fullName = [Link]();

nextBoolean() true or false boolean done = [Link]();

Important Scanner issue: nextInt() then nextLine()


A very common beginner mistake happens when you use nextInt() and then nextLine() right after
it. nextInt() leaves the Enter key in the input buffer, so the nextLine() may look like it was skipped.

import [Link];
public class ScannerProblem {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter your age: ");


int age = [Link]();
[Link](); // clears the leftover Enter

[Link]("Enter your favorite subject: ");


String subject = [Link]();

[Link]("Age: " + age);


[Link]("Subject: " + subject);
}
}
Fix: When you use nextInt(), nextDouble(), or next(), and then want to use nextLine(), usually
add [Link]() once to clear the leftover Enter.

2. switch statement
A switch statement is used when you want to compare one variable against many exact values. It is
often cleaner than a long chain of if-else statements when you are checking a menu choice, day
number, grade letter, or simple command.

General form
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}
 The expression is usually an int, char, String, or enum.
 Each case checks for one exact value.
 break stops the switch after a matching case runs.
 default is optional, but it is strongly recommended.

Example 1: menu choice


import [Link];

public class SwitchMenu {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("=== Cafe Menu ===");


[Link]("1. Tea");
[Link]("2. Coffee");
[Link]("3. Juice");
[Link]("Choose an option: ");
int choice = [Link]();

switch (choice) {
case 1:
[Link]("You chose Tea.");
break;
case 2:
[Link]("You chose Coffee.");
break;
case 3:
[Link]("You chose Juice.");
break;
default:
[Link]("Invalid option.");
}
}
}

Example 2: using String with Scanner


import [Link];

public class SwitchString {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter a letter grade (A, B, C, D, or F): ");


String grade = [Link]().toUpperCase();

switch (grade) {
case "A":
[Link]("Excellent work.");
break;
case "B":
[Link]("Good job.");
break;
case "C":
[Link]("Satisfactory.");
break;
case "D":
[Link]("Needs improvement.");
break;
case "F":
[Link]("Failing grade.");
break;
default:
[Link]("That is not a valid grade.");
}
}
}
Notice the use of toUpperCase(). This helps because the user may type a, A, or even spaces around
the text in some situations. You can also use trim() when needed to remove extra spaces.

What happens if break is missing?


If break is missing, Java continues into the next case. This is called fall-through. Sometimes it is
done on purpose, but most of the time beginners forget break by accident.

import [Link];

public class MissingBreak {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter a number from 1 to 2: ");


int number = [Link]();

switch (number) {
case 1:
[Link]("Case 1 ran.");
case 2:
[Link]("Case 2 ran.");
break;
default:
[Link]("No match.");
}
}
}
Remember: If the user enters 1, both case 1 and case 2 will run because there is no break after
case 1.

Good uses for switch


 Program menus
 Checking exact commands like yes/no or start/stop
 Mapping numbers to days or months
 Reacting to one exact grade or category

3. while loop
A while loop repeats code as long as its condition is true. It is best when you do not know in
advance exactly how many times the loop should run.

General form
while (condition) {
// repeated code
}
 Java checks the condition first.
 If the condition is true, the loop body runs.
 After the body finishes, Java checks the condition again.
 If the condition is false at the start, the loop does not run at all.

Example 1: counting with while


import [Link];

public class WhileCount {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Count up to what number? ");


int limit = [Link]();

int count = 1;

while (count <= limit) {


[Link]("Count = " + count);
count++;
}
}
}
The variable count is called the loop control variable. It starts at 1, the condition checks whether it
is still within range, and count++ changes it each time so the loop can eventually stop.
Example 2: input validation
import [Link];

public class WhileValidation {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter a number from 1 to 5: ");


int number = [Link]();

while (number < 1 || number > 5) {


[Link]("Invalid. Enter a number from 1 to 5: ");
number = [Link]();
}

[Link]("Accepted value: " + number);


}
}
Remember: This is one of the most useful real-world uses of while: keep asking until the user
enters valid input.

Example 3: sentinel-controlled loop


import [Link];

public class WhileSentinel {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

int total = 0;

[Link]("Enter a number (-1 to stop): ");


int number = [Link]();

while (number != -1) {


total = total + number;
[Link]("Enter a number (-1 to stop): ");
number = [Link]();
}

[Link]("Total = " + total);


}
}
A sentinel value is a special value that tells the program to stop. In this example, -1 is not added to
the total. It only ends the loop.

Common while loop mistakes


 Forgetting to update the loop control variable, causing an infinite loop.
 Using = instead of == in comparisons.
 Writing a condition that can never become false.
 Updating the wrong variable inside the loop.

4. do-while loop
A do-while loop is very similar to a while loop, but the condition is checked at the end. That means
the loop body always runs at least one time.
General form
do {
// repeated code
} while (condition);
Syntax detail: Notice the semicolon after while (condition); This is part of the syntax.

Example 1: menu that repeats


import [Link];

public class DoWhileMenu {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

int choice;

do {
[Link]("=== Simple Menu ===");
[Link]("1. Say hello");
[Link]("2. Show time message");
[Link]("3. Exit");
[Link]("Choose: ");
choice = [Link]();

switch (choice) {
case 1:
[Link]("Hello!");
break;
case 2:
[Link]("Keep practicing Java.");
break;
case 3:
[Link]("Goodbye.");
break;
default:
[Link]("Invalid choice.");
}

[Link]();
} while (choice != 3);
}
}
This is a great example of when do-while is better than while. You want the menu to show first,
then keep repeating until the user chooses Exit.

Example 2: ask until the answer is yes


import [Link];

public class DoWhileYes {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

String answer;

do {
[Link]("Type yes to continue: ");
answer = [Link]().toLowerCase();
} while (![Link]("yes"));

[Link]("You may continue.");


}
}
while vs do-while
Feature while do-while

Condition checked Before the loop body After the loop body

Runs at least once? Not always Yes

Best for Unknown repetitions Menus or prompts that must


show once

5. for loop
A for loop is used when you know the number of repetitions or when you want a clear counter-
based loop. It packs the starting value, condition, and update in one line.

General form
for (initialization; condition; update) {
// repeated code
}
 Initialization runs once at the beginning.
 Condition is checked before each repetition.
 Update runs after each repetition.
 for loops are great for counting, repeating fixed tasks, and working with indexes.

Example 1: repeat a message


import [Link];

public class ForRepeat {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("How many times should the message print? ");


int times = [Link]();
[Link]();

[Link]("Enter the message: ");


String message = [Link]();

for (int i = 1; i <= times; i++) {


[Link](i + ": " + message);
}
}
}

Example 2: sum a series of user-entered numbers


import [Link];

public class ForSum {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("How many numbers will you enter? ");


int count = [Link]();

int total = 0;
for (int i = 1; i <= count; i++) {
[Link]("Enter number " + i + ": ");
int number = [Link]();
total = total + number;
}

[Link]("Total = " + total);


}
}

Example 3: count backward


import [Link];

public class ForCountdown {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Start countdown from: ");


int start = [Link]();

for (int i = start; i >= 1; i--) {


[Link](i);
}

[Link]("Lift off!");
}
}
The update does not always have to be i++. It can be i-- for counting backward, or even i = i + 2 for
skipping values.

When to choose for instead of while


 Use for when the loop is mainly controlled by a counter.
 Use while when the loop depends more on user choice or a changing condition.
 Both can often solve the same problem, but one may be clearer.

6. Methods in Java
A method is a named block of code that performs a task. Methods help you break a big problem
into smaller, reusable parts. They improve organization, reduce repetition, and make programs
easier to test and debug.

Why methods matter


 They let you reuse code instead of rewriting it.
 They make programs easier to read.
 They allow one method to focus on one job.
 They help separate input, processing, and output.

Basic method vocabulary


Term Meaning

Method name The identifier used to call the method.

Return type The type of value the method gives back, such as int, double,
String, or void.

Parameter An input listed in the method header.

Argument The real value passed into a method when it is called.

void Means the method does not return a value.

General forms
public static void methodName(parameters) {
// code
}

public static returnType methodName(parameters) {


// code
return value;
}

Example 1: void method that prints a greeting


import [Link];

public class MethodGreeting {


public static void showGreeting(String name) {
[Link]("Welcome, " + name + "!");
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

showGreeting(name);
}
}
showGreeting takes one parameter called name. When main calls showGreeting(name), the
current value stored in the variable name is passed to the method.

Example 2: method that returns a value


import [Link];

public class MethodReturn {


public static int squareNumber(int number) {
return number * number;
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("Enter an integer: ");


int value = [Link]();

int result = squareNumber(value);

[Link]("The square is " + result);


}
}
Rule: If a method has a non-void return type, it must return a value of that type.
Example 3: method with two parameters
import [Link];

public class MethodTwoParameters {


public static double calculateAverage(double a, double b) {
return (a + b) / 2.0;
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("Enter the first number: ");


double first = [Link]();

[Link]("Enter the second number: ");


double second = [Link]();

double average = calculateAverage(first, second);

[Link]("Average = " + average);


}
}

Example 4: separating jobs into methods


import [Link];

public class MethodOrganization {


public static int getNumber(Scanner input) {
[Link]("Enter a number: ");
return [Link]();
}

public static int tripleNumber(int number) {


return number * 3;
}

public static void showResult(int original, int tripled) {


[Link]("Original = " + original);
[Link]("Tripled = " + tripled);
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

int value = getNumber(input);


int result = tripleNumber(value);
showResult(value, result);
}
}
This program is better organized because input, processing, and output are separated into different
methods. That is a very good habit in programming.

Parameter vs argument
Inside the method header, the variable names are parameters. In the method call, the real values
sent in are arguments. For example, in calculateAverage(first, second), first and second are
arguments.
7. The static keyword
The keyword static means something belongs to the class itself rather than to a specific object. At
the beginner level, the most important thing to know is that main is static, and the helper methods
you call directly from main are often made static too.

Why main is static


public static void main(String[] args) {
// program starts here
}
Java starts the program without creating an object of your class first. Because of that, main must be
static. A static method can be used by the class itself.

Why beginner helper methods are often static


If you write another method and want to call it directly from main in the same class, it is common
to make it static too. That avoids object creation while you are still learning the basics.

import [Link];

public class StaticExample {


public static int doubleNumber(int number) {
return number * 2;
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("Enter a number: ");


int value = [Link]();

int result = doubleNumber(value);

[Link]("Double = " + result);


}
}

Static variable example


import [Link];

public class StaticCounter {


static int visitCount = 0;

public static void visit() {


visitCount++;
[Link]("Visit count = " + visitCount);
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("How many visits should be recorded? ");


int times = [Link]();

for (int i = 1; i <= times; i++) {


visit();
}
}
}
visitCount is shared by the class. Each time visit() runs, the same variable is updated. This is
different from a local variable inside a method, which is created fresh each time the method runs.

Simple idea to remember


Memory shortcut: static = belongs to the class. Non-static = belongs to an object.

8. Mixed examples that combine topics


The best way to learn programming is to combine topics. These examples mix Scanner, loops,
methods, switch, and static.

Example 1: calculator menu


import [Link];

public class MiniCalculator {


public static double add(double a, double b) {
return a + b;
}

public static double subtract(double a, double b) {


return a - b;
}

public static double multiply(double a, double b) {


return a * b;
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);
int choice;

do {
[Link]("=== Mini Calculator ===");
[Link]("1. Add");
[Link]("2. Subtract");
[Link]("3. Multiply");
[Link]("4. Exit");
[Link]("Choose: ");
choice = [Link]();

if (choice >= 1 && choice <= 3) {


[Link]("Enter first number: ");
double first = [Link]();

[Link]("Enter second number: ");


double second = [Link]();

switch (choice) {
case 1:
[Link]("Result = " + add(first, second));
break;
case 2:
[Link]("Result = " + subtract(first, second));
break;
case 3:
[Link]("Result = " + multiply(first, second));
break;
}
} else if (choice != 4) {
[Link]("Invalid menu choice.");
}

[Link]();
} while (choice != 4);
}
}

Example 2: guessing game with while loop


import [Link];

public class GuessingGame {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

int secret = 7;
int guess = 0;

while (guess != secret) {


[Link]("Guess the secret number: ");
guess = [Link]();

if (guess < secret) {


[Link]("Too low.");
} else if (guess > secret) {
[Link]("Too high.");
} else {
[Link]("Correct!");
}
}
}
}

Example 3: class average with for loop and method


import [Link];

public class ClassAverage {


public static double computeAverage(double total, int count) {
return total / count;
}

public static void main(String[] args) {


Scanner input = new Scanner([Link]);

[Link]("How many students? ");


int students = [Link]();

double total = 0;

for (int i = 1; i <= students; i++) {


[Link]("Enter mark for student " + i + ": ");
double mark = [Link]();
total = total + mark;
}

double average = computeAverage(total, students);

[Link]("Class average = " + average);


}
}

9. Final summary
 Use Scanner to get user input.
 Use switch for many exact choices.
 Use while when a loop should continue as long as a condition stays true.
 Use do-while when the code must run at least once.
 Use for when a counter controls the repetitions.
 Use methods to organize code and reuse logic.
 Use static for methods or variables that belong to the class rather than an object.

10. Quick comparison chart


Topic Main purpose Checks condition Best beginner example

Scanner Reads input - Ask the user for age or


name

switch Chooses among exact - Menu option


values

while Repeats while true Before Validate input

do-while Runs at least once After Repeat a menu

for Counter loop Before Repeat 5 times

Method Reusable task - calculateAverage()

static Belongs to class - main method

Practice tip: Type every example yourself, change a few values, and predict the output before
running the code. That is one of the fastest ways to get comfortable with Java.

You might also like