0% found this document useful (0 votes)
4 views16 pages

Java Input and Output Formatting Examples

The document contains multiple Java programs that demonstrate various input/output operations and calculations, including displaying ASCII values, formatting floats, converting dates, and performing arithmetic operations. Each program includes logic explanations, sample inputs, and expected outputs. The examples cover a range of topics such as temperature conversion, interest calculation, and geometric calculations.

Uploaded by

Anusha T.R
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)
4 views16 pages

Java Input and Output Formatting Examples

The document contains multiple Java programs that demonstrate various input/output operations and calculations, including displaying ASCII values, formatting floats, converting dates, and performing arithmetic operations. Each program includes logic explanations, sample inputs, and expected outputs. The examples cover a range of topics such as temperature conversion, interest calculation, and geometric calculations.

Uploaded by

Anusha T.R
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

Display ASCII value of a character

Logic:
• Every character has an integer ASCII value.
• Simply cast the character to int.
import [Link];

public class ASCIIValue {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a character: ");
char ch = [Link]().charAt(0); // Read first character
int ascii = (int) ch;
[Link]("ASCII value of '" + ch + "' is " + ascii);
}
}
Input: 'a' Expected Output: ASCII value of 'a' is 97 Input: '!' Expected Output: ASCII value of '!' is 33

Float input with more than 3 decimals → print with 2 decimals


Logic:
• Use printf with %.2f to format float/double.
import [Link];

public class FloatTwoDecimals {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a float: ");
double num = [Link]();
[Link]("%.2f\n", num);
}
}
Input: 123.45678
Expected Output: 123.46
Input: 0.1234567
Expected Output: 0.12

Print floating-point in exponential notation


Logic:
• Use printf with %e.
import [Link];

public class ExponentialFormat {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a float: ");
double num = [Link]();
[Link]("%e\n", num);
}
}
Input: 123.456
Expected Output: 1.23456e+02
Input: 0.000123456
Expected Output: 1.23456e-04

Right justify number within 8 columns


Logic:
• Use printf with %8.6f for floats or %8s for general values.
• Adjust width/precision for rounding/trimming.
import [Link];

public class RightJustify {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
double num = [Link]();
[Link]("%8.6f\n", num); // width 8, 6 decimals max
}
}
Input: 123 Expected Output: 123
Input: 987654 Expected Output: 987654
Input: 1.23 Expected Output: 1.23
Input: 0.123456789 Expected Output: 0.123457 (rounded to fit within 8 columns)
Input: 1234567890 Expected Output: 12345678 (trimmed to fit within 8 columns)

Print float with exactly 2 decimal places


Logic:
• Similar to #2: Use %.2f.
import [Link];

public class FloatTwoDecimalsExact {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a float: ");
double num = [Link]();
[Link]("%.2f\n", num);
}
}
Input: 3.14159
Expected Output: 3.14
Input: 123.45678
Expected Output: 123.46
Input: 7.5
Expected Output: 7.50

Print integer right-aligned in width 10


Logic:
• Use printf with %10d to right-align integers.
import [Link];

public class RightAlignInteger {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int num = [Link]();
[Link]("%10d\n", num);
}
}
Input: 987654321 Expected Output: 987654321 Input: -987 Expected Output: -987

Print string surrounded by quotation marks


Logic:
• Concatenate " before and after string.
import [Link];

public class QuoteString {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("\"" + str + "\"");
}
}
Expected Output: "Hello, World!"
Input: Programming
Expected Output: "Programming"

Convert date YYYY MM DD → DD/MM/YYYY


Logic:
• Read 3 integers and print in new order.
import [Link];

public class DateFormat {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int year = [Link]();
int month = [Link]();
int day = [Link]();
[Link]("%02d/%02d/%04d\n", day, month, year);
}
}
Input: 2024 06 15
Expected Output: 15/06/2024
Input: 1999 12 31
Expected Output: 31/12/1999

Read integer, float, and string → print in one line


Logic:
• Read in order, then print separated by commas.
• For string input, use next() if one word, nextLine() if sentence.
import [Link];

public class MultipleInput {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int i = [Link]();
double d = [Link]();
[Link](); // consume leftover newline
String s = [Link]();
[Link](i + ", " + d + ", " + s);
}
}
Input:
10
3.14
"Hello"
Expected Output: 10, 3.14, Hello
Input:
-5
2.718
"Program"
Expected Output: -5, 2.718, Program

