0% found this document useful (0 votes)
4 views

java eg sufi

This document provides various Java programs demonstrating string manipulation techniques, including user input handling, string comparison, whitespace removal, string concatenation, and palindrome checking. It covers methods such as equals(), trim(), concat(), and parseInt(), along with examples and explanations for each program. Additionally, it includes a section on comparing dates using the Date class and methods like compareTo().
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java eg sufi

This document provides various Java programs demonstrating string manipulation techniques, including user input handling, string comparison, whitespace removal, string concatenation, and palindrome checking. It covers methods such as equals(), trim(), concat(), and parseInt(), along with examples and explanations for each program. Additionally, it includes a section on comparing dates using the Date class and methods like compareTo().
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

JAVA STRING PROGRAMS

JAVA PROGRAM TO GET USER INPUT AND PRINT ON SCREEN

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.

• Java equals() method is used to compare strings.


• Java equalsIgnoreCase() method can ignore the case.
• We cannot use == operator to compare two strings.

Example:

public class EqualCheck {


public static void main(String args[]){
String a = "AVATAR";
String b = "avatar";

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

Both strings are not equal

Both strings are equal

Here's a detailed explanation of what's happening inside this code snippet:

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.

Again, it is to be noted that the comparison is case-sensitive. So to perform a comparison which


ignores case differences, you have to use equalsIgnoreCase() method. As it compares two
strings, it considers A-Z to be the same as a-z.

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:

public class JavaTrim {


public static void main(String a[]){
String MyString = " Avatar ";
System.out.println(MyString.trim());
}
}

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:

public class JavaConcat {


public static void main(String[] args){
String a = "madtec";
String b = ".in";
String c = a.concat(b);
System.out.println(c);
}
}

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:

public class DuplStr {


public static void main(String argu[]) {
String str = "madtec";
int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (inp[i] == inp[j]) {
System.out.println(inp[j]);
cnt++;
break;
}
}
}
}
}

Program Output:

Duplicate Characters are: s o

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.

The steps involved are as follows:

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

public class StringtoArrayList {


public static void main(String args[]){
String strings = "99,42,55,81,79,64,22";
String str[] = strings.split(",");

List nl = new ArrayList();


nl = Arrays.asList(str);
for(String s: nl){
System.out.println(s);
}
}
}

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:

String strings = "99, 42, 55, 81, 79, 64, 22";

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:

Example: madam, lol, pop, radar, etc.

Palindrome String Check Program in Java

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

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + str.charAt(i);

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.

Consider a palindrome string: radar,

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:

public static int parseInt(String s)

Example:

