Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views62 pages

Introduction To Java Final

Uploaded by

abinshaji
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)
8 views62 pages

Introduction To Java Final

Uploaded by

abinshaji
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
You are on page 1/ 62

Object Oriented Programming

Dr. Arul Xavier V M


Why Java?
Declares a class named HelloWorld. In Java,
every application starts with a class. Think of a
Basic Structure class as a blueprint or container for your code.

This is the starting point of every


class HelloWorld Java program. JVM looks for this
{ method to run your program.
public static void main(String[] args)
{
//to display output
System.out.println("Hello, World!");
}
} Prints the message "Hello, World!"
to the console or command prompt

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;

double Decimal numbers (more precision) double pi = 3.14159;

float Decimal numbers (less precision) float price = 19.99f;

char Single character char grade = 'A';


boolean True or false Shorterwhole
Decimal
Small version
numbers
number
of (more
int (-128
(-32,768
to to boolean isPassed = true;
Data Type
int
float
double
char
boolean
byte
short
long Description
Whole
Decimal
Single
True
Largeorwhole
character
numbers
false
numbers
number(less precision) Example
int
float
double
char
boolean
byte
short
longage
level
population
grade
price
temperature
pi
=isPassed
21;
===3.14159;
10;
19.99f;
'A'; = 7800000000L;
==true;
250;
precision)
127)
32,767)
byte Small whole number (-128 to 127) byte level = 10;

short Shorter version of int (-32,768 to 32,767) short temperature = 250;

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";

System.out.println("Name: " + name);


System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Gender: " + gender);
System.out.println("Employed: " + isEmployed);
}
}
Comments in Java Program
// Java program to demonstrate the usage of different data types
public class DataTypeExample {
// Main method: Entry point of the program
public static void main(String[] args) {

// int: used for storing age of a person


int age = 25;

// double: used for decimal numbers with higher precision


double salary = 45800.75;

// char: used to store a single character


char gender = 'M';

// boolean: used for true/false values


boolean isEmployed = true;

// String: a sequence of characters (not a primitive, but widely used)


String name = "Alice";
}
}
Exercise
Question:
A mobile shop sells smartphones. Each smartphone costs ₹18,999.50.
The shop sold 5 smartphones in a day.
Write a Java program to:
1.Use an int variable to store the number of smartphones sold
2.Use a double variable to store the price of one smartphone
3.Calculate and display the total revenue for the day
public class MobileShopRevenue
{
public static void main(String[] args)
{
// Number of smartphones sold
int smartphonesSold = 5;

// Price of one smartphone


double pricePerSmartphone = 18999.50;

// Calculate total revenue


double totalRevenue = smartphonesSold * pricePerSmartphone;

// Display the total revenue


System.out.println("Number of smartphones sold: " + smartphonesSold);
System.out.println("Price per smartphone: ₹" + pricePerSmartphone);
System.out.println("Total revenue for the day: ₹" + totalRevenue);
}
}
Getting Input from User
• The Scanner class is a part of the java.util package and is used to read
input from the user (via keyboard) in Java.
• Steps to use the Scanner Class
• Import the Scanner class:- import java.util.Scanner;
• Create a Scanner object:- Scanner sc = new Scanner(System.in);
• Use appropriate methods to read input
//Reads an integer
int age = sc.nextInt();
//Reads a double
double price = sc.nextDouble();
//Reads a String word
String name = sc.next();
Scanner class methods
Scanner class Methods
Name Use
nextInt() Returns the next int value
nextDouble() Returns the next double value
nextLong() Returns the next long value
nextFloat() Returns the next float value
nextShort() Returns the next short value
nextByte() Returns the next byte value
nextBoolean() Returns the next Boolean values
nextLine() Returns the next line of Text input
next() Returns the next word(string)
next().charAt(0) Returns the character data
Exercise 1:
A company wants to store employee information and calculate their monthly salary.
Question:
Develop a Java program to store the following details of an employee using user input
with appropriate data types:
• Employee Name (String)
• Employee ID (int)
• Basic Salary (double)
• Allowance (double)
• Tax Deduction (double)
Calculate and display the net salary as:
Net Salary = Basic Salary + Allowance - Tax Deduction

Also, print a message like:


"Employee [Name] with ID [Employee ID] has a net salary of Rs.[Net Salary]"
import java.util.Scanner;
public class EmployeeSalary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking employee details from user
System.out.print("Enter Employee Name: ");
String employeeName = sc.nextLine();
System.out.print("Enter Employee ID: ");
int employeeID = sc.nextInt();
System.out.print("Enter Basic Salary: ");
double basicSalary = sc.nextDouble();
System.out.print("Enter Allowance: ");
double allowance = sc.nextDouble();
System.out.print("Enter Tax Deduction: ");
double taxDeduction = sc.nextDouble();
// Calculate net salary
double netSalary = basicSalary + allowance - taxDeduction;
// Display employee salary details
System.out.println("\nEmployee " + employeeName + " with ID " +
employeeID + " has a net salary of Rs." +netSalary);
}
}
Data Type Conversion
• In Java, data type conversion refers to converting a variable
from one data type to another.
• There are two types:
• 1. Implicit Type Conversion (Widening Conversion)
• Done Automatically by Java
• Smaller → Larger data type
• No data loss
1. Implicit Type Conversion
(Widening Conversion) - Example
class TypeConversion
{
public static void main(String[] args)
{
int a = 100;
long b = a; // int to long
float c = b; // long to float
System.out.println(c); // Output: 100.0
}
}
Predict the output
class TypeConversion
{
public static void main(String[] args)
{
int a = 10;
double b = a;
System.out.println(b); Answer: B. 10.0
} A. 10
} B. 10.0
C. Error
D. 10.00
2. Explicit Type Conversion (Narrowing
Conversion or Type Casting)

• Done Manually by Programmer


• Larger → Smaller data type
• Possible data loss

dataType variable = (dataType) value;


Explicit Type Conversion
(Narrowing Conversion or Type Casting) - Example

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

• Primitive to String: String.valueOf() method


class TypeConversion
{
public static void main(String[] args)
{
int a = 25;
String s = String.valueOf(a); // Converted as “25”
}
}
Conversion Between Primitive and String
• String to Primitive: Integer.parseInt(string), Double.parseDouble(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

• Use the if statement to specify a block of Java code to be executed if a condition


is true.

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();

// Simple if to check perfect score


if(score == 10)
{
System.out.println("Excellent!. You will receive a
certificate of appreciation.");
}
Comparison Operators
Exercise
A movie ticket has a special discount of 20% for children under 12 years old. Write a
program to check if a person is eligible for a discount based on their age.
import java.util.Scanner;
public class MovieTicketDiscount
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Take age as input
System.out.print("Enter your age: ");
int age = sc.nextInt();
// Check eligibility for discount
if (age < 12) {
System.out.println("You are eligible for a 20% discount on your movie ticket.");
} else {
System.out.println("You are not eligible for the children's discount.");
}
}
}
if else

• Use the else statement to specify a block of code to be executed if the


condition is false.
if (condition)
{
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
Example:
A college issues hall tickets for semester exams. A student must have a minimum of 80%
attendance to get the hall ticket. Write a program that checks the attendance percentage
and prints:
• "Eligible" if the attendance is 80% or more
• "Not Eligible" otherwise
import java.util.Scanner;
class HallTicketIssue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input attendance percentage
System.out.print("Enter your attendance percentage: ");
int attendance = sc.nextInt();
// if-else to check eligibility
if(attendance >= 80)
{
System.out.println("Eligible");
} else {
System.out.println("Not Eligible");
}
}
}
Exercise:-

• 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.

for(statement 1; statement 2; statement 3)


{
// code block to be executed
}
How for loop works
Find Factorial of a given number
import java.util.Scanner;
class Factorial {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Number: ");
int number = sc.nextInt();
int fact = 1;
if(number<=0)
{
System.out.println("Factorial: "+fact);
}
else
{
for(int i=1;i<=number;i++)
{
fact = fact * i;
}
System.out.println("Factorial: "+fact);
}
}
}
Exercise 1
A bus collects the number of passengers who board at each stop. There
are 5 stops. The conductor wants to know the total number of passengers
who got on the bus throughout the route.
Question:
Write a Java program using a for loop that:
•Iterates through 5 bus stops.
•For each stop, takes the number of passengers boarding.
•Calculates and displays the total number of passengers.
import java.util.Scanner;
public class BusPassengerCounter
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int totalPassengers = 0;
// Loop for 5 stops
for (int stop = 1; stop <= 5; stop++) {
System.out.print("Enter no of passengers boarding at stop "+stop+": ");
//read and store the no of passengers boarding at particular stop
int passengers = sc.nextInt();
totalPassengers += passengers; // add to total
}
// Display total passengers
System.out.println("Total Passengers Boarded: " + totalPassengers);
}
}
while loop

• The while loop is a control flow statement that allows code to be


executed repeatedly based on a condition. The loop runs as long as
the condition is true.
while (condition)
{
// code block to be executed
}
Problem Statement

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;

//Write your logic here

}
}
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:

• Repeat until the user chooses to exit (e.g., option 0)


Nested Loops
(1,1) Row – Outer Loop - 1 to 5

Column – Inner Loop - 1 to 5

(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);
}
}

You might also like