Print floating-point money with $


Logic:
• Use printf with $ and %.2f.
import [Link];

public class DollarAmount {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter amount: ");
double amount = [Link]();
[Link]("Amount: $%.2f\n", amount);
}
}
Input: 123.45
Expected Output: Amount: $123.45
Input: 1000.0
Expected Output: Amount: $1000.00
1 Print names and ages in columns (names left, ages right)
Logic:
• Use printf with %-10s for left-aligned string and %3d for right-aligned age.
• Loop until input ends (e.g., fixed number or using sentinel).
import [Link];

public class NamesAndAges {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
for (int i = 0; i < 3; i++) { // Read 3 entries
String name = [Link]();
int age = [Link]();
[Link]("%-10s %3d\n", name, age);
}
}
}
John 25
Praveen 30
Kanishk 22
Expected Output:
John 25
Praveen 30
Kanishk 22

1 Floating-point in width 10 with 3 decimals


Logic:
• Use printf with %10.3f (10 width, 3 decimals).
import [Link];

public class FloatWidth3Decimals {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double num = [Link]();
[Link]("%10.3f\n", num);
}
}
Input
123.456
Expected Output
123.456
Input
-987.654321
Expected Output
-987.654
Input
0.123456789
Expected Output
0.123

1 Integer padded with leading zeros (width 5)


Logic:
• Use printf with %05d.
import [Link];

public class LeadingZeros {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int num = [Link]();
[Link]("%05d\n", num);
}
}
Input
123
Expected Output
00123
Input
9876
Expected Output
09876

1 Print integer in decimal, hexadecimal, octal


Logic:
• Use [Link]() and [Link]() for conversions.
• Add prefix manually.
import [Link];

public class NumberFormats {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int num = [Link]();
[Link]("Decimal: " + num);
[Link]("Hexadecimal: 0x" + [Link](num));
[Link]("Octal: 0o" + [Link](num));
}
}
Input
123
Expected Output
Decimal: 123
Hexadecimal: 0x7b
Octal: 0o173
Input
255
Expected Output
Decimal: 255
Hexadecimal: 0xff
Octal: 0o377

1 Swap two bits in a byte


Logic:
• Check if bits at positions p1 and p2 differ.
• If yes, flip them using XOR (^).
import [Link];

public class SwapBits {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int b = [Link]();
int p1 = [Link]();
int p2 = [Link]();
[Link]("Original byte: " + b);

if (((b >> p1) & 1) != ((b >> p2) & 1)) {


b ^= (1 << p1) | (1 << p2);
}
[Link]("Byte with swapped bits: " + b);
}
}
Enter a byte (0-255): 127
Enter the first bit position (0-7): 0
Enter the second bit position (0-7): 7
Expected Output
Original byte: 127
Byte with swapped bits: 254

1 Swap two nibbles of a byte


Logic:
• High nibble = (b & 0xF0) >> 4
• Low nibble = (b & 0x0F) << 4
• Combine them.
import [Link];

public class SwapNibbles {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int b = [Link]();
int swapped = ((b & 0x0F) << 4) | ((b & 0xF0) >> 4);
[Link](swapped);
}
}
Input
5
Expected Output
80
Input
0
Expected Output
0
Internal Placement Training
6|Page
Input
255
Expected Output
255

1 Swap two numbers without third variable


Logic:
• Use addition/subtraction or XOR to swap.
import [Link];

public class SwapNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
[Link]("Before swapping: num1 = " + a + ", num2 = " + b);

a = a + b;
b = a - b;
a = a - b;

[Link]("After swapping: num1 = " + a + ", num2 = " + b);


}
}
Expected Output
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5

1 Temperature conversion (Celsius ↔ Fahrenheit)


Logic:
• F = C * 9/5 + 32
• C = (F - 32) * 5/9
import [Link];

public class TemperatureConversion {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double celsius = [Link]();
double fahrenheit = [Link]();

[Link](celsius * 9/5 + 32 + " Fahrenheit");


[Link]((fahrenheit - 32) * 5/9 + " Celsius");
}
}
Celsius: 37 Fahrenheit: 98.6 Expected Output 98.6 Fahrenheit 37.0 Celsius

1 Calculate Simple Interest (SI) and Compound Interest (CI)


Logic:
• SI = P * R * T / 100
• CI = P * [Link](1 + R/100, T) - P
import [Link];