public class StrToInt {

public static void main(String args[]) {


String str = "123";
int i = Integer.parseInt(str);
System.out.println(str + 50); //12350 because its concatenate to value.
System.out.println(i + 50); //173 because +(plus) is binary plus operator.
}

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.

Example Java Program:

import java.util.Scanner;

public class RemoveSpaces {

public static void main(String[] args) {


Scanner obj = new Scanner(System.in); /* create a object */

/* Taking user input */


System.out.print("Enter some text: ");
String sentence = obj.nextLine();

/* Check and remove all spaces. */


sentence = sentence.replaceAll("\\s", "");
System.out.println("Text after removing spaces: " + sentence);
}
}

Program Output:

Enter some text: m a d t e c


Text after removing spaces: madtec
JAVA PROGRAM TO FIND ASCII VALUE OF A CHARACTER

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:

public class PrintAsciiExample {

public static void main(String[] args) {


//Define the character whose ASCII value is to be found
char ch = 'G';
int ascii = ch; //Assign the character value to integer

//Print the output


System.out.println("The ASCII value of character '" + ch + "' is: " + ascii);

//Casting (character to integer)


int castAscii = (int) ch;

//Print the output


System.out.println("The ASCII value of character '" + ch + "' is: " + castAscii);
}
}

Program Output:

The ASCII value of 'G' is: 71


The ASCII value of 'G' is: 71

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

JAVA PROGRAM TO COMPARE BETWEEN TWO DATES.


This Java program demonstrate to compare between two dates.

There are two completely different ways to comparing dates in Java.

• Compare date in milliseconds by using getTime() method.


• compareTo() method can be use to compare two dates in Java.

Example:

import java.util.Date;

public class DisplayDate {


public static void main(String args[]) {
// Instantiate a objects
Date date1 = new Date();
Date date2 = new 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:

Date1 is equal to Date2

before() and after() and equals() method is also used to compare dates.
Example:

import java.util.Date;

public class DisplayDate {


public static void main(String args[]) {
// Instantiate a objects
Date date1 = new Date();
Date date2 = new 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();

System.out.print("Please enter maximum range: ");


maxRange=SC.nextInt();

for(int loop=1; loop<=10; loop++)


{
System.out.println(rand.nextInt(maxRange));
}
}
}
Program Output:

Please enter maximum range: 500


467
61
100
449
68
316
445
224
54
498

Sometimes situation arises where random numbers are required to be generated between the
ranges.

Generate a Random Number Between the Range


Example:

import java.util.Random;

class HelloWorld
{
public static void main(String[] args)
{
Random rand = new Random();

int minRange = 1000, maxRange= 5000;


int value = rand.nextInt(maxRange - minRange) + minRange;

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:

public class JavaSwapExample {

public static void main(String[] args) {


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

//swap the value


swap(x, y);
}

private static void swap(int x, int y) {


int temp = x;
x = y;
y = temp;

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:

System.out.println("Value of x is :" + x);

System.out.println("Value of y is :" +y);

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.

private static void swap(int x, int y)

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;

The two statements:

System.out.println("Value of x is :" + x);

System.out.println("Value of y is :" +y);

Prints the value after swapping.


JAVA PROGRAM TO PERFORM ADDITION, SUBRACTION,
MULTIPLICATION AND DIVISION
Java program to perform basic arithmetic operations of two numbers. Numbers are
assumed to be integers and will be entered by the user.

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:

import java.util .*;


class sici
{
public static void main (String argu[ ])
{
double pr, rate, t, sim,com;
Scanner sc=new Scanner (System. in);
System.out.println("Enter the amount:");
pr=sc.nextDouble();
System. out. println("Enter the No.of years:");
t=sc.nextDouble();
System. out. println("Enter the Rate of interest");
rate=sc.nextDouble();
sim=(pr * t * rate)/100;
com=pr * Math.pow(1.0+rate/100.0,t) - pr;
System.out.println("Simple Interest="+sim);
System.out. println("Compound Interest="+com);
}
}

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:

public class FindLargestSmallestNumber {

public static void main(String[] args) {

//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};

//assign first element of an array to largest and smallest


int smallest = numbers[0];
int largetst = numbers[0];

for (int i = 1; i < numbers.length; i++) {


if (numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}

System.out.println("Largest Number is : " + largetst);


System.out.println("Smallest Number is : " + smallest);
}
}

Program Output:

Output – FindLargestSmallestNumber

Largest Number is :98

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:

int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};

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

When …. numbers[i] is greater than largetst

largetst = numbers[i];

when numbers[i] greater than smallest

smallest = numbers[i];

The last two statements --

System.out.println("Largest Number is : " + largetst);

System.out.println("Smallest Number is : " + smallest);

Is used to print the largest and the smallest value which is extracted from the array.
JAVA PROGRAM TO FIND REVERSE NUMBER

This Java program is used to find reverse number.

Example:

public class FindReverseNumber {

public static void main(String[] args) {

//number defined
int number = 1234;
int reversedNumber = 0;
int temp = 0;

while (number > 0) {


//modulus operator used to strip off the last digit
temp = number % 10;

//create reversed number


reversedNumber = reversedNumber * 10 + temp;
number = number / 10;
}

//output
System.out.println("Reversed Number is: " + reversedNumber);
}
}

Program Output:

Output – FindReverseNumber

Reversed Number is :1246421


Explanation:

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;

reversedNumber = reversedNumber * 10 + temp;

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

This Java program is used to find the factorial.

Factorial of any number is !n.


For example, the factorial of 4 is 4*3*2*1.

Example:

public class FindFactorial {

public static void main(String[] args) {

int number = 4;
int factorial = number;

for (int i = (number - 1); i > 1; i--) {


factorial = factorial * i;
}

System.out.println("Factorial of " + number + " is " + factorial);


}
}

Program Output:

Output – FindFactorial

Factorial of 4 is 24
Explanation:

Here is a detailed explanation of what is happening within this code snippet -

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 {

public static void main(String[] args) {


int FibLength;
Scanner sc = new Scanner(System.in); //create object

System.out.print("Please enter length: ");


FibLength = sc.nextInt();

int[] num = new int[FibLength];


//initialized first element to 0
num[0] = 0;
//initialized second element to 1
num[1] = 1;

//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];
}

//Print Fibonacci Series


System.out.println("Fibonacci Series: ");
for (int i = 0; i < FibLength; i++) {
System.out.print(num[i] + " ");
}
}

}
Program Output:

Please enter length: 10

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:

public class JavaSwapExample {

public static void main(String[] args) {

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

//add both the numbers and assign it to first


x = x + y;
y = x - y;
x = x - 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

What is a Prime Number?

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.

Examples of prime numbers:

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.

Prime Number Check Program in Java

Program:

public class PrimeNumbers {


public static void main(String[] args) {
int num = 20; // Define the upper limit
int count; // Initialize counter for divisibility checks

// Iterate from 1 up to 'num' to identify prime numbers


for (int i = 1; i <= num; i++) {
count = 0; // Reset counter for each 'i'

// Check for divisibility from 2 up to i/2


for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
count++; // Increment if 'i' is divisible by 'j'
break; // Exit loop if a divisor is found
}
}

// If the count is 0, 'i' is prime


if (count == 0) {
System.out.println(i); // Output the prime number
}
}
}
}
Program Output:

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:

Here is a line-by-line explanation of the prime no program in Java:

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:

public class JavaInvertTriangle


{
public static void main(String args[])
{
int num = 9;
while(num > 0)
{
for(int i=1; i<=num; i++)
{
System.out.print(" "+num+" ");
}
System.out.print("\n");
num--;
}
}
}

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:

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

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:

public class JavaFlip {


public static void main(String[] args) {
if (Math.random() < 0.5){
System.out.println("Heads");
}else{
System.out.println("Tails");
}
}
}

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

System.out.println("enter the value of size");


int a = sc.nextInt();

int arr[] = new int[a];

for (int i = 0; < a; i++) {


arr[i] = sc.nextInt();
}
for (int i = 0; < a; i++) {
if (arr[i] % 2 == 0)
System.out.println("even");
else
System.out.println("odd");
}
}
}

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;

public class CircArea {

public static void main(String ag[]) {


int rad;
double pie = 3.14, ar;
Scanner s = new Scanner(System.in);
System.out.print("Enter radius of circle:");
rad = s.nextInt();
ar = pie * rad * rad;
System.out.println("Area of circle:" + ar);
}
}

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:

1. Calculate the power of a number through while loop.


2. Calculate the power of a number by through for loop.
3. Calculate the power of a number by through pow() function.

To calculate the power of any number, the base number and an exponent are required.

Syntax:

Power of a number = baseexponent

Example:

In case of 23

The base number is 2


The exponent is 3
So, the power will be the result of 2*2*2

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:

public class ExampleProgram {

public static void main(String[] args) {

int basenumber = 2, exponent = 3;


long temp = 1;

while (exponent != 0) {
temp *= basenumber;
--exponent;
}

System.out.println("Result: " + temp);


}
}

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:

public class ExampleProgram {

public static void main(String[] args) {

int basenumber = 2, exponent = 3;


long temp = 1;

for (;exponent != 0; --exponent) {


temp *= basenumber;
}

System.out.println("Result: " + temp);


}
}

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:

public class ExampleProgram {

public static void main(String[] args) {

int basenumber = 2, exponent = 3;


double pow = Math.pow(basenumber, exponent);

System.out.println("Result: " + pow);


}
}

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{

public static void main(String[] args) {

//Variable definition and assignment


int first, second;
Scanner obj = new Scanner(System.in); /* create a object */

//Taking user input


System.out.print("Enter an integer: ");
first = obj.nextInt();
System.out.print("Enter a second integer: ");
second = obj.nextInt();

//Add the numbers


int sum = first + second;

//Print the output


System.out.println("The sum of two integers "+first+" and "+second+" is: "+sum);
}
}

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;

public class Main {


public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

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;

public class Main {


public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

String evenOdd = (num % 2 == 0) ? "even" : "odd";


System.out.println(num + " is " + evenOdd);
}
}

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.

What is an Armstrong Number?

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.

Consider the number 1634:

(1^4) + (6^4) + (3^4) + (4^4)


= (1 * 1 * 1 * 1) + (6 * 6 * 6 * 6) + (3 * 3 * 3 * 3) + (4 * 4 * 4 * 4)
= 1 + 1296 + 81 + 256
= 1634

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.

Java Program to Check Armstrong Number

import java.util.Scanner;

public class ArmstrongNumberChecker {


public static void main(String[] args) {
int number, originalNumber, lastDigit, sum = 0, digits = 0, temp;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


number = scanner.nextInt();
originalNumber = number;

// Calculate the number of digits


temp = number;
while (temp != 0) {
temp /= 10;
digits++;
}

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

// Check if the sum equals the original number


if (sum == number)
System.out.printf("%d is an Armstrong number.\n", number);
else
System.out.printf("%d is not an Armstrong number.\n", number);
}
}

Program Output:

Here are some examples of running the program and the corresponding output:

Enter an integer: 123


123 is not an Armstrong number.
Enter an integer: 9474
9474 is an Armstrong number.

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

JAVA PROGRAM TO CALL METHOD IN SAME CLASS.


This Java program is used to call method in same class.

Example:

public class CallingMethodsInSameClass


{
// Method definition performing a Call to another Method
public static void main(String[] args) {
Method1(); // Method being called.
Method2(); // Method being called.
}

// Method definition to call in another Method


public static void Method1() {
System.out.println("Hello World!");
}

// Method definition performing a Call to another Method


public static void Method2() {
Method1(); // Method being called.
}
}

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:

public class Factorial {

public static void main(String[] args) {


//Variable definition and assignment
int num = 5;

//Call recursive function


long factorial = multiplyNumbers(num);

//Print the output


System.out.println("Factorial of " + num + " = " + factorial);
}

public static long multiplyNumbers(int num)


{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}

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:

public class Reverse {

public static void main(String[] args) {


String sentence = "Welcome back";
String reversed = reverse(sentence);
System.out.println("The reversed sentence is: " + reversed);
}

public static String reverse(String sentence) {


if (sentence.isEmpty())
return sentence;

return reverse(sentence.substring(1)) + sentence.charAt(0);


}
}

Program Output:

The reversed sentence is: kcab emocleW


OTHER JAVA FUNCTIONS
READING CONTENT IN JAVA FROM URL
You may sometimes need to read the HTML content of the web page from the URL,
and this Java program can be used to do this.

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;

public class ParseHTML {


public static void main(String[] args) {
try {
String parseLine; /* variable definition */
/* create objects */
URL URL = new URL("http://www.example.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(URL.openStream()));

while ((parseLine = br.readLine()) != null) {


/* read each line */
System.out.println(parseLine);
}
br.close();

} catch (MalformedURLException me) {


System.out.println(me);

} catch (IOException ioe) {


System.out.println(ioe);
}
}//class end
}
Program Output:

<!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" />


<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport"
content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-
color: #f0f0f2; margin: 0; padding: 0; font-family: "Open Sans", "Helvetica Neue", Helvetica,
Arial, sans-serif; } div { width: 600px; margin: 5em auto; padding: 50px; background-color:
#fff; border-radius: 1em; } a:link, a:visited { color: #38488f; text-decoration: none; } @media
(max-width: 700px) { body { background-color: #fff; } div { width: auto; margin: 0 auto; border-
radius: 0; padding: 1em; } } </style> </head> <body> <div> <h1>Example Domain</h1>
<p>This domain is established to be used for illustrative examples in documents. You may use
this domain in examples without prior coordination or asking for permission.</p> <p><a
href="http://www.iana.org/domains/example">More information...</a></p> </div> </body>
</html>.

You might also like