[Go to site: main page, start]

0% found this document useful (0 votes)
11 views6 pages

Java Sample Programs and Examples

1. The document contains 7 Java programs with examples and outputs: a "Hello World" program, a program that takes integer input, a program that multiplies two floating point numbers, a program that swaps two values using a third variable, a program that checks if a number is even or odd, a program that finds the biggest of three numbers, and a program that checks if a year is a leap year. 2. The programs demonstrate basic Java concepts like input/output, variables, conditional statements, methods, and data types. Examples are provided to illustrate how to print output, take user input, perform calculations, and apply logical conditions. 3. The leap year program uses modulo operators and conditionals
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)
11 views6 pages

Java Sample Programs and Examples

1. The document contains 7 Java programs with examples and outputs: a "Hello World" program, a program that takes integer input, a program that multiplies two floating point numbers, a program that swaps two values using a third variable, a program that checks if a number is even or odd, a program that finds the biggest of three numbers, and a program that checks if a year is a leap year. 2. The programs demonstrate basic Java concepts like input/output, variables, conditional statements, methods, and data types. Examples are provided to illustrate how to print output, take user input, perform calculations, and apply logical conditions. 3. The leap year program uses modulo operators and conditionals
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

1.

Java program to print the “ Hello Java”

Import [Link].*;

Class A

public static void main(String args [])

[Link](“ Hello Java”);

[Link] program to take an integer as input and print it

import [Link].*;

import [Link];

// Driver Class