public class InterestCalculator {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double P = [Link]();
double R = [Link]();
double T = [Link]();

double SI = (P * R * T) / 100;
double CI = P * [Link](1 + R/100, T) - P;

[Link]("Simple Interest: " + SI);


[Link]("Compound Interest: " + CI);
}
}
Input
Enter principal amount: 1200
Enter interest rate: 2.5
Enter time (in years): 5
Expected Output
Simple Interest: 150.0
Compound Interest: 131.442041

2 Volume of a sphere
Logic:
• Volume = 4/3 * π * r³
import [Link];

public class SphereVolume {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double r = [Link]();
double volume = (4.0/3.0) * [Link] * [Link](r, 3);
[Link]("%.2f\n", volume);
}
}
Input
5
Expected Output
523.60
Input
10
Internal Placement Training
7|Page
Expected Output
4188.79
2 Perimeter of a rectangle
Logic:
• Perimeter = 2 × (height + width)
import [Link];

public class RectanglePerimeter {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the height of the rectangle: ");
double height = [Link]();
[Link]("Enter the width of the rectangle: ");
double width = [Link]();

double perimeter = 2 * (height + width);


[Link]("The perimeter of the rectangle with height " + height + " and width " + width
+ " is: " + perimeter);
}
}
Input:
Enter the height of the rectangle: 10000
Enter the width of the rectangle: 5000
Expected Output:
The perimeter of the rectangle with height 10000.0 and width 5000.0 is: 30000.0

2 Display forename, surname, year


Logic:
• Read 2 strings + 1 integer, then print sequentially.
import [Link];

public class NameAndYear {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter forename: ");
String forename = [Link]();
[Link]("Enter surname: ");
String surname = [Link]();
[Link]("Enter year of birth: ");
int year = [Link]();

[Link](forename + " " + surname + " " + year);


}
}
Input
Enter forename: Kanishk
Enter surname: Smith
Enter year of birth: 1990
Expected Output
Kanishk Smith 1990

2 Sum of three numbers input in one line (comma-separated)


Logic:
• Read line, split by ,, parse as double, sum them.
import [Link];

public class SumThreeNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter three numbers separated by commas: ");
String line = [Link]();
String[] parts = [Link](",");

double sum = 0;
for (String part : parts) {
sum += [Link]([Link]());
}

[Link](sum);
}
}
Input:
10, 20.5, 5
Expected Output:
35.5
Input:
-5, 10, -3
Expected Output:
2.0

2 Addition, subtraction, multiplication, division of two numbers


Logic:
• Read 2 numbers, print all four operations.
import [Link];

public class BasicOperations {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double a = [Link]();
double b = [Link]();

[Link](a + b);
[Link](a - b);
[Link](a * b);
[Link](a / b);
}
}
Input
10
5
Expected Output
15.0
5.0
50.0
2.0

2 Find third angle of triangle


Logic:
• Sum of triangle angles = 180 → third = 180 - (a + b)
import [Link];

public class ThirdAngle {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the first angle: ");
double angle1 = [Link]();
[Link]("Enter the second angle: ");
double angle2 = [Link]();

double angle3 = 180 - (angle1 + angle2);


[Link]("The third angle of the triangle is: " + angle3 + " degrees");
}
}
Input
Enter the first angle of the triangle in degrees: 30
Enter the second angle of the triangle in degrees: 60
Expected Output
The third angle of the triangle is: 90.0 degrees

2 Reverse given characters


Logic:
• Store in string/array, reverse, print.
public class ReverseCharacters {
public static void main(String[] args) {
char[] chars = {'T', 'A', 'P'};
[Link]("The reverse of ");
for (char c : chars) [Link](c);
[Link](" is ");
for (int i = [Link] - 1; i >= 0; i--) [Link](chars[i]);
}
}
Test Characters: 'T‟, 'A', 'P'
Expected Output:
The reverse of TAP is PAT

2 Convert days → years, weeks, days


Logic:
• Years = days / 365
• Remaining weeks = (days % 365) / 7
• Remaining days = (days % 365) % 7
import [Link];

public class DaysConversion {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int days = [Link]();

int years = days / 365;


int weeks = (days % 365) / 7;
int remDays = (days % 365) % 7;

[Link](days + " days is equivalent to:");


[Link]("Years: " + years);
[Link]("Weeks: " + weeks);
[Link]("Days: " + remDays);
}
}
Input
Enter the number of days: 1000
Expected Output
1000 days is equivalent to:
Years: 2
Weeks: 142
Days: 6

