0% found this document useful (0 votes)
13 views7 pages

Java Programming Examples and Solutions

The document contains multiple Java programs demonstrating various functionalities such as a student grading system, a simple calculator, a password authentication system, and methods to find the largest of three numbers, sum of natural numbers, factorial of a number, and print elements from arrays. Each program includes user input and outputs results based on the logic implemented. The examples illustrate basic programming concepts including conditionals, loops, and array manipulation.

Uploaded by

Naveen Vnk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Java Programming Examples and Solutions

The document contains multiple Java programs demonstrating various functionalities such as a student grading system, a simple calculator, a password authentication system, and methods to find the largest of three numbers, sum of natural numbers, factorial of a number, and print elements from arrays. Each program includes user input and outputs results based on the logic implemented. The examples illustrate basic programming concepts including conditionals, loops, and array manipulation.

Uploaded by

Naveen Vnk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Student Grading System

import [Link];

public class StudentGrading {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter marks: ");

int marks = [Link]();

char grade;

if (marks >= 90)

grade = 'A';

else if (marks >= 80)

grade = 'B';

else if (marks >= 70)

grade = 'C';

else if (marks >= 60)

grade = 'D';

else

grade = 'F';

[Link]("Grade = " + grade);

Output:

Enter marks: 82

Grade = B

Simple Calculator (Menu-driven)


import [Link];

public class Calculator {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("[Link]\[Link]\[Link]\[Link]");

[Link]("Choose operation: ");

int choice = [Link]();

[Link]("Enter two numbers: ");

double a = [Link](), b = [Link]();

switch (choice) {

case 1: [Link]("Sum = " + (a + b)); break;

case 2: [Link]("Difference = " + (a - b)); break;

case 3: [Link]("Product = " + (a * b)); break;

case 4:

if (b != 0)

[Link]("Quotient = " + (a / b));

else

[Link]("Cannot divide by zero.");

break;

default: [Link]("Invalid choice");

Output:

[Link]

[Link]

[Link]

[Link]

Choose operation: 3
Enter two numbers: 7 8

Product = 56.0

Password Authentication System


import [Link];

public class AuthSystem {

public static void main(String[] args) {

String username = "admin";

String password = "1234";

Scanner sc = new Scanner([Link]);

[Link]("Enter username: ");

String user = [Link]();

[Link]("Enter password: ");

String pass = [Link]();

if ([Link](username) && [Link](password))

[Link]("Access Granted");

else

[Link]("Access Denied");

Output:

Enter username: admin

Enter password: 1234

Access Granted

Find Largest of Three Numbers


import [Link];

public class LargestThree {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter 3 numbers: ");

int a = [Link](), b = [Link](), c = [Link]();

if (a >= b && a >= c)

[Link](a + " is largest");

else if (b >= a && b >= c)

[Link](b + " is largest");

else

[Link](c + " is largest");

Sum of Natural Numbers up to N


import [Link];

public class SumNaturalNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter N: ");

int n = [Link](), sum = 0;

for (int i = 1; i <= n; i++)

sum += i;

[Link]("Sum = " + sum);

Find Factorial of a Number


import [Link];
public class FactorialWhile {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");

int n = [Link]();

int fact = 1, i = 1;

while (i <= n) {

fact *= i;

i++;

[Link]("Factorial: " + fact);

Continue Prompting Until “yes” is Entered


import [Link];

public class PromptUntilYes {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String answer;

do {

[Link]("Do you want to continue? (yes/no): ");

answer = [Link]();

} while (![Link]("yes"));

[Link]("Continuing...");

Output:
Do you want to continue? (yes/no): no

Do you want to continue? (yes/no): maybe

Do you want to continue? (yes/no): yes

Continuing...

Print All Elements of an Array


public class PrintArray {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

for (int num : numbers) {

[Link](num);

Output:

10

20

30

40

50

Display All Words in a String Array


public class WordsArray {

public static void main(String[] args) {

String[] words = {"Java", "is", "fun"};

for (String word : words) {

[Link](word);

}
}

Output:

Java

is

fun

Print Odd Numbers from Array


public class OddNumbers {

public static void main(String[] args) {

int[] values = {11, 22, 33, 44, 55};

for (int val : values) {

if (val % 2 != 0)

[Link](val);

Output:

11

33

55

Common questions

Powered by AI

The program uses a 'for-each' loop to iterate through the 'words' string array, printing each word on a new line. This structure ensures that every element is accessed and displayed sequentially, resulting in each string being printed individually. The use of the 'for-each' loop simplifies the traversal and output process, ensuring clarity in display format .

The Student Grading System determines the grade based on a series of conditions that check the range of the given marks. If the mark is 90 or above, the grade is 'A'. For marks 80 to 89, the grade is 'B'. Marks between 70 to 79 receive a 'C', 60 to 69 get a 'D', and anything below 60 is graded as 'F'. This logic uses a sequence of 'if-else' conditions to evaluate and assign the appropriate grade based on the mark range .

The program calculates the sum of natural numbers up to 'N' using a simple 'for' loop. Starting from 1 and iterating to 'N', it accumulates the sum by adding each integer to a running total ('sum'). This method iteratively builds the total and leverages the intrinsic properties of arithmetic progression to efficiently compute the sum .

This program iterates through the 'values' array using a 'for-each' loop. Within each iteration, it employs a modulus operation (val % 2 != 0) to check if the current number is odd. If the condition is met, the number is printed. This filtering strategy effectively isolates and outputs only the odd numbers from the array .

The program repeatedly prompts the user with 'Do you want to continue? (yes/no)' until the input matches 'yes', using a 'do-while' loop structure. The loop continues as long as the entered string, converted to lowercase, does not equal 'yes', ensuring case-insensitivity. Only when 'yes' is entered does the loop exit, resulting in the output 'Continuing...' This loop structure ensures user input is verified and meets the expected condition before proceeding .

The program computes the factorial using a 'while' loop that multiplies an accumulating variable ('fact') by the loop index ('i'), starting from 1 up to the given number 'N'. This iterative multiplication exploits the mathematical definition of factorial (N!), ensuring each step multiplies the current product by the next integer. The loop continues until 'i' exceeds 'N', at which point the factorial has been fully calculated. This method is effective due to its straightforward, step-by-step approach that mirrors the factorial's definition .

The Simple Calculator is limited to basic arithmetic operations: addition, subtraction, multiplication, and division. It uses a 'switch' statement to select the operation based on user input. A significant limitation is its handling of division: the program checks if the divisor (b) is zero before performing division, displaying a custom message 'Cannot divide by zero' to avoid arithmetic errors. However, it lacks error handling for invalid input types or malformed data beyond the case of division by zero .

The Password Authentication System prompts for a username and password, both of which are compared against hardcoded values ('admin' and '1234'). Access is granted only if both the input username and password exactly match these predefined values using the 'equals' method for string comparison. If either value does not match, access is denied .

The program employs an enhanced 'for-each' loop to iterate over each integer in the 'numbers' array. For every loop iteration, it prints the current element. This method ensures that all elements are accessed in sequence and displayed on separate lines, efficiently handling the array traversal without requiring manual indexing .

The Largest of Three Numbers program uses a series of 'if-else' conditions to compare three input numbers (a, b, c). It first checks if 'a' is greater than or equal to both 'b' and 'c', and if true, 'a' is considered the largest. If not, it then checks if 'b' is greater than or equal to 'a' and 'c', returning 'b' as the largest if true. If neither condition is met, 'c' is declared the largest. This approach ensures that all scenarios of larger numbers among the three are evaluated comprehensively .

You might also like