class GFG {

// main function

public static void main(String[] args)

// Declare the variables

int num;

// Input the integer

[Link]("Enter the integer: ");

// Create Scanner object

Scanner s = new Scanner([Link]);

// Read the next integer from the screen

num = [Link]();

// Display the integer

[Link]("Entered integer is: " + num);

Input
Enter the integer: 10

Output

Entered integer is: 10

[Link] Program to print Multiplication of two floating point Number.

import [Link].*;

class GFG {

public static void main(String[] args)

// f is to ensures that numbers are float DATA TYPE

float f1 = 1.5f;

float f2 = 2.0f;

// to store the multiplied value

float p = f1 * f2;

// to print the product

[Link]("The product is: " + p);

Output

The product is: 3.0

[Link] Program to Swap Two values using third variable using temp variable

// Importing generic libraries

import [Link].*;

class GFG {

// Function to swap two numbers

// Using temporary variable

static void swapValuesUsingThirdVariable(int m, int n)

// Swapping the values

int temp = m;

m = n;

n = temp;

[Link]("Value of m is " + m
+ " and Value of n is " + n);

// Main driver code

public static void main(String[] args)

// Random integer values

int m = 9, n = 5;

// Calling above function to

// reverse the numbers

swapValuesUsingThirdVariable(m, n);

Output

Value of m is 5 and Value of n is 9

[Link] Program to Check if Given Integer is Odd or Even

// Importing required classes

import [Link].*;

import [Link];

// Main class

class GFG {

// Main Driver Method

public static void main(String[] args)

// Declaring and initializing integer variable

int num = 10;

// Checking if number is even or odd number

// via remainder

if (num % 2 == 0) {

// If remainder is zero then this number is even

[Link]("Entered Number is Even");

}
else {

// If remainder is not zero then this number is

// odd

[Link]("Entered Number is Odd");

Output

Entered Number is Even

[Link] Program to Find the Biggest of 3 Numbers

// Importing generic Classes/Files

import [Link].*;

class GFG {

// Function to find the biggest of three numbers

static int biggestOfThree(int x, int y, int z)

return z > (x > y ? x : y) ? z : ((x > y) ? x : y);

// Main driver function

public static void main(String[] args)

// Declaring variables for 3 numbers

int a, b, c;

// Variable holding the largest number

int largest;

a = 5;

b = 10;

c = 3;

// Calling the above function in main

largest = biggestOfThree(a, b, c);

// Printing the largest number

[Link](largest + " is the largest number.");

}
}

Output

10 is the largest number.

[Link] program to find a leap year

// Importing Classes/Files

import [Link].*;

// Class for leap-year dealing

public class GeeksforGeeks {

// Method to check leap year

public static void isLeapYear(int year)

// flag to take a non-leap year by default

boolean is_leap_year = false;

// If year is divisible by 4

if (year % 4 == 0) {

is_leap_year = true;

// To identify whether it is a

// century year or not

if (year % 100 == 0) {

// Checking if year is divisible by 400

// therefore century leap year

if (year % 400 == 0)

is_leap_year = true;

else

is_leap_year = false;

// We land here when corresponding if fails

// If year is not divisible by 4

else

// Flag dealing- Non leap-year

is_leap_year = false;

if (!is_leap_year)
[Link](year + " : Non Leap-year");

else

[Link](year + " : Leap-year");

// Driver Code

public static void main(String[] args)

// Calling our function by

// passing century year not divisible by 400

isLeapYear(2000);

// Calling our function by

// passing Non-century year

isLeapYear(2002);

Output

2000 : Leap-year

2002 : Non Leap-year

Common questions

Powered by AI

The main method serves as the entry point for Java programs, where execution begins. It is essential because it establishes the program's control flow and initializes the execution of its specific tasks. The main method's signature (public static void main(String[] args)) is standardized to ensure compatibility with the Java runtime environment, enabling it to call user-defined functions, manage execution order, and handle initial setup tasks .

The main principles behind using conditional statements in Java include decision-making based on conditions and directing the program’s execution flow accordingly. They are crucial for implementing logic that adapts to different inputs or states, as seen with conditional evaluations for even/odd numbers and leap year checks. This adaptability allows Java programs to perform effectively under varying conditions, enhancing robustness and efficiency .

The Scanner class provides a convenient way to parse primitive data types and strings using regular expressions, making it a flexible tool for input handling in Java. Advantages include its ability to read from various sources such as input streams, files, and strings, and its ease of use for simple data types. However, disadvantages include potential performance issues for large data due to internal synchronization and lack of built-in error handling for unexpected input formats, which can lead to runtime exceptions .

The Java program defines a leap year based on two main criteria: a year is a leap year if it is divisible by 4 but not a century unless it is also divisible by 400. The program checks divisibility by 4 for general leap year status and additional divisibility by 100 and 400 to determine century leap years. This approach follows the Gregorian calendar rules, ensuring correct leap year identification .

Using a temporary variable to swap two numbers is significant because it prevents loss of data during the swapping process. By storing one number temporarily, the program can safely overwrite its initial location with the other number’s value, ensuring that no data is lost or overwritten incorrectly. This method improves the program's reliability by avoiding error-prone direct value overwriting .

Importing the package java.io.* allows the Java program to utilize all the classes within the java.io package, which are necessary for input and output operations. This includes classes like BufferedReader, InputStream, OutputStream, etc. The broad import statement makes it easier to write programs involving various I/O tasks without repeatedly specifying each required class, increasing code readability and reducing the complexity of project management .

The program multiplies two floating-point numbers by declaring them with the float data type (using an 'f' suffix to ensure they are treated as floats) and directly performing the multiplication operation. It ensures precision by using the float data type, which provides sufficient precision for most decimal fractions, while the operation itself is straightforward and reduces potential numerical errors .

The program uses nested conditional operators (ternary operators) to find the biggest of three numbers. It first compares the first two numbers, x and y, with the expression (x > y ? x : y), and then compares the result with the third number, z, using the condition z > (x > y ? x : y) ? z : ((x > y) ? x : y). This ensures correctness by carrying out sequential comparisons, effectively exploring all pairwise comparisons needed to identify the largest number .

The Java program determines if a provided integer is odd or even by using the modulus operator (%) to compute the remainder of the integer when divided by 2. If the remainder is zero, the integer is even; otherwise, it is odd. This method is effective because the remainder of dividing an even number by 2 is always zero, while for an odd number, it is always one, making this a reliable and efficient check .

The increment operator (++), although not prominently featured in these programs, generally increases a variable's value by one. It affects algorithm execution by enabling iterative processes and loop control structures to proceed appropriately, simplifying code by reducing the need for explicit assignment expressions. Its correct usage helps in maintaining clean, readable, and efficient loops, aiding in the development of algorithms that require repetitive actions [General Java Knowledge].

You might also like