Java Fundamentals
Learn the basic building blocks of Java programming, including variables, data types, operators, user input, conditions and loops. Every concept is explained in simple language with easy examples so that even an 8th-grade student can understand it.
What Will You Learn in This Module?
In the previous module, you learned what Java is, how it works, and how to write your first Java program.
Now, it is time to learn how to write programs that can store information, perform calculations, take input from users, make decisions and repeat tasks.
Think of a Java program as a set of instructions given to a computer. In this module, you will learn the basic tools needed to create those instructions.
Learning Objectives
After completing this module, you will be able to:
- Understand variables and constants.
- Identify different data types in Java.
- Convert one data type into another.
- Perform calculations using Java operators.
- Take input from users using the Scanner class.
- Make decisions using conditional statements.
- Use switch statements to select between multiple options.
- Repeat instructions using loops.
- Control loops using break and continue.
1. Variables and Constants in Java
What is a Variable?
A variable is a named memory location used to store information in a program. You can think of a variable as a box in which you keep something.
For example, imagine you have a box named age and you put the number 20 inside it. In Java, we can create a variable named age to store the value 20.
Real-Life Example
Imagine a school register. Each student has a name, age and roll number. These details can be stored in separate variables in a Java program.
How to Declare a Variable?
The basic syntax is:
dataType variableName = value;
Example:
public class Main {
public static void main(String[] args) {
int age = 20;
String name = "Rahul";
System.out.println(name);
System.out.println(age);
}
}
Understanding the Code
- int is the data type used to store whole numbers.
- age is the variable name.
- 20 is the value stored in the variable.
- String is used to store text.
- name is another variable.
Changing a Variable's Value
The value of a variable can be changed while the program is running.
public class Main {
public static void main(String[] args) {
int marks = 70;
System.out.println(marks);
marks = 90;
System.out.println(marks);
}
}
What is a Constant?
A constant is a value that cannot be changed after it has been assigned.
In Java, we use the final keyword to create constants.
public class Main {
public static void main(String[] args) {
final double PI = 3.14;
System.out.println(PI);
}
}
2. Data Types in Java
What is a Data Type?
A data type tells Java what kind of value a variable can store. For example, a person's age is a whole number, while a person's name is text.
Java provides different data types for storing different kinds of information.
Types of Data Types
Java data types are mainly divided into two categories:
- Primitive Data Types
- Non-Primitive Data Types
Primitive Data Types
Primitive data types are the basic data types already provided by Java.
| Data Type | Used For | Example |
|---|---|---|
| byte | Small whole numbers | byte age = 20; |
| short | Whole numbers | short marks = 300; |
| int | Integer values | int salary = 30000; |
| long | Very large whole numbers | long population = 9000000L; |
| float | Decimal values | float price = 25.5f; |
| double | More precise decimal values | double pi = 3.14159; |
| char | A single character | char grade = 'A'; |
| boolean | True or false values | boolean passed = true; |
Non-Primitive Data Types
Non-primitive data types are used to store more complex information. They include classes, objects, arrays and strings.
Example
A String can store a person's name, while an array can store marks of multiple students.
public class Main {
public static void main(String[] args) {
int age = 18;
double percentage = 85.5;
char grade = 'A';
boolean passed = true;
String name = "Aman";
System.out.println(name);
System.out.println(age);
System.out.println(percentage);
System.out.println(grade);
System.out.println(passed);
}
}
3. Type Casting and Type Conversion
What is Type Conversion?
Type conversion means changing a value from one data type into another data type.
For example, sometimes we may want to convert an integer into a decimal number.
1. Widening Casting
Widening casting means converting a smaller data type into a larger data type. Java performs this conversion automatically in compatible cases.
Example: int to double.
public class Main {
public static void main(String[] args) {
int number = 25;
double result = number;
System.out.println(result);
}
}
2. Narrowing Casting
Narrowing casting means converting a larger data type into a smaller data type. In Java, we generally need to perform this conversion manually.
Example: double to int.
public class Main {
public static void main(String[] args) {
double number = 25.75;
int result = (int) number;
System.out.println(result);
}
}
Notice that the decimal part is removed when a double is converted to an int.
| Type of Casting | Meaning | Example |
|---|---|---|
| Widening | Smaller type to larger compatible type | int to double |
| Narrowing | Larger type to smaller type | double to int |
4. Operators in Java
What are Operators?
Operators are special symbols used to perform operations on values and variables.
For example, the plus symbol (+) is used to add two numbers.
1. Arithmetic Operators
These operators are used for mathematical calculations.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 5 | 15 |
| - | Subtraction | 10 - 5 | 5 |
| * | Multiplication | 10 * 5 | 50 |
| / | Division | 10 / 5 | 2 |
| % | Remainder | 10 % 3 | 1 |
2. Relational Operators
Relational operators compare two values. Their result is either true or false.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | 10 == 10 |
| != | Not equal to | 10 != 5 |
| > | Greater than | 10 > 5 |
| < | Less than | 5 < 10 |
| >= | Greater than or equal to | 10 >= 10 |
| <= | Less than or equal to | 5 <= 10 |
3. Logical Operators
Logical operators combine conditions or reverse a condition.
| Operator | Meaning | Example |
|---|---|---|
| && | AND – both conditions must be true | age >= 18 && age <= 60 |
| || | OR – at least one condition must be true | marks > 90 || grade == 'A' |
| ! | NOT – reverses a boolean value | !isPassed |
4. Assignment Operators
Assignment operators are used to assign or update values.
| Operator | Example | Same As |
|---|---|---|
| = | x = 10 | Assign 10 to x |
| += | x += 5 | x = x + 5 |
| -= | x -= 5 | x = x - 5 |
| *= | x *= 5 | x = x * 5 |
| /= | x /= 5 | x = x / 5 |
5. Increment and Decrement Operators
The increment operator (++) increases a value by 1. The decrement operator (--) decreases a value by 1.
public class Main {
public static void main(String[] args) {
int number = 10;
number++;
System.out.println(number);
number--;
System.out.println(number);
}
}
Example: Using Arithmetic Operators
public class Main {
public static void main(String[] args) {
int a = 20;
int b = 10;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % 3);
}
}
5. Taking User Input Using Scanner
Why Do We Need User Input?
Until now, we have stored values directly inside our programs. But in real applications, we often want users to enter their own information.
For example, a calculator should allow users to enter two numbers instead of always using fixed numbers.
What is Scanner?
Scanner is a Java class that helps us take input from the user. To use it, we first need to import it from the java.util package.
Steps to Take User Input
- Import the Scanner class.
- Create a Scanner object.
- Use an appropriate method to read the input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
sc.close();
}
}
Common Scanner Methods
| Method | Purpose | Example |
|---|---|---|
| nextInt() | Reads an integer | sc.nextInt() |
| nextDouble() | Reads a decimal number | sc.nextDouble() |
| nextFloat() | Reads a float value | sc.nextFloat() |
| next() | Reads one word | sc.next() |
| nextLine() | Reads a complete line of text | sc.nextLine() |
| nextBoolean() | Reads true or false | sc.nextBoolean() |
Example: Adding Two Numbers Entered by the User
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
int sum = a + b;
System.out.println("Sum = " + sum);
sc.close();
}
}
6. Conditional Statements in Java
What are Conditional Statements?
Conditional statements allow a program to make decisions. They execute different instructions depending on whether a condition is true or false.
Real-Life Example
Imagine that you want to enter a movie theatre. If your age is 18 or above, you are allowed to watch an adult movie. Otherwise, you are not allowed.
This is an example of decision-making using a condition.
1. if Statement
The if statement executes a block of code only when its condition is true.
public class Main {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}
2. if-else Statement
The if-else statement is used when we have two possible outcomes. If the condition is true, the if block executes. Otherwise, the else block executes.
public class Main {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
}
}
3. if-else-if Ladder
The if-else-if ladder is used when we need to check multiple conditions one after another.
public class Main {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}
4. Nested if Statement
A nested if means writing one if statement inside another if statement.
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
} else {
System.out.println("ID required");
}
} else {
System.out.println("Entry not allowed");
}
}
}
7. Switch Statement in Java
What is a Switch Statement?
A switch statement is used when we want to select one option from multiple possible choices.
For example, a menu may contain options such as 1 for Tea, 2 for Coffee and 3 for Juice. A switch statement can execute the code for the selected option.
Syntax of Switch
switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Code if no case matches
}
Example: Day Selection
public class Main {
public static void main(String[] args) {
int day = 2;
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");
}
}
}
Understanding Important Keywords
- case: Defines a possible matching value.
- break: Stops execution of the switch after a matching case has run.
- default: Runs when no case matches.
When Should You Use Switch?
Use switch when you are comparing one expression against several fixed choices. Use if-else when conditions involve ranges or more complex comparisons.
8. Loops in Java – for, while and do-while
What is a Loop?
A loop is used to execute the same block of code repeatedly. Instead of writing the same instruction many times, we can use a loop.
Real-Life Example
Imagine writing numbers from 1 to 100 in your notebook. Writing each number separately would take a lot of time. A loop can repeat the same instruction and print all the numbers automatically.
1. for Loop
A for loop is commonly used when we know how many times we want to repeat an instruction.
Syntax:
for (initialization; condition; update) {
// Code to repeat
}
Example: Print Numbers from 1 to 5
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
2. while Loop
A while loop repeats a block of code as long as its condition remains true.
It is useful when we do not know exactly how many times the loop needs to run.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
3. do-while Loop
A do-while loop executes the code at least once before checking the condition.
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Difference Between for, while and do-while
| Loop | When to Use | Condition Check |
|---|---|---|
| for | When the number of repetitions is known | Before execution |
| while | When repetitions depend on a condition | Before execution |
| do-while | When the code must execute at least once | After execution |
Example: Sum of Numbers from 1 to 5
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println("Sum = " + sum);
}
}
9. Break and Continue Statements
What is the break Statement?
The break statement is used to stop a loop immediately. Once break is executed, the program comes out of that loop.
Example: Stop the Loop at 3
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
}
}
When i becomes 3, the break statement stops the loop. Therefore, 3, 4 and 5 are not printed.
What is the continue Statement?
The continue statement skips the current iteration and moves to the next iteration of the loop.
Example: Skip Number 3
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
}
}
When i becomes 3, continue skips the print statement for that iteration. The loop then continues with 4 and 5.
Difference Between break and continue
| break | continue |
|---|---|
| Stops the entire loop. | Skips only the current iteration. |
| Control moves outside the loop. | Control moves to the next iteration. |
| Used when we want to stop repeating. | Used when we want to skip a particular case. |
Module 2 Summary – Java Fundamentals
In this module, you learned the basic building blocks of Java:
- Variables: Store values in a program.
- Constants: Store values that cannot be reassigned.
- Data Types: Define the kind of value a variable can store.
- Type Casting: Convert values from one data type to another.
- Operators: Perform calculations and comparisons.
- Scanner: Take input from users.
- Conditional Statements: Make decisions in a program.
- Switch: Select an option from multiple choices.
- Loops: Repeat instructions.
- Break and Continue: Control loop execution.
These concepts are used in almost every Java program. Make sure you understand them before moving to the next module.
Practice Questions
Try solving these beginner-friendly Java programming questions:
- Create a variable to store your name, age and percentage. Print all three values.
- Declare a constant to store the value of PI.
- Write a program to convert an int value into a double.
- Write a program to convert a double value into an int.
- Take two numbers from the user and print their sum, difference and product.
- Write a program to check whether a number is even or odd.
- Write a program to find the largest of two numbers.
- Write a program to check whether a student has passed or failed. Assume 40 marks are required to pass.
- Use a switch statement to print the name of a day based on its number.
- Print numbers from 1 to 10 using a for loop.
- Print numbers from 10 to 1 using a while loop.
- Find the sum of numbers from 1 to 100.
- Print all even numbers between 1 and 50.
- Use break to stop a loop when the number reaches 5.
- Use continue to skip the number 5 while printing numbers from 1 to 10.
Java Fundamentals – Interview Questions
1. What is a variable in Java?
A variable is a named memory location used to store data. Its value can change during program execution.
2. What is the difference between a variable and a constant?
A variable can be reassigned, whereas a constant declared using the final keyword cannot be reassigned.
3. How many primitive data types are available in Java?
Java has eight primitive data types: byte, short, int, long, float, double, char and boolean.
4. What is type casting?
Type casting means converting a value from one data type into another data type.
5. What is the difference between == and =?
The = operator assigns a value to a variable, while == compares two values for equality.
6. What is the use of the Scanner class?
Scanner is used to read input from the user, such as numbers and text.
7. What is the difference between if-else and switch?
if-else is useful for checking conditions and ranges, while switch is useful for selecting from multiple fixed choices.
8. What is the difference between while and do-while?
A while loop checks the condition before executing its body. A do-while loop executes its body first and then checks the condition.
9. What is an infinite loop?
An infinite loop is a loop that never stops because its condition never becomes false or it has no effective exit condition.
10. What is the difference between break and continue?
break terminates the loop, while continue skips the current iteration and moves to the next one.
Congratulations! Module 2 Completed
You have learned the fundamental concepts required to start writing Java programs independently.
Practice the programs and make sure you understand how variables, conditions and loops work.
In the next module, you will learn about Arrays and Strings in Java.