java eg sufi
java eg sufi
This Java program is used to print on the screen input by the user.
This Java program asks the user to provide a string, integer and float input, and prints it.
• Scanner class and its functions are used to obtain inputs, and println() function is used
to print on the screen.
• Scanner class is a part of java.util package, so we required to import this package in our
Java program.
• We also required to create a object of Scanner class to call its functions.
• There are different functions is available to obtain integer, float and string inputs:
nextInt() function for integer input, nextFloat() function for float input
and nextLine() function for string input.
Example:
import java.util.Scanner;
class GetInputs
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner obj = new Scanner(System.in); /* create a object */
System.out.println("Enter a string:");
s = obj.nextLine(); /* Take string input and assign to variable */
System.out.println("You entered string "+s); /* Print */
System.out.println("Enter an integer:");
a = obj.nextInt(); /* Take integer input and assign to variable */
System.out.println("You entered integer "+a); /* Print */
System.out.println("Enter a float:");
b = obj.nextFloat(); /* Take float input and assign to variable */
System.out.println("You entered float "+b); /* Print */
}
}
Program Output:
Enter a string:
madtec
You entered string madtec
Enter an integer:
15
You entered integer 15
Enter a float:
12.5
You entered float 12.5
JAVA PROGRAM TO COMPARE TWO STRINGS
This Java program is used to demonstrates a comparison of two strings.
Example:
if(a.equals(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
if(a.equalsIgnoreCase(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
}
}
Program Output:
Output – EqualCheck
Explanation:
First of all, a class named EqualCheck is declared with the keyword public. Public designates
that the class can be accessed from anywhere within the program.
Within this class, the main() method is defined. The main() method has two String variables.
These are:
• String a = "AVATAR";
• String b = "avatar";
First String type variable a is storing the string value AVATAR, and the second variable b is
storing the string value avatar.
It is to be noted that both variables a and b will generate different ASCII (American Standard
Code for Information Interchange) values, and the string comparison is checked based on the
ASCII values among two or more strings.
a.equals(b) is a pre-defined method of Java String Class which checks whether two given and
initialized strings are equal or not. If found equal, the statement System.out.println ("Both strings
are equal."); will get printed else this statement System.out.println ("Both strings are not
equal."); gets printed.
In this Java program, it ignores the upper and lower case issue and compares both the strings.
JAVA PROGRAM TO REMOVE WHITE SPACES
This program shows how to remove white spaces from within a string which is having
extra spaces.
Example:
Program Output:
Output – JavaTrim
Avatar
Explanation:
In this program, the class is named as JavaTrim which is having an access specifier as public.
Within this class, the main method has been defined.
This program contains a package which is by default available to every Java program. The
package is import java.lang.*; All the basic programming methods and requirements comes
under this Java package.
This main() method is having a String class which defines a variable name MyString and is
initialized with a value named as " Avatar " having spaces following it. Now the thing is
you have to eliminate the spaces from within the string.
This is possible using the trim() method which is already defined within the String class. This
method is used to return a copy of the string and omitting the trailing white spaces. The syntax
is: <access specifier> String trim(). This returns a replica of any given string with starting and
ending white space(s) removed from the string.
This type of methods are usually used, where user enters extra spaces and the programmer's need
to take care of that thing while programming, eliminating those spaces for making the string
looks as the space is also having its own ASCII value.
JAVA PROGRAM TO CONCATENATE TWO STRINGS USING CONCAT
METHOD.
This Java program is used to demonstrates concatenate two strings using concat method.
Example:
Program Output:
Output – JavaConcat
madtec.in
Explanation:
Here is a Java program which illustrates how you can concatenate two strings in Java. The
meaning of concatenation is that two words can be joined as a single word. In other words, this
pre defined method is used to append one string to the end of other string (Here string a with
string b). This method returns a String in the form of result with the value of the String passed
into the method, attached to the end of the String creating a new string.
In this program, first a class name JavaConcat is declared with the access specifier public and
inside it the main() method has been defined. Inside the main(), 2 string type variables has been
defined named a and b. The new concatenated string which gets generated after using concat() is
being stored in another String variable name c which is being initialized by the predefined
method concat() and operates on two strings 'a' and 'b' to concatenate then as one.
The concatenation in Java can also be done in other ways. One simple way is by using + symbol
between two string operands. Another way of doing is by the use of pre defined
method concat() as done above.
JAVA PROGRAM TO FIND DUPLICATE CHARACTERS IN STRING
This Java program is used to find duplicate characters in string.
Example:
Program Output:
Explanation:
Here in this program, a Java class name DuplStr is declared which is having the main() method.
All Java program needs one main() function from where it starts executing program. Inside the
main(), the String type variable name str is declared and initialized with string madtec. Next an
integer type variable cnt is declared and initialized with value 0. This cnt will count the number
of character-duplication found in the given string.
The statement: char [] inp = str.toCharArray(); is used to convert the given string to character
array with the name inp using the predefined method toCharArray().
The System.out.println is used to display the message "Duplicate Characters are as given
below:". Now the for loop is implemented which will iterate from zero till string length. Another
nested for loop has to be implemented which will count from i+1 till length of string.
Inside this two nested structure for loops, you have to use an if condition which will check
whether inp[i] is equal to inp[j] or not. If the condition becomes true prints inp[j] using
System.out.println() with s single incrementation of variable cnt and then break statement will
be encountered which will move the execution out of the loop.
JAVA PROGRAM TO CONVERT STRINGS TO ARRAY LIST.
This Java program is used to demonstrates split strings into ArrayList.
• Splitting the string by using Java split() method and storing the substrings into an array.
• Creating an ArrayList while passing the substring reference to it
using Arrays.asList() method.
Example:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
Program Output:
99
42
55
81
79
64
22
Explanation:
In this Java program, the java.util.Arraylist package has been imported. This package provides
resizable array and it uses the List interface. It provides various methods for manipulating the
size of the array which is used internally for storing the list. Java.util.Arrays is used to deal with
arrays of different types. It contains a static factory which provides arrays to be viewed as lists.
The a class is declared name StringtoArrayList inside which the main() is defined. The
statement:
defines that using the String class, a string type of variable name strings is declared and
initialized with a set of values.
Then comes the String array str[] which implements the default split() method. This method
has two alternatives and is used to splits the associated string around matches of that given
regular expression. It splits a string into sub string and returns it as a new array.
Now another statement where a List is created with the name nl and that object of the List is
assigned a ArrayList type of value by converting it from string, which is str[] here. And then
using enhanced For loop, prints all the converted valued. This is how a simple string value gets
converted to ArrayList.
JAVA PROGRAM TO CHECK WHETHER GIVEN STRING IS A PALINDROME
A palindrome is a string, which, when read in both forward and backward ways is the same.
Example:
This Java program asks the user to provide a string input and checks it for the Palindrome String.
• Scanner class and its function nextLine() is used to obtain the input,
and println() function is used to print on the screen.
• Scanner class is a part of java.util package, so we required to import this package in our
Java program.
• We also required to create an object of Scanner class to call its functions.
Example:
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Program Output:
Enter a string:
radar
radar is a palindrome
Explanation:
To check if a string is a palindrome or not, a string needs to be compared with the reverse of
itself.
R A D A R
Palindrome String
---------------------------
index: 0 1 2 3 4
value: r a d a r
---------------------------
JAVA PROGRAM TO CONVERT STRING TO INT
This Java program converts String to Integer.
Usually String to int conversion is required when we need to do some mathematical operations in
the string variable that contains numbers. This situation normally arises whenever we receive
data from user input via textfield or textarea, data is obtained as string and we required to
convert string to int.
Java Integer class has parseInt() static method, which is used convert string to int.
Syntax:
Example:
Program Output:
12350
173
JAVA PROGRAM TO REMOVE ALL SPACES FROM GIVEN STRING
This Java program removes spaces from the string entered by the user. It checks for
and removes all blank characters using a regular expression and prints the final output to the
screen.
import java.util.Scanner;
Program Output:
This Java example code demonstrates a simple Java program to find the ASCII value of
a character and print the output to the screen.
Example:
Program Output:
The above Java program shows two ways to print the ASCII value of a character:
1. First, a character is defined using single quotes and assigned to an integer; In this way,
Java automatically converts the character value to an ASCII value.
2. Next, we cast the character ch variable to an integer using (int). Casting is the way of
converting a variable type to another type.
C LANGUAGE FUNDAMENTALS
Example:
import java.util.Date;
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else{
System.out.println("Date1 is equal to Date2");
}
}
}
Program Output:
before() and after() and equals() method is also used to compare dates.
Example:
import java.util.Date;
if(date1.before(date2)){
//Do Something
}
if(date1.after(date2)){
//Do Something
}
if(date1.equals(date2)){
//Do Something else
}
}
}
Explanation:
This Java program is used to compare between two dates. For comparing two dates, you have to
write the program like this:
First you have imported the package java.util.Date; which contains all the pre defined methods
that will deal with dates and time. The java.util.Date class is used to represent a precise moment
in time having millisecond precision.
Now create a class with the name 'DisplayDate' inside which Date1 and Date2 are the objects of
Date. Then implement a conditional statement if(date1.compareTo(date2)>0), which compares
whether date1 is same as that of date2 and returns 0 if same and returns a value less than 0 when
the argument is a string is lexicographically greater than this string; and returns a value greater
than 0 when the argument is a string is lexicographically less than this string.
Now when the condition (date1.compareTo(date2)>0) is greater than 0, the program prints Date1
is after Date2", whereas when date1.compareTo(date2)<0, prints "Date1 is before Date2" and if
both the dates are equal, prints the message - "Date1 is equal to Date2"
JAVA PROGRAM TO DEDMONSTRATE SWITCH CASE
This Java program is used to show the use of switch case to display the month based on
the number assigned.
Example:
class monthno {
public static void main(String argu[]) {
int mnth = 6;
switch (mnth) {
case 1:
System.out.println("Showing Month: January");
break;
case 2:
System.out.println("Showing Month: February");
break;
case 3:
System.out.println("Showing Month: March");
break;
case 4:
System.out.println("Showing Month: April");
break;
case 5:
System.out.println("Showing Month: May");
break;
case 6:
System.out.println("Showing Month: June");
break;
case 7:
System.out.println("Showing Month: July");
break;
case 8:
System.out.println("Showing Month: August");
break;
case 9:
System.out.println("Showing Month: September");
break;
case 10:
System.out.println("Showing Month: October");
break;
case 11:
System.out.println("Showing Month: November");
break;
case 12:
System.out.println("Showing Month: December");
break;
default:
System.out.println("Invalid input - Wrong month number.");
break;
}
}
}
Explanation:
Here in this program, a Java class name monthno is declared which is having the main() method.
All Java program needs one main() function from where it starts executing program. Inside the
main(), the integer type variable name mnth is declared and initialized with value 6. This integer
type variable will indicate to the month for which the case value is set.
Here inside the switch statement parenthesis the variable mnth is passed. Then, inside the switch
block the cases are defined where case 1 will print " Showing Month: January" using
the System.out.println() method. Similarly the case 2 will print " Showing Month: February"
using the System.out.println() method and this will go on till case 12 will print " Showing
Month: December" using the System.out.println() method.
After that according to the switch case structure, a default statement can be put which will get
displayed an error message as wrong month number will get entered other than 1 till 12.
JAVA PROGRAM NUMBERS
JAVA PROGRAM TO GENERATE RANDOM NUMBERS
This Java program generates random numbers within the provided range.
This Java program asks the user to provide maximum range, and generates a number within the
range.
• Scanner class and its function nextInt() is used to obtain the input,
and println() function is used to print on the screen.
• Random class and its function is used to generates a random number.
• Scanner class and Random class is a part of java.util package, so we required to import
this package in our Java program.
• We also required to create objects of Scanner class and Random class to call its functions.
Example:
import java.util.Scanner;
import java.util.Random;
class AtRandomNumber
{
public static void main(String[] args)
{
int maxRange;
//create objects
Scanner SC = new Scanner(System.in);
Random rand = new Random();
Sometimes situation arises where random numbers are required to be generated between the
ranges.
import java.util.Random;
class HelloWorld
{
public static void main(String[] args)
{
Random rand = new Random();
System.out.println(value);
}
}
Program Output:
3256
JAVA PROGRAM TO SWAPPING TWO NUMBERS, USING A TEMPORARY
VARIABLE.
This Java program is used to demonstrates swapping two numbers, using a temporary variable.
Example:
System.out.println("Before Swapping");
System.out.println("Value of x is :" + x);
System.out.println("Value of y is :" + y);
System.out.println("After Swapping");
System.out.println("Value of x is :" + x);
System.out.println("Value of y is :" + y);
}
}
Program Output:
Output – JavaSwapExample
Before Swapping
Value of x is :10
Value of y is :20
After Swapping
Value of x is :20
Value of y is :10
Explanation:
In this program, a class name JavaSwapExample is being declared which contains the main()
method. Inside the main(), two integer type variables are declared name x and y and are
initialized with values 10 and 20 respectively.
Now in this program, you have to swap the value that is present in x to y and that of y in x, i.e.
after swapping the current value of 'x' and 'y', the 'x' will store 20 and 'y' will store 10. The
statements:
Print the current value of x and y. Then the swap() user defined function is called which is
having 2 parameters x and y. The two parameters are passed. The user defined function swap() is
defined next, where the actual swapping is taking place.
Since the swapping is done using the third variable, here you will include another integer type
variable name temp where you first put the value of 'x', the in 'x' put the value of 'y' and then
from temp, initialize the value of y as done above -
y = temp;
This Java program asks the user to provide integer inputs to perform mathematical operations.
• Scanner class and its functions are used to obtain inputs, and println() function is used
to print on the screen.
• Scanner class is a part of java.util package, so we required to import this package in our
Java program.
• We also required to create a object of Scanner class to call its functions.
Example:
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float devide;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Two Numbers : ");
first = scanner.nextInt();
second = scanner.nextInt();
add = first + second;
subtract = first - second;
multiply = first * second;
devide = (float) first / second;
System.out.println("Sum = " + add);
System.out.println("Difference = " + subtract);
System.out.println("Multiplication = " + multiply);
System.out.println("Division = " + devide);
}
}
Program Output:
Enter Two Numbers : 12
5
Sum = 17
Difference = 7
Multiplication = 60
Division = 2.4
JAVA PROGRAM TO CALCULATE SIMPLE AND COMPOUND INTEREST
This Java program is used to calculate the simple and compound interest for the
given values of amount, rate and time.
Example:
Explanation:
First you have to import the util package of Java so that you can use the Scanner class in this
program which will help programmers to fetch input from users. Then define a class name sici.
Inside the class define the main() function. All Java program needs one main() function from
where it starts executing program.
Next declare a double type variable name pr, rate, t, sim and com. Also define an object
name s of Scanner class using which the value will be fetched from input device. Then
System.out.println() method will be used to display a message - "Enter the amount:". Then the
statement pr=sc.nextDouble(); will be used to fetch the value from keyboard, and parse it to
integer from string and store to variable pr. Similarly the values for time and rate will also be
fetched from the user using sc.nextDouble().
Now you have to use the formula for simple interest to calculate the SI with the given values. So
the statement will be: (pr * t * rate)/100; which will get assigned to variable sim. Similarly the
formula for compound interest is: pr * Math.pow(1.0+rate/100.0,t) - pr; and its calculated
value will be assigned to variable com. The next two System.out.println() methods will be used
to display the calculated result of simple and compound interest.
JAVA PROGRAM TO FIND LARGEST AND SMALLEST NUMBER IN AN
ARRAY.
This Java program is used to demonstrates find largest and smallest number in an Array.
Example:
//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};
Program Output:
Output – FindLargestSmallestNumber
Smallest Number is :9
Explanation:
This Java program shows how to find the largest and the smallest number from within an array.
Here in this program, a Java class name FindLargestSmallestNumber is declared which is
having the main() method. Inside the main(), the integer type array is declared and initialized.
The integer type array is used to store consecutive values all of them having type integer. The
statement is:
The numbers 55, 55, 32, 45, 98, 82, 11, 9, 39, 50 are stored manually by the programmer at the
compile time. Then two integer type variable, name smallest and largest are declared and
initialized with the 0th index value of the array.
Then a 'for loop' is used which goes from 1 to the array length. Within this loop the largest and
the smallest value is detected and initialized to the smallest and largest value uisng if()
largetst = numbers[i];
smallest = numbers[i];
Is used to print the largest and the smallest value which is extracted from the array.
JAVA PROGRAM TO FIND REVERSE NUMBER
Example:
//number defined
int number = 1234;
int reversedNumber = 0;
int temp = 0;
//output
System.out.println("Reversed Number is: " + reversedNumber);
}
}
Program Output:
Output – FindReverseNumber
This is a Java program which is used to find the reverse of a number. So in this program you
have to first create a class name FindReverseNumber and within this class you will declare the
main() method. Now inside the main() you will take two integer type variables. One will be
initialized with the value whose reverse is to be done. Secondly, another variable has been
defined reverse number which will store the value after the reverse operation is done.
Also you have to take one temporary variable for storing integer value within the calculation.
Now you have to use a looping statement, here while loop has been used. Inside that while loop
the condition is being checked whether taken is greater than zero or not. If the condition becomes
true the following statements gets executed:
temp = number%10;
number = number/10;
first statement finds the modulus of the number taken and store it in a temporary variable. The
next statement is used to initialize the calculation (multiplication) of reverseNumber with 10 and
add it with temp and then storing it back to reverseNumber variable. And the final statement
number is divided by 10 and is getting stored on the variable itself.
And lastly, the System.out.println("Reversed Number is: " + reversedNumber); statement gets
executed, printing the value of reverse number.
JAVA PROGRAM TO FIND FACTORIAL
Example:
int number = 4;
int factorial = number;
Program Output:
Output – FindFactorial
Factorial of 4 is 24
Explanation:
This program will find out the factorial for a number, a classic is declared
named FactorialNumber is declared with the keyword public. Public designates that the class
can be accessed from anywhere within the program. Within this class, the main() method is
invoked. The main() method is having two variables of the String class. These are:
• int number = 4;
• int factorial = number;
Here, the two variables are storing the string value 2 integer type variales.
Now, a loop has to be implemented (here for loop) and within this loop, the county variable 'i' is
initialized as number-1, and the loop will continue till (i>1).
Then the statement factorial =factorial * i; is given which calculates the factorial taking one
value of 'i' at a time within the loop and storing them back in the 'factorial' variable. This loop
will start from one value which is a number minus 1 and based on the condition, the loop will
decrement and comes to 1.
Finally, the 'factorial' variable has been printed using the System.out.println().
JAVA PROGRAM TO GENERATE THE FIBONACCI SERIES
In the Fibonacci Series, a number of the series is obtained by adding the last two
numbers of the series.
This Java program asks the user to provide input as length of Fibonacci Series.
• Scanner class and its function nextInt() is used to obtain the input,
and println() function is used to print on the screen.
• Scanner class is a part of java.util package, so we required to import this package in our
Java program.
• We also required to create object of Scanner class to call its functions.
Example:
import java.util.Scanner;
public class FibSeries {
//New number should be the sum of the last two numbers of the series.
for (int i = 2; i < FibLength; i++) {
num[i] = num[i - 1] + num[i - 2];
}
}
Program Output:
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
Explanation:
The first two elements are respectively started from 0 1, and the other numbers in the series are
generated by adding the last two numbers of the series using looping. These numbers are stored
in an array and printed as output.
JAVA PROGRAM TO SWAPPING TWO NUMBERS, WITHOUT USING A
TEMPORARY VARIABLE.
This Java program is used to swapping two numbers, without using a temporary variable.
Example:
int x = 10;
int y = 20;
System.out.println("Before Swapping");
System.out.println("Value of x is :" + x);
System.out.println("Value of y is :" + y);
System.out.println("Before Swapping");
System.out.println("Value of x is :" + x);
System.out.println("Value of y is :" + y);
}
}
Program Output:
Output – JavaSwapExample
Before Swapping
Value of x is :10
Value of y is :20
After Swapping
Value of x is :20
Value of y is :10
Explanation:
This program explains about how you can use the concept of swapping of values within a
variable without using the third variable. Here third variable means, without using temporary
variable. First of all you have to create a class having access specifier as 'public' and name
'JavaSwapExample'. Within this class, the main() method has been declared where two integer
type variables 'x' and 'y' have been declared and initialized.
int x = 10;
int y = 20;
Now before swapping the values present in the variables are shown using the
System.out.println(). Now, the trick for swapping two variable's values without using the
temporary variable is that
x = x + y;
y = x - y;
x = x - y;
first variable is first added to the second variable and stored in first variable. Then the second
variable is subtracted from first variable and stored in second variable. Lastly, the value of
2nd variable is subtracted from 1st and stored in first variable. This is how the values of one
variable get swapped to another and vice versa, i.e. x becomes 20 and y becomes 10.
Finally, the swapped value gets printed using the System.out.println() method.
JAVA PROGRAM TO PRINT PRIME NUMBERS
This Java program demonstrates how to calculate and print prime numbers. Whether
you aim to print prime numbers from 1 to 100 in Java or want to understand the logic behind
identifying a prime number in Java, this tutorial has you covered
Prime numbers are unique natural numbers greater than 1, divisible only by 1 and themselves.
Unlike composite numbers, they can't be divided by smaller natural numbers. Prime numbers are
significant in fields like number theory, cryptography, and computer science.
A few prime numbers are 2, 3, 5, 7, 11, and 13. These numbers can only be divided evenly by 1
or themselves, so they are prime numbers.
Program:
Execute this Java program to generate prime numbers. You will get the list of prime numbers up
to 20 as follows:
1
2
3
5
7
11
13
17
19
Code Explanation:
1. Class and Main Method: First, create a class named PrimeNumbers. Inside this class,
declare the main() method.
2. Variable Initialization: Declare two integer variables num and count. Set num to 20,
which is the upper limit for the prime number search.
3. Outer Loop: An outer loop runs from 1 to num. Initialize count to zero at the start of each
iteration.
4. Inner Loop: An inner loop runs from 2 to i / 2 and checks if i is divisible by any number
in this range. If a divisor is found, count increments by one, and the loop exits.
5. Prime Identification: After the inner loop, if count remains zero, the program
considers i as a prime number and prints it.
Conclusion
This Java tutorial provides an efficient and straightforward way to calculate prime numbers up to
a given limit. Whether you aim to print a list of prime numbers in Java or understand the core
logic behind identifying them, this guide makes it accessible to everyone.
JAVA PROGRAM TO PRINT INVERT TRIANGLE.
This Java program is used to print Invert Triangle.
Example:
Program Output:
Output – JavaInvertTriangle
999999999
88888888
7777777
666666
55555
4444
333
22
1
Explanation:
This program creates a design of an inverse triangle in the form of numbers. In this program first
you need to create a class name 'JavaInvertTriangle' and the main() method within the class.
Now inside the main() definition, declare an integer type variable 'num' and assign it with a value
9.Now you need to imply a loop statement to repeat the numbers from 9 up to 1 to create the
design of an inverse triangle something like this:
Now the loop will continue if the num is having value greater than 0. Within the while loop,
comes the for loop. The statement:
counts the integer variable i from 1 till the value of 'num' (here from 1 to 9) and within the scope
of the for - loop, the value of 'i' is getting printed. As the curly braces of the for - loop ends, the
printing cursor goes to the next line using the escape sequence '\n' (i.e. new line) and the value of
num decreases by 1, using the post decrement operator. The decrement of 'num' value goes till
one and hence prints the triangle from upper to lower starting from 9 nine times till 1, a single
time.
JAVA PROGRAM TO TOSS A COIN
This Java program is used to toss a coin using Java random class.
• Java Math.random() returns a random value between 0.0 and 1.0 each time.
• If value is below 0.5 then it's Heads or otherwise Tails.
Example:
Program Output:
Output – JavaFlip
Tails
Explanation:
In this program, you will learn the code of how the tossing of a coin can be implemented in
program. First of all, you have to declare a class name 'JavaFlip' and implement the main()
method within this class. Now within this main() method declaration you have to use a
conditional statement, in this program, the if() statement within which the Math.random ()
method, which is a predefined method for randomizing any value is used.
java.lang.Math.random() gives a double value along with the positive sign, greater than or equal
to 0.0 and less than 1.0. The resulting values of this predefined method are chosen pseudo-
randomly with (approximately) uniform distribution from that range. It does not contains
parameter.
if (Math.random() < 0.5) statement checks whether Math.randon() method gives return value less
than 0.5 or not. If t.he condition becomes true, System.out.println() prints the string "Heads"
otherwise prints "Tails".
JAVA PROGRAM TO FIND ODD OR EVEN NUMBERS IN AN ARRAY
This Java program is used to find whether values inserted within an array are odd even.
Example:
import java.util.*;
class pn {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Explanation:
First you have to import the util package of Java so that you can use the Scanner class in this
program which will help programmers to fetch input from users. Then define a class name 'pn'.
Inside the class define the main() function. All Java program needs one main() function from
where it starts executing program. Next define an object name 'sc' of Scanner class. Then
System.out.println(); will be used to display a message - " enter the value of size". The size of
array will be of type integer and will get stored in variable a using the object 'sc' of Scanner
class.
Next, you have to declare an integer type array name arr[]. Now, implement for loop to insert
values into the array. The for loop will start from 0 and goes one less, up to the value assigned to
'a'. Then you have to implement another for loop which will also iterate from 0 till a-1. Inside the
array will be the if condition which will check whether i%2 is equal to zero or not, which means
value of 'arr[i]' if divided by 2 remains no remainder then the number is even and so
System.out.println() will display the message "even"; otherwise prints the message "odd".
JAVA PROGRAM TO CALCULATE THE AREA OF A CIRCLE
This Java program is used to calculate the area of a circle.
Example:
import java.util.Scanner;
Explanation:
This program is used to calculate the area of a circle where the radius will be fetched from user.
So, first you have to import the util package of Java so that you can use the Scanner class in this
program which will help programmers to fetch input from users. Then define a class
name CircArea. Inside the class define the main() function. All Java program needs one main()
function from where it starts executing program. Next declare an integer type variable rad which
will hold the radius of the circle and two double type variable pie and ar, where pie will store the
decimal value which is 3.14 and ar will be used to store the calculated area of circle. Also define
an object name s of Scanner class using which the value will be fetched from input device. Then
System.out.println(); will be used to display a message - " Enter radius of circle:". Then the
statement rad = s.nextInt(); will be used to fetch the value from keyboard, and parse it to integer
from string and store to variable rad. Then calculating the result value of multiplication of pie
and rad * rad will get assigned to ar variable.
Then the next System.out.println() will be used to display the message - "Area of circle:" along
with the calculated output which is stored in the variable ar.
CALCULATE THE POWER OF ANY NUMBER IN THE JAVA PROGRAM
There are different ways of doing the same thing, especially when you are
programming. In Java, there are several ways to do the same thing, and in this tutorial, various
techniques have been demonstrated to calculate the power of a number.
Required Knowledge
To understand this lesson, the level of difficulty is low, but the basic understanding of
Java arithmetic operators, data types, basic input/output and loop is necessary.
Used Techniques
In Java, three techniques are used primarily to find the power of any number. These are:
To calculate the power of any number, the base number and an exponent are required.
Syntax:
Example:
In case of 23
Output:
For the numerical input value, you can use predefined standard values, or take input from the
user through scanner class, or take it through command line arguments.
Calculating the Power of a Number Through the While Loop in Java
Program:
while (exponent != 0) {
temp *= basenumber;
--exponent;
}
Output:
Result: 8
Explanation:
• In the above program, the base number and exponent values have been assigned 2 and 3,
respectively.
• Using While Loop we keep multiplying temp by besanumber until the exponent becomes
zero.
• We have multiplied temp by basenumber three times, hence the result would be = 1 * 2 *
2 * 2 = 8.
Calculating the Power of a Number Through the For Loop in Java
Program:
Output:
Result: 8
Explanation:
• In the above program, we used for loop instead of while loop, and the rest of the
programmatic logic is the same.
Calculate the Power of a Number by Through pow() function
Program:
Output:
Result: 8.0
Explanation:
• Above program used Math.pow() function and it's also capable of working with a
negative exponent.
JAVA PROGRAM TO ADD TWO INTEGERS
This Java program adds two integers. It takes input from the user in the form of an
integer and performs simple arithmetic operations for addition.
Example:
import java.util.Scanner;
class AddTwoIntegers{
Program Output:
Enter an integer: 15
Enter a second integer: 5
The sum of two integers 15 and 5 is: 20
JAVA PROGRAM TO CHECK ODD OR EVEN NUMBERS
This Java example code demonstrates a simple Java program that checks whether a
given number is an even or odd number and prints the output to the screen.
Program:
import java.util.Scanner;
if(num%2 == 0){
System.out.println(num + " is even");
}else{
System.out.println(num + " is odd");
}
}
}
Program Output:
Enter a number: 8
8 is even
If a number is evenly divisible by 2 without any remainder, then it is an even number; Otherwise,
it is an odd number. The modulo operator % is used to check it in such a way as num%2 == 0.
In the calculation part of the program, the given number is evenly divisible by 2 without
remainder, so it is an even number.
The above program can also be written using a ternary operator such as:
Java Program to Check Even or Odd Number Using Ternary Operator
Program:
impt java.util.Scanner;
Program Output:
Enter a number: 9
9 is odd
JAVA PROGRAM TO CHECK LEAP YEAR
This Java program does leap year checks. It takes input from the user in the form of
integers and performs simple arithmetic operations within the condition statement for the output.
Example:
import java.util.Scanner;
public class LeapYearCheck {
public static void main(String[] args) {
//Variable definition and assignment
int year = 2016;
boolean leap = false;
Scanner obj = new Scanner(System.in); /* create a object */
//Remove comments from the bottom lines to take input from the user
//System.out.print("Enter a year: ");
//year = obj.nextInt();
//A year divisible by 4 is a leap year
if (year % 4 == 0) {
//It is a centenary year if the value is divisible by 100 with no remainder.
if (year % 100 == 0) {
//Centenary year is a leap year divided by 400
if (year % 400 == 0)
leap = true;
else
leap = false;
}
// if the year is not century
else
leap = true;
}
//The Year is not a leap year
else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
Program Output:
Enter a year: 2016
2016 is a leap year.
JAVA PROGRAM TO VALIDATE ARMSTRONG NUMBER
This Java tutorial helps you understand Armstrong numbers and how to write a Java
program to validate them. Here you will learn to verify whether the integer entered by the user is
an Armstrong number or not.
An Armstrong number is a positive integer equal to the sum of all its digits raised to the power of
the total count of digits.
In this case, 1634 is a four-digit number, and when each of its digits is raised to the power of 4
(the total number of digits), the sum equals the original number.
import java.util.Scanner;
while (originalNumber != 0) {
// lastDigit contains the last digit of the number
lastDigit = originalNumber % 10;
// raise the last digit to the power of digits and add it to the sum
sum += Math.pow(lastDigit, digits);
// remove last digit from the original number
originalNumber /= 10;
}
Program Output:
Here are some examples of running the program and the corresponding output:
Program Explanation:
1. The program asks the user to enter an integer with the help of Java's Scanner class.
2. The program calculates the digit count of the input number.
3. The program enters a loop where it raises each digit to the power of the total number of
digits and adds this to a sum.
4. After processing all the digits, the sum is compared to the original number.
5. Finally, the program will print that the input number is an Armstrong number if the sum
and original number are equal. If not, it will print that the input number is not an
Armstrong number.
JAVA FUNCTION PROGRAMS
Example:
Program Output:
Output – CallingMethodInSameClass
Hello World!
Hello World!
Explanation:
This program demonstrates how programmers can call a method from within the same class. In
this program, you have to first make a class name 'CallingMethodsInSameClass' inside which
you call the main() method. This main() method is further calling the Method1() and Method2().
Now you can call this as a method definition which is performing a call to another lists of
method.
Now inside the main, the Method1 and Method2 gets called. In the next consecutive lines, the
Method1() is defined having access specifier 'public' and no return type i.e. 'void'. Inside that
Method1() a statement is being coded which will print Hello World!. Similarly another method
which is Method2() is being defined with 'public' access specifier and 'void' as return type and
inside that Method2() the Method1() is called.
Hence, this program shows that a method can be called within another method as both of them
belong to the same class.
JAVA PROGRAM TO FIND FACTORIAL OF A NUMBER USING RECURSION
This Java example code demonstrates a simple Java program to calculate factorial values using
recursion and print the output to the screen. In this Java program, a function is defined that calls
itself multiple times until the specified condition matches. This process is called Recursion, and
the function is called the Recursive function.
Example:
Program Output:
Factorial of 5 = 120
JAVA PROGRAM TO REVERSE A SENTENCE USING RECURSION
This Java example code demonstrates a simple Java program to reverse a sentence
using recursion and print the output to the screen.
Example:
Program Output:
In this Java example, we are reading HTML from example.com and printing on screen.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;