2 Distance between two points


Logic:
• Distance formula: √((x2 - x1)² + (y2 - y1)²)
import [Link];

public class DistanceBetweenPoints {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double x1 = [Link]();
double y1 = [Link]();
double x2 = [Link]();
double y2 = [Link]();

double distance = [Link]([Link](x2 - x1, 2) + [Link](y2 - y1, 2));


[Link]("Distance between the points (%.0f, %.0f) and (%.0f, %.0f) is: %.2f\n", x1, y1,
x2, y2, distance);
}
}
Input
Enter coordinates of first point (x1, y1): 1 2
Enter coordinates of second point (x2, y2): 4 6
Expected Output
Distance between the points (1, 2) and (4, 6) is: 5.00

2 Bike average consumption


Logic:
• Average = distance / fuel
import [Link];

public class BikeConsumption {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int distance = [Link]();
double fuel = [Link]();

double avg = distance / fuel;


[Link]("Average consumption of the bike: %.2f km/liter\n", avg);
}
}
Enter the total distance traveled (in km): 1000
Enter the fuel spent (in liters): 50.25
Expected Output:
Average consumption of the bike: 19.88 km/liter

3 Convert km/h → mph


Logic:
• 1 km = 0.621371 miles → mph = km/h × 0.621371
import [Link];

public class KmToMph {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
double kmh = [Link]();
double mph = kmh * 0.621371;
[Link]("Speed in miles per hour: %.2f mph\n", mph);
}
}
Input:
Enter speed in kilometres per hour: 1500
Expected Output:
Speed in miles per hour: 932.06 mph
3 Convert hours and minutes → total minutes
Logic:
• Total minutes = hours × 60 + minutes
import [Link];

public class TotalMinutes {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int hours = [Link]();
int minutes = [Link]();

int totalMinutes = hours * 60 + minutes;


[Link](totalMinutes);
}
}
Example:
• Input: 3 0 → 3×60 + 0 = 180
• Input: 10 120 → 10×60 + 120 = 720

3 Convert minutes → hours and remaining minutes


Logic:
• Hours = minutes / 60
• Remaining minutes = minutes % 60
import [Link];

public class HoursAndMinutes {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int totalMinutes = [Link]();

int hours = totalMinutes / 60;


int remainingMinutes = totalMinutes % 60;

[Link]("Total hours: " + hours);


[Link]("Remaining minutes: " + remainingMinutes);
}
}
Example: 135 minutes → 2 hours, 15 minutes

3 Break amount into smallest number of bank notes


Logic:
• Use integer division and modulo.
• Start from largest note → smallest note.
import [Link];

public class BankNotes {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int amount = [Link]();
int remaining = amount;

int[] notes = {1000, 500, 100, 50, 20, 10, 5, 2, 1};

[Link]("Amount " + amount + " can be broken down into:");


for (int note : notes) {
int count = remaining / note;
remaining %= note;
[Link](count + " notes of Rs " + note);
}
}
}
Example: 2563 → 2×1000, 1×500, 1×50, 1×10, 1×2, 1×1

3 Movie snack bill


Logic:
• Multiply quantity by unit price, sum total.
import [Link];

public class MovieBill {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of pizzas bought: ");


int pizzas = [Link]();
[Link]("Enter number of puffs bought: ");
int puffs = [Link]();
[Link]("Enter number of cool drinks bought: ");
int drinks = [Link]();

int total = pizzas * 100 + puffs * 20 + drinks * 10;


[Link]("Total Bill Amount: Rs. " + total);
}
}
Example: 2 pizzas, 3 puffs, 4 drinks → 2×100 + 3×20 + 4×10 = 380

3 Swap all odd and even bits of an unsigned integer


Logic:
• Even bits: mask 0xAAAAAAAA
• Odd bits: mask 0x55555555
• Right shift even bits, left shift odd bits, combine with OR.
import [Link];

public class SwapOddEvenBits {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

int evenBits = n & 0xAAAAAAAA; // mask even bits


int oddBits = n & 0x55555555; // mask odd bits

evenBits >>= 1; // shift even bits right


oddBits <<= 1; // shift odd bits left

int result = evenBits | oddBits;


[Link](result);
}
}
Example:
• Input: 23 → binary 00010111 → Output: 43 → binary 00101011

You might also like