Java Programming Step 3
Java Operators and Input/Output
Introduction
Java Operators and Input/Output are essential concepts for every Java programmer. Operators allow you to perform calculations, compare values, assign data, and create logical conditions. Input and output allow your programs to communicate with users by receiving information and displaying results.
In this Step 3 Java Programming Tutorial, you will learn Java arithmetic operators, assignment operators, relational operators, logical operators, unary operators, increment and decrement operators, ternary operators, operator precedence, type promotion, user input with Scanner, formatted output, and practical Java programs.
This lesson continues from Step 2: Java Variables and Data Types.
What You Will Learn
After completing this lesson, you will understand:
- What operators are
- Arithmetic operators
- Assignment operators
- Compound assignment operators
- Relational operators
- Equality operators
- Logical operators
- Unary operators
- Increment and decrement
- Ternary operator
- Bitwise operators
- Shift operators
- Operator precedence
- Parentheses and expressions
- Type promotion
- Java input
Scannerclass- Reading integers
- Reading decimal numbers
- Reading strings
- Reading characters
- Boolean input
- Java output
print()println()printf()- Escape sequences
- Practical programs
- Exercises
- Mini project
What Are Operators in Java?
An operator is a symbol or construct that tells Java to perform an operation on one or more values.
For example:
int result = 10 + 5;
Here:
10is an operand.5is an operand.+is the operator.resultstores the result.
The output is:
15
Operators are essential for calculations, comparisons, assignments, and decision-making.
Types of Operators in Java
Java provides several categories of operators.
Main operator categories
- Arithmetic operators
- Assignment operators
- Relational operators
- Equality operators
- Logical operators
- Unary operators
- Increment and decrement operators
- Ternary operator
- Bitwise operators
- Shift operators
Let's learn each category step by step.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder |
Example:
int a = 20;
int b = 6;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
Output:
26
14
120
3
2
Notice that 20 / 6 produces 3 because both operands are integers.
Addition Operator +
The + operator adds numeric values.
int a = 10;
int b = 20;
int result = a + b;
System.out.println(result);
Output:
30
The + operator can also concatenate strings.
String firstName = "Jitu";
String lastName = "Hasan";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output:
Jitu HasanSubtraction Operator -
The - operator subtracts one value from another.
int a = 50;
int b = 20;
int result = a - b;
System.out.println(result);
Output:
30Multiplication Operator *
The * operator performs multiplication.
int price = 500;
int quantity = 3;
int total = price * quantity;
System.out.println(total);
Output:
1500Division Operator /
The / operator performs division.
int a = 20;
int b = 4;
System.out.println(a / b);
Output:
5Integer Division
When both operands are integers:
int result = 10 / 3;
The result is:
3
The decimal portion is not retained.
To perform floating-point division:
double result = 10.0 / 3;
System.out.println(result);
Output will be approximately:
3.3333333333333335Modulus Operator %
The % operator returns the remainder after division.
int remainder = 17 % 5;
System.out.println(remainder);
Output:
2
The modulus operator is commonly used to determine whether a number is even or odd.
int number = 10; if (number % 2 == 0) { System.out.println("Even");}
2. Assignment Operator =
The assignment operator assigns a value to a variable.
int age = 25;
Here:
=
assigns 25 to age.
You can change the value:
age = 30;Compound Assignment Operators
Java provides shorthand assignment operators.
Operator | Example | Equivalent |
|---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
Example:
int score = 50;
score += 10;
System.out.println(score);
Output:
603. Relational Operators
Relational operators compare values.
They produce a boolean result:
true
or:
false
| Operator | Meaning |
|---|---|
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example:
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);
Output:
true false truefalse
4. Equality Operators
Java provides two equality operators:
== !===
Checks whether two values are equal.
int a = 10;
int b = 10;
System.out.println(a == b);
Output:
true
!=
Checks whether two values are not equal.
int a = 10;
int b = 20;
System.out.println(a != b);
Output:
true
Important: == and Strings
For objects such as String, == compares references rather than string content.
For comparing String contents, use:
String a = "Java";
String b = "Java";
System.out.println(a.equals(b));
Output:
true
We will study String comparison in more detail later.
5. Logical Operators
Logical operators are used to combine boolean expressions.
Logical AND &&
The && operator returns true only when both conditions are true.
int age = 25;
boolean citizen = true;
if (age >= 18 && citizen) {
System.out.println("Eligible");
}
Both conditions must be true.
Logical OR ||
The || operator returns true when at least one condition is true.
boolean hasEmail = false;
boolean hasPhone = true;
if (hasEmail || hasPhone) {
System.out.println("Contact available");
}
Output:
Contact available
Java's && and || operators use short-circuit evaluation.
Logical NOT !
The ! operator reverses a boolean value.
boolean loggedIn = false;
System.out.println(!loggedIn);
Output:
true6. Unary Operators
Unary operators work with one operand.
Examples include:
+
-
!
~
++
--
Example:
int number = 10;
System.out.println(-number);
Output:
-107. Increment Operator ++
The ++ operator increases a value by one.
int count = 5;
count++;
System.out.println(count);
Output:
6
It is equivalent to:
count = count + 1;Decrement Operator --
The -- operator decreases a value by one.
int count = 5;
count--;
System.out.println(count);
Output:
4
It is equivalent to:
count = count - 1;Prefix and Postfix Operators
Increment and decrement operators can be used before or after a variable.
Postfix
int x = 5;
int result = x++;
System.out.println(result);
System.out.println(x);
Output:
5
6
The original value is used first, then x is increased.
Prefix
int x = 5;
int result = ++x;
System.out.println(result);
System.out.println(x);
Output:
6
6
The value is increased first, then used.
8. Ternary Operator
The ternary operator provides a compact way to choose between two expressions.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
int age = 20;
String result = age >= 18 ? "Adult" : "Minor";
System.out.println(result);
Output:
Adult
It can be useful for simple conditional assignments.
9. Bitwise Operators
Bitwise operators work at the bit level for integral types.
Important operators include:
&
|
^
~
Example:
int a = 5;
int b = 3;
System.out.println(a & b);
System.out.println(a | b);
System.out.println(a ^ b);
Bitwise operations are particularly useful in areas such as:
- Low-level programming
- Flags
- Binary data processing
- Performance-sensitive code
- Algorithms
10. Shift Operators
Java provides shift operators:
<<
>>
>>>Left Shift <<
int number = 4;
System.out.println(number << 1);
Output:
8
Signed Right Shift >>
int number = 8;
System.out.println(number >> 1);
Output:
4
Unsigned Right Shift >>>
The >>> operator shifts bits to the right and fills the leftmost positions with zeros.
These operators are advanced topics and will become more useful when studying binary operations.
Operator Precedence
When an expression contains multiple operators, Java follows operator precedence rules.
Example:
int result = 10 + 5 * 2;
The multiplication is performed before addition.
Therefore:
5 × 2 = 10
10 + 10 = 20
Result:
20Using Parentheses
Parentheses can be used to control the order of evaluation.
int result = (10 + 5) * 2;
System.out.println(result);
Output:
30
Without parentheses:
int result = 10 + 5 * 2;
Output:
20
Best Practice
When an expression could be confusing, use parentheses to make your intention clear.
Type Promotion in Expressions
Java may promote smaller numeric types when evaluating expressions.
For example:
byte a = 10;
byte b = 20;
int result = a + b;
The result of the arithmetic expression is an int.
This is an important rule to understand when working with byte, short, and char.
Division by Zero
Be careful with division by zero.
For integer arithmetic:
int result = 10 / 0;causes an ArithmeticException at runtime.
For floating-point arithmetic:
double result = 10.0 / 0.0;
the result follows IEEE 754 floating-point rules and produces positive infinity rather than an integer-style division exception.
What Is Input and Output?
Input means receiving data from a user or another source.
Output means displaying or sending information.
A simple program might:
User enters name ↓ Java program receives input ↓ Java processes the input ↓Java displays output
Java Output
Java provides several ways to display output.
The most commonly used are:
System.out.print() System.out.println()System.out.printf()
System.out.print()
print() displays text without automatically moving to the next line.
System.out.print("Hello ");
System.out.print("Java");
Output:
Hello JavaSystem.out.println()
println() displays text and then moves to the next line.
System.out.println("Hello");
System.out.println("Java");
Output:
Hello
JavaSystem.out.printf()
printf() is useful for formatted output.
Example:
String name = "Rahim";
int age = 25;
System.out.printf("Name: %s, Age: %d%n", name, age);
Output:
Name: Rahim, Age: 25
Common format specifiers include:
| Specifier | Purpose |
|---|---|
%d | Integer |
%f | Floating-point value |
%s | String |
%c | Character |
%b | Boolean |
%n | Platform-independent line separator |
Formatting Decimal Values
You can control the number of decimal places using printf().
double price = 99.56789;
System.out.printf("%.2f%n", price);
Output:
99.57
Here:
%.2f
means a floating-point value displayed with two digits after the decimal point.
Escape Sequences
Escape sequences allow you to insert special characters into strings.
New Line
System.out.println("Hello\nJava");
Output:
Hello
Java
Tab
System.out.println("Name:\tJitu");
Double Quote
System.out.println("He said \"Hello\"");
Backslash
System.out.println("C:\\Java\\Programs");
Common escape sequences:
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\' | Single quote |
\\ | Backslash |
Taking Input in Java
Java provides several ways to receive input.
For beginner console applications, the Scanner class is one of the easiest approaches.
Import it:
import java.util.Scanner;
Then create a Scanner object:
Scanner input = new Scanner(System.in);Reading an Integer
Use:
nextInt()
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("Your age is: " + age);
input.close();
}
}
Example interaction:
Enter your age: 20
Your age is: 20Reading a Double
Use:
nextDouble()
Example:
double price = input.nextDouble();
Complete example:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter price: "); double price = input.nextDouble(); System.out.println("Price: " + price); input.close(); }}
Reading a String
There are two commonly used methods.
next()
Reads the next token, stopping at whitespace.
String name = input.next();
If the user enters:
Jitu Hasan
next() reads only:
Jitu
nextLine()
Reads the complete line.
String name = input.nextLine();
For example:
Jitu Hasan
is read as the complete string.
Reading a Character
Scanner does not provide a direct nextChar() method.
A common approach is:
char grade = input.next().charAt(0);
Example:
System.out.print("Enter grade: ");
char grade = input.next().charAt(0);
System.out.println("Grade: " + grade);
If the user enters:
A
the program stores A.
Reading Boolean Input
You can use:
nextBoolean()
Example:
System.out.print("Are you a student? ");
boolean student = input.nextBoolean();
System.out.println("Student: " + student);
The expected input is normally:
true
or:
falseImportant Scanner Issue: nextInt() and nextLine()
A common beginner problem occurs when using nextInt() followed immediately by nextLine().
Example:
int age = input.nextInt();
String name = input.nextLine();
After nextInt(), the newline remains in the input buffer, so nextLine() may immediately consume the remaining line break.
A common solution is:
int age = input.nextInt();
input.nextLine();
String name = input.nextLine();
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter age: ");
int age = input.nextInt();
input.nextLine();
System.out.print("Enter full name: ");
String name = input.nextLine();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
input.close();
}
}
Understanding this behavior will prevent many beginner input errors.
Complete Input/Output Example
Let's combine different input types.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); String name = input.nextLine(); System.out.print("Enter your age: "); int age = input.nextInt(); System.out.print("Enter your CGPA: "); double cgpa = input.nextDouble(); System.out.print("Are you a student? "); boolean student = input.nextBoolean(); System.out.println(); System.out.println("===== Student Information ====="); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("CGPA: " + cgpa); System.out.println("Student: " + student); input.close(); }}
Practical Program – Add Two Numbers
Let's create a program that receives two numbers and adds them.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = input.nextDouble();
System.out.print("Enter second number: ");
double second = input.nextDouble();
double sum = first + second;
System.out.println("Sum = " + sum);
input.close();
}
}
Example:
Enter first number: 25
Enter second number: 15
Sum = 40.0
Practical Program
Basic Calculator
Now let's use arithmetic operators and user input together.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double a = input.nextDouble();
System.out.print("Enter second number: ");
double b = input.nextDouble();
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
if (b != 0) {
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));
} else {
System.out.println("Division by zero is not allowed.");
}
input.close();
}
}
This program demonstrates:
Scanner- Variables
- Arithmetic operators
- Division
- Modulus
- Conditional checking
- Output
Even or Odd
The modulus operator is very useful for checking whether a number is even or odd.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int number = input.nextInt(); if (number % 2 == 0) { System.out.println("The number is even."); } else { System.out.println("The number is odd."); } input.close(); }}
Age Eligibility
Let's use relational and logical operators.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your age: "); int age = input.nextInt(); if (age >= 18 && age <= 60) { System.out.println("You are within the specified age range."); } else { System.out.println("You are outside the specified age range."); } input.close(); }}
Student Result
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter student name: "); String name = input.nextLine(); System.out.print("Enter marks: "); double marks = input.nextDouble(); boolean passed = marks >= 40; System.out.println(); System.out.println("===== RESULT ====="); System.out.println("Name: " + name); System.out.println("Marks: " + marks); System.out.println("Passed: " + passed); input.close(); }}
Simple Bill
Let's build a simple shopping bill.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter product name: "); String product = input.nextLine(); System.out.print("Enter price: "); double price = input.nextDouble(); System.out.print("Enter quantity: "); int quantity = input.nextInt(); double subtotal = price * quantity; System.out.println(); System.out.println("=============================="); System.out.println(" SHOPPING BILL"); System.out.println("=============================="); System.out.println("Product: " + product); System.out.printf("Price: %.2f%n", price); System.out.println("Quantity: " + quantity); System.out.printf("Subtotal: %.2f%n", subtotal); System.out.println("=============================="); input.close(); }}
Practice Exercises
Now practice the concepts yourself.
Exercise 1 – Calculator
Ask the user for two numbers and display:
- Addition
- Subtraction
- Multiplication
- Division
- Remainder
Exercise 2 – Even or Odd
Ask the user for an integer and determine whether it is even or odd.
Exercise 3 – Positive or Negative
Ask the user for a number and determine whether it is:
- Positive
- Negative
- Zero
Exercise 4 – Age Check
Ask for the user's age.
Display whether the user is:
Adult
or:
MinorExercise 5 – Student Information
Ask the user for:
- Name
- Age
- Marks
- Grade
Then display all information.
Exercise 6 – Rectangle Calculator
Ask the user for:
- Length
- Width
Calculate:
Area = length × width
and:
Perimeter = 2 × (length + width)Challenge Exercise – BMI Calculator
Create a program that asks the user for:
Weight in kilograms
Height in meters
Calculate:
BMI = weight / (height × height)
Display the BMI with two decimal places.
Example:
Enter weight: 70
Enter height: 1.75
BMI: 22.86
Mini Project – Student Grade Calculator
Let's combine variables, operators, input, output, and conditional logic.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = input.nextLine();
System.out.print("Enter marks for Java: ");
double javaMarks = input.nextDouble();
System.out.print("Enter marks for Programming: ");
double programmingMarks = input.nextDouble();
System.out.print("Enter marks for Database: ");
double databaseMarks = input.nextDouble();
double total = javaMarks + programmingMarks + databaseMarks;
double average = total / 3;
String grade;
if (average >= 80) {
grade = "A+";
} else if (average >= 70) {
grade = "A";
} else if (average >= 60) {
grade = "B";
} else if (average >= 50) {
grade = "C";
} else if (average >= 40) {
grade = "D";
} else {
grade = "F";
}
System.out.println();
System.out.println("==============================");
System.out.println(" STUDENT RESULT");
System.out.println("==============================");
System.out.println("Name: " + name);
System.out.printf("Total Marks: %.2f%n", total);
System.out.printf("Average: %.2f%n", average);
System.out.println("Grade: " + grade);
System.out.println("==============================");
input.close();
}
}
This project combines several important concepts that you have learned so far.
Common Beginner Mistakes
Mistake 1: Using = Instead of ==
Incorrect:
if (age = 18)
Correct:
if (age == 18)
= is assignment.
== is equality comparison for primitive values.
Mistake 2: Forgetting Integer Division
int result = 5 / 2;
Result:
2
For decimal division:
double result = 5.0 / 2;
Result:
2.5Mistake 3: Forgetting Parentheses
This:
int result = 10 + 5 * 2;
is not the same as:
int result = (10 + 5) * 2;
Use parentheses when necessary to make the intended calculation clear.
Mistake 4: Comparing Strings with ==
Avoid:
name == "Jitu"
for checking String content.
Use:
name.equals("Jitu")
instead.
Mistake 5: nextInt() Followed by nextLine()
Remember:
input.nextInt();
input.nextLine();
The extra nextLine() consumes the remaining newline before reading the next full line.
Mistake 6: Division by Zero
Avoid:
int result = 10 / 0;
Check the divisor before integer division when zero is possible.
Quick Revision
| Concept | Key Point | ||
|---|---|---|---|
+ | Addition or String concatenation | ||
- | Subtraction | ||
* | Multiplication | ||
/ | Division | ||
% | Remainder | ||
= | Assignment | ||
== | Equality comparison | ||
!= | Not equal | ||
> | Greater than | ||
< | Less than | ||
>= | Greater than or equal | ||
<= | Less than or equal | ||
&& | Logical AND | ||
| ` | Logical OR | ||
! | Logical NOT | ||
++ | Increment | ||
-- | Decrement | ||
?: | Ternary conditional operator | ||
& | Bitwise AND | ||
| ` | Bitwise OR | ||
^ | Bitwise XOR | ||
<< | Left shift | ||
>> | Signed right shift | ||
>>> | Unsigned right shift | ||
print() | Prints without automatic newline | ||
println() | Prints with newline | ||
printf() | Formatted output | ||
Scanner | Common console input class |
What You Should Know Before Step 4
Before moving to the next lesson, make sure you can:
- Explain what a Java operator is.
- Use arithmetic operators.
- Use assignment and compound assignment operators.
- Compare numeric values.
- Use equality operators.
- Use logical AND, OR, and NOT.
- Use increment and decrement.
- Understand prefix and postfix operators.
- Use the ternary operator.
- Understand basic bitwise and shift operators.
- Understand operator precedence.
- Use parentheses in expressions.
- Understand integer division.
- Understand basic numeric type promotion.
- Print output using
print(). - Print output using
println(). - Format output using
printf(). - Use escape sequences.
- Create a
Scannerobject. - Read integers and decimal values.
- Read complete lines.
- Understand the
nextInt()/nextLine()issue. - Build simple interactive programs.
Conclusion
Operators and Input/Output are two of the most important foundations of Java programming.
Operators allow you to perform calculations, compare values, create logical expressions, manipulate bits, and assign data. Input and output allow your programs to interact with users by accepting information and displaying useful results.
By completing this lesson, you can now build interactive Java programs instead of programs that only display fixed text.
Continue practicing the examples and exercises. Try changing the values, adding new calculations, and creating your own small programs.
Next Lesson
Step 4: Java Conditional Statements – if, else, else-if, Nested if and switch
In the next lesson, you will learn how to make decisions in Java programs using conditions and control flow.

Post a Comment
Thank You For Visit My Website.
I Will Contact As Soon As Possible.