Introduction To Java Final
Introduction To Java Final
Filename: HelloWorld.java
Compile and Execute Java Program
➢Software Required
➢JDK 21 or later
➢ Java Development Toolkit
➢Java Compiler (javac.exe)
➢Java Interpreter (java.exe)
javac.exe
java.exe
javac.exe java.exe
Create a Program and Save as HelloWorld.java
class HelloWorld
{
public static void main(String[] args)
{
//to display output
System.out.println("Hello, World!");
}
}
Compile and Execute in Command Prompt
Variables
• A variable is a location in memory (storage area) to hold data.
• To indicate the storage area, each variable should be given a
unique name (identifier).
• The data types specify the type of data that can be stored
inside variables in Java.
• Java is a strongly typed language. This means that all variables
must be declared before they can be used.
Data Types in Java
Data Type Description Example
int Whole numbers int age = 21;
long population =
long Large whole number
7800000000L;
public class DataTypeExample {
public static void main(String[] args)
Example {
int age = 25;
double salary = 45800.75;
char gender = 'M';
boolean isEmployed = true;
String name = "John";
class TypeConversion
{
public static void main(String[] args)
{
double x = 12.56;
int y = (int) x; // double to int (data loss: decimal part removed)
System.out.println(y); // Output: 12
}
}
Predict the output
class TypeConversion
{
public static void main(String[] args)
{
double d = 45.78;
int i = (int) d;
System.out.println(i); Answer: C. 45
} A. 45.78
} B. 46
C. 45
D. Error
Conversion Between Primitive and String
class TypeConversion
{
public static void main(String[] args)
{
String str = "123";
int num = Integer.parseInt(str);
double d = Double.parseDouble("45.67");
}
}
Control Structures
• In the most basic sense, a program is a list of instructions.
• Control structures are programming blocks that can change the path we take
through those instructions.
• Conditional Statements
• Decision-making statements in Java execute a block of code based on a
condition.
• if, if-else, if-else-if, switch case, break and continue
• Loops
• Iterate through multiple values/objects and repeatedly run specific code
blocks.
• for loop, while loop, do while loop
if statement
if (condition)
{
// block of code to be executed if the condition is true
}
Example:-
• Example: A student gets a certificate of appreciation if their score in the quiz is a
perfect 10.
// Input quiz score
Scanner sc = new Scanner(System.in);
System.out.print("Enter your quiz score (out of 10): ");
int score = sc.nextInt();
• A college library allows students to borrow books for 7 days. If a book is returned after 7
days, a fine of ₹10 per day is applied.
• Write a Java program that checks the number of days a student kept the book and:
• If returned within 7 days, print "No fine. Thank you!"
• Else, calculate and display the fine: "You have a fine of ₹<amount>"
import java.util.Scanner;
public class LibraryFine
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Get number of days book was kept
System.out.print("Enter number of days you kept the book: ");
int days = sc.nextInt();
// Check if fine is applicable
if (days <= 7) {
System.out.println("No fine. Thank you!");
} else {
int lateDays = days - 7;
int fine = lateDays * 10; // ₹10 per day late
System.out.println("You have a fine of ₹" + fine);
}
}
}
if else if
• Use the else if statement to specify a new condition if the first condition
is false.
if (condition1)
{
// block of code to be executed if condition1 is true
} else if (condition2)
{
// block of code to be executed if the condition1 is
false and condition2 is true
} else {
// block of code to be executed if the condition1 is
false and condition2 is false
}
Exercise:-
• A student has written exams in Math, Physics, and Chemistry. You are asked to write a
program that:
• Takes the marks for all three subjects.
• Determines which subject has the highest score.
• Displays the subject with the highest mark.
import java.util.Scanner;
public class MainApplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input marks for three subjects
System.out.print("Enter Math marks: ");
int math = sc.nextInt();
System.out.print("Enter Physics marks: ");
int physics = sc.nextInt();
System.out.print("Enter Chemistry marks: ");
int chemistry = sc.nextInt();
// Find and display the subject with highest mark
if (math >= physics && math >= chemistry) {
System.out.println("Math has the highest score: " + math);
}
if (physics > math && physics >= chemistry) {
System.out.println("Physics has the highest score: " + physics);
}
if (chemistry > math && chemistry > physics) {
System.out.println("Chemistry has the highest score: " + chemistry);
}
}
}
Logical Operators
Switch Statement
• The switch statement is used to select one of many code blocks to
execute, based on the value of a variable.
switch (expression)
{
case value1:
// code block
break;
case value2:
// code block
break;
// more cases...
default:
// default code block
}
Example
• A store sells 5 different products, each identified by a unique product code (1 to 5) with a fixed unit
price.
Write a Java program that Prompts the user to enter a product code and quantity. Calculates
and displays the product name, unit price and total cost. If the product code is invalid, show
"Invalid product code."
import java.util.Scanner;
class Purchase {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the Product Code: ");
int productCode = sc.nextInt();
System.out.print("Enter the Quantity: ");
int quantity = sc.nextInt();
int totalcost=0;
switch(productCode){
case 1:
totalcost=10*quantity;
System.out.println("Product Name: Pen\nPrice:Rs.10\nTotal Cost:Rs."+totalcost);
break;
case 2:
totalcost=40*quantity;
System.out.println("Product Name: Notebook\nPrice:Rs.40\nTotal Cost:Rs."+totalcost);
break;
case 3:
totalcost=60*quantity;
System.out.println("Product Name: Water Bottle\nPrice:Rs.60\nTotal Cost:Rs."+totalcost);
break;
case 4:
totalcost=300*quantity;
System.out.println("Product Name: USB Drive\nPrice:Rs.300\nTotal Cost:Rs."+totalcost);
break;
default:
System.out.println("Invalid Code");
}
}
}
for loop
• Java for loop is a control flow statement that allows code to be executed
repeatedly based on a given condition.
• The for loop in Java provides an efficient way to iterate over a range of
values, execute code multiple times, or traverse arrays and collections.
A user is allowed 3 attempts to enter the correct 4-digit PIN for their ATM
card. If the user enters the wrong PIN three times, the account is locked.
If they enter it correctly within 3 attempts, they gain access.
import java.util.Scanner;
public class ATMAccess {
public static void main(String[] args) {
final int CORRECT_PIN = 1234; // preset correct PIN
final int MAX_ATTEMPTS = 3;
Scanner sc = new Scanner(System.in);
int attempts = 0;
boolean accessGranted = false;
while (attempts < MAX_ATTEMPTS) {
System.out.print("Enter your 4-digit PIN: ");
int enteredPIN = sc.nextInt();
attempts++;
if (enteredPIN == CORRECT_PIN) {
accessGranted = true;
break; // correct PIN, exit loop
} else {
System.out.println("Incorrect PIN. Attempts left: " + (MAX_ATTEMPTS - attempts));
}
}
if (accessGranted) {
System.out.println("Access Granted.");
} else {
System.out.println("Account Locked.");
}
}
}
Exercise
The system randomly selects a number between 1 to 100.
The user keeps guessing until they get it right. After each guess, display:
• “Too High”
• “Too Low”
• “Correct Guess!”
Develop a program that implements this guessing game.
import java.util.Random;
public class Test {
public static void main(String[] args) { Generate Random Number:
Random rand = new Random();
//Random integer from 1 to 100
int randomNum = rand.nextInt(100)+1;
}
}
do while loop
• The do-while loop is similar to the while loop, but the condition is
evaluated after the loop body. This guarantees that the loop body
executes at least once.
do
{
// code block to be executed
} while (condition);
Problem Statement
• Create a menu-based program for a restaurant where the customer can
select items repeatedly until they choose to exit. Your application must do
the following ----- Welcome to JavaBites Restaurant -----
1. Pizza - ₹150
• Display the menu 2. Burger - ₹100
3. Sandwich - ₹70
• Take the user's choice 4. Coffee - ₹50
0. Exit
• Add the item's price to the total Enter your choice:
(5,5)
Nested for loop
• A nested for loop in Java means a for loop inside another for loop. It is
commonly used for working with 2D data structures like matrices,
patterns, or nested iterations.
for (int i = 0; i < outerLimit; i++)
{
for (int j = 0; j < innerLimit; j++)
{
// Code to execute
}
}
Nested for Loop
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print("* ");
}
System.out.println();
}
Nested for Loop
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
System.out.print("* ");
}
System.out.println();
}
break with label
• In Java, the break statement with a label allows you to break out of nested loops or blocks more
cleanly and precisely than a simple break.
labelName:
for (initialization; condition; update)
{
for (initialization; condition; update) {
if (condition) {
break labelName;
}
}
}
break with label
outerLoop: // Label for outer loop
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (i == 2 && j == 2)
{
System.out.println("Breaking out of outer loop");
break outerLoop; // Exits both loops
}
System.out.println("i = " + i + ", j = " + j);
}
}
Find Output
public class Test {
public static void main(String[] args) {
int sum = 0;
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i + j > 4) {
break outer;
}
sum += i + j;
}
}
System.out.println("Sum = " + sum);
}
}