- Learning Objectives
- Introduction to Programming and Java
- Your First Program: Hello, World!
- Variables and Data Types
- Basic Java Operators
- Control Flow
- Arrays
- Working with Strings
- Key Takeaways
- Glossary of Key Terms
By the end of this lesson, you will be able to:
- Understand basic programming concepts
- Write and run simple Java programs
- Use variables, data types, and operators in Java
- Implement control flow using if statements and loops
- Work with arrays and strings in Java
Programming is like giving instructions to a very literal friend to make a sandwich. You need to be precise and break down each step clearly.
Java is like learning a new language, but instead of communicating with people, you're communicating with computers. Just like human languages have grammar rules, Java has syntax rules we need to follow.
Before we start cooking (coding), we need to set up our kitchen (development environment):
- Install Java Development Kit (JDK) - This is like getting your basic cooking utensils - Java 17.
- Install an Integrated Development Environment (IDE) - Think of this as your specialized kitchen for coding. We recommend IntelliJ IDEA.
Just like you might say "Hello" when learning a new language, in programming, we start with printing "Hello, World!". Here's how it looks:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Don't worry if this looks confusing now. We'll break it down and explain each part as we progress through the course.
Variables are one of the most fundamental concepts in programming. Think of a variable as a container or a labeled box that holds a piece of information.
Imagine you're organizing a party. You might use different containers to hold different items:
- A bowl for chips
- A pitcher for juice
- A plate for cookies
In programming, variables are like these containers. Each variable has:
- A name (like "bowl", "pitcher", "plate")
- A type (what kind of thing it can hold)
- A value (the actual content)
In Java, every variable has a specific type. Here are some basic types:
int
: For whole numbers (e.g., 1, -5, 1000)double
: For decimal numbers (e.g., 3.14, -0.01, 2.0)boolean
: For true/false valueschar
: For single characters (e.g., 'A', '7', '$')String
: For text (e.g., "Hello, World!")
To create a variable in Java, you need to declare it. Here's the basic syntax:
type variableName = value;
Examples:
int age = 25;
double price = 19.99;
boolean isStudent = true;
char grade = 'A';
String name = "Alice";
- Reusability: You can use the same value multiple times in your program.
- Readability: Using well-named variables makes your code easier to understand.
- Flexibility: You can easily change values in one place, affecting the entire program.
Now it's time to put your understanding of variables into practice! In this exercise, you'll create a simple program to catalog books in your personal library.
- Create variables to store information about three books. For each book, you should have:
- Title (String)
- Author (String)
- Publication Year (int)
- Number of Pages (int)
- Whether you've read it or not (boolean)
- Assign values to these variables for three different books.
- Use
System.out.println()
to display the information for each book in a formatted way. - Calculate and display some basic statistics:
- The total number of pages across all books
- The average publication year
Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.
These are used to perform common mathematical operations:
+
(Addition): Adds two values-
(Subtraction): Subtracts the right-hand operand from the left-hand operand*
(Multiplication): Multiplies two values/
(Division): Divides the left-hand operand by the right-hand operand%
(Modulus): Returns the remainder of a division operation
=
: Assigns a value to a variable
These perform an operation and assignment in one step:
+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign
These are used to compare two values:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
These are used to determine the logic between variables or values:
&&
: Logical AND||
: Logical OR!
: Logical NOT
Try to guess the output of these operations:
int result = 10 + 5 * 2;
boolean isAdult = (18 >= 18);
int x = 10; x += 5; x *= 2;
If statements are fundamental to programming as they allow your code to make decisions and execute different code blocks based on conditions.
if (condition) {
// code to be executed if the condition is true
}
Example:
int temperature = 25;
if (temperature > 30) {
System.out.println("It's a hot day!");
}
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
int temperature = 25;
if (temperature > 30) {
System.out.println("It's a hot day!");
} else {
System.out.println("It's not too hot today.");
}
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example:
int temperature = 25;
if (temperature > 30) {
System.out.println("It's a hot day!");
} else if (temperature > 20) {
System.out.println("It's a nice day.");
} else {
System.out.println("It's a bit chilly.");
}
You can also place if statements inside other if statements. This is called nesting.
Example:
boolean isWeekend = true;
boolean isRaining = false;
if (isWeekend) {
if (isRaining) {
System.out.println("Let's stay home and watch a movie.");
} else {
System.out.println("Let's go for a picnic!");
}
} else {
System.out.println("It's a work day.");
}
Let's create a program that assigns letter grades based on numerical scores.
- Create a program that takes a numerical grade (0-100) and prints the corresponding letter grade.
- Use the following grading scale:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
- The program should also handle invalid grades (below 0 or above 100).
Loops are fundamental programming constructs that allow you to repeat a block of code multiple times. They're essential for efficient programming and are particularly useful when working with collections of data.
Loops help you:
- Automate repetitive tasks
- Process collections of data efficiently
- Implement algorithms that require repeated operations
-
for Loop: Used when you know in advance how many times you want to repeat a block of code.
for (initialization; condition; update) { // code to be repeated }
-
while Loop: Used when you want to repeat a block of code as long as a condition is true.
while (condition) { // code to be repeated }
-
do-while Loop: Similar to while loop, but guarantees that the code block is executed at least once.
do { // code to be repeated } while (condition);
Java provides statements to control the flow of loops:
break
: Exits the loop immediatelycontinue
: Skips the rest of the current iteration and moves to the next one
Let's create a program that generates a multiplication table to practice using loops.
- Create a program that prints out a multiplication table for numbers 1 through 5.
- Use nested loops to generate the table.
- The output should look something like this:
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
An array is a container that holds a fixed number of values of a single type. Think of an array as a row of boxes, where each box can hold an item of a specific type (like integers, strings, etc.).
Arrays allow you to store multiple items of the same type under a single variable name. This makes it easier to:
- Group related data together
- Perform operations on multiple values efficiently
- Organize and manage large sets of data
In Java, you can declare and initialize an array in several ways:
-
Declare an array without initializing:
int[] numbers; // Declares an array of integers
-
Declare and allocate memory for the array:
int[] numbers = new int[5]; // Creates an array that can hold 5 integers
-
Declare, allocate memory, and initialize the array:
int[] numbers = {1, 2, 3, 4, 5}; // Creates and initializes an array with 5 integers
Array elements are accessed using their index. In Java, array indices start at 0.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]); // Outputs: 10
System.out.println(numbers[2]); // Outputs: 30
You can change the value of an array element by assigning a new value to a specific index:
numbers[1] = 25; // Changes the second element (index 1) to 25
You can find out how many elements an array has using the length
property:
int arraySize = numbers.length; // arraySize will be 5
You can use loops to iterate through array elements:
-
Using a for loop:
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
-
Using an enhanced for loop (for-each loop):
for (int number : numbers) { System.out.println(number); }
-
Finding the sum of array elements:
int sum = 0; for (int number : numbers) { sum += number; }
-
Finding the largest element:
int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } }
In this exercise, you'll create a program that tracks daily temperatures for a week and performs some basic analysis.
- Create an array to store 7 daily temperature readings (as integers).
- Initialize the array with temperature values for a week.
- Calculate and print the average temperature.
- Find and print the highest and lowest temperatures of the week.
- Count how many days were above average temperature.
Strings are fundamental in Java for handling text. Java provides a rich set of methods to manipulate and analyze strings efficiently.
String methods allow you to:
- Modify and transform text
- Extract information from strings
- Compare and search within strings
- Perform various text-processing tasks
Here are some of the most frequently used String methods in Java:
-
length(): Returns the length of the string.
String str = "Hello"; int length = str.length(); // length is 5
-
charAt(int index): Returns the character at the specified index.
char ch = str.charAt(1); // ch is 'e'
-
substring(int beginIndex, int endIndex): Extracts a portion of the string.
String sub = str.substring(1, 4); // sub is "ell"
-
toLowerCase() and toUpperCase(): Converts all characters to lower or upper case.
String lower = str.toLowerCase(); // lower is "hello" String upper = str.toUpperCase(); // upper is "HELLO"
-
trim(): Removes leading and trailing whitespace.
String trimmed = " Hello ".trim(); // trimmed is "Hello"
-
replace(char oldChar, char newChar): Replaces all occurrences of a character.
String replaced = str.replace('l', 'x'); // replaced is "Hexxo"
-
startsWith(String prefix) and endsWith(String suffix): Checks if the string starts or ends with the given text.
boolean starts = str.startsWith("He"); // true boolean ends = str.endsWith("lo"); // true
-
contains(CharSequence s): Checks if the string contains the specified sequence of characters.
boolean contains = str.contains("ell"); // true
-
split(String regex): Splits the string around matches of the given regular expression.
String[] parts = "Hello,World".split(","); // parts is ["Hello", "World"]
-
equals(Object obj): Compares this string to another object.
boolean isEqual = str.equals("Hello"); // true
Strings in Java are immutable, which means once a String object is created, it cannot be changed. Methods like replace()
or toUpperCase()
don't modify the original string; instead, they return a new string with the requested changes.
Think of a String like a word carved in stone. You can't change the carving, but you can make a new stone with a modified version of the word.
Let's create a program that analyzes names using various String methods.
- Create a program that takes a full name (first name and last name) as a single string.
- The program should:
- Print the length of the full name
- Extract and print the first name
- Extract and print the last name
- Print the initials (first letter of first name + first letter of last name)
- Check if the name contains the letter 'a' (case insensitive)
- Print the name in all uppercase
public class NameAnalyzer {
public static void main(String[] args) {
String fullName = "John Doe"; // You can change this to test different names
// Your code goes here
// Use various String methods to analyze the name
// Print the results of your analysis
}
}
- Handle middle names (extract middle name or middle initial)
- Reverse the full name
- Count the number of vowels in the name
Congratulations! You've completed the lesson. Here's what you've learned:
- Basic programming concepts and Java syntax
- Variables and data types
- Operators and expressions
- Control flow with if statements and loops
- Working with arrays
- String manipulation
Remember, programming is like learning a new language or a musical instrument - it takes practice! Don't be discouraged if you don't understand everything right away. Keep coding, experimenting, and building small projects to reinforce what you've learned.
- JDK: Java Development Kit
- IDE: Integrated Development Environment
- Variable: A container for storing data values
- Data Type: Specifies the type of data that a variable can hold
- Operator: A symbol that tells the compiler to perform specific mathematical or logical manipulations
- Control Flow: The order in which individual statements, instructions, or function calls are executed or evaluated
- Array: A container object that holds a fixed number of values of a single type
- String: A sequence of characters
- Loop: A programming construct that repeats a group of commands
- Conditional Statement: A feature of coding that performs different computations or actions depending on whether a programmer-specified condition evaluates to true or false