2. Variables.
A variable is a location in the computer’s memory where a value is
stored and from which the value can be retrieved later.
Variable must be declared before they can be used.
Variable declaration syntax:
datatype variableName;
Where datatype is a valid data type in Java.
variableName is a valid variable name given by the user.
Eg:- int marks;
float rateOfInterest;
char sex;
double compoundInterest;
3. Declaration and Initialization:
Variables can be declared and initialized in a single line.
Syntax:
datatype variableName = value;
value is the valid value given by the user.
Egs:-
float rateOfInterest = 10.25F;
double pi=22/7;
long annualIncome=500000000;
Multiple variables[of same kind] can be declared and/or initialized in a
single line.
Eg:-
float amount=50000, rate=5.5F, duration=5, simpleInterest;
int day,month,year,age;
4. class NumberExchange
{
public static void main(String [ ] args)
{
int a = 100, b = 200, temp;
System.out.println(“The value of variables before exchange :”);
System.out.println(“A = “ + a + “t” + “B = “ + b);
//exchanging the values
temp = a; // temp = 100
a=b; // a = 200
b=temp; // b= 100
System.out.println(“nThe value of variables after exchange :”);
System.out.println(“A = “ + a + “t” + “B = “ +b);
}
}
// program to exchange two numbers by using a third variable
5. Program Output:
The value of variables before exchange :
A = 100 B = 200
The value of variables after exchange :
A = 200 B = 100
6. class SwapNumbers
{
public static void main(String [ ] args)
{
int a = 100, b = 200;
System.out.println(“The value of variables before exchange :”);
System.out.println(“A = “ + a + “t” + “B = “ + b);
//exchanging the values
a = a + b; // a =100 + 200 = 300
b = a – b; // b =300 – 200 = 100
a = a – b; // a = 300 – 100 = 200
System.out.println(“nThe value of variables after exchange :”);
System.out.println(“A = “ + a + “t” + “B = “ +b);
}
}
// program to exchange two numbers without using a third variable
7. Program Output:
The value of variables before exchange :
A = 100 B = 200
The value of variables after exchange :
A = 200 B = 100
8. class Circle
{
public static void main(String [ ] args)
{
double radius,area,circumference;
radius = 10; //set the value 10 to radius
area = Math.PI * radius * radius; // A=PIr^2
circumference = 2 * Math.PI * radius; // 2PIr
System.out.println(“Area = “ + area);
System.out.println(“Circumference = “ + circumference);
}
}
Program Output:
Area = 314.1592653589793
Circumference = 62.83185307179586
/* program to set the radius of a circle , find and print its area &
circumference */
9. Variable Naming Rules:
Naming conventions are to be followed as they ensure good
programming practices.
Variable name may consists of Unicode letters and digits,
underscore(__) and dollar sign ($).
A variable name must begin with a letter, dollar sign ($), or
underscore (__). The convention however, is to always begin your
variable names with a letter, not with dollar($) or
underscore(__).
A variable name must not be a keyword or reserved word in
Java.
Variable names in Java are case sensitive. (For example,
number and Number refers to two different variables.
If a variable name comprises a single word, the name should
be in lower case. (For example velocity or ratio ).
10. If a variable name consists of more than one word, the first letter of
each subsequent word should be capitalized.
(For example employeeNumber or accountBalance or numberOfDigits).
Note: What is Unicode?
Unicode is a 16 bit character set, which contains all the characters
commonly used in information processing. It is an attempt to
consolidate the alphabets of the world’s various languages in to a single
and international character set.
11. Data Types
The data type of a variable, determines the type of the data that can be
stored in the variable.
The data type of a variable tells the compiler how much space should
be allocated in the memory for that variable.
Data Types are of two kinds in Java.
Data Types
Primitive Data Types Derived Data Types
12. A primitive data type, also called build in data type, stores a single value
stores a single value, normally a literal of some sort, such as a number or
character.
Data Type Description Range
byte 8 bit signed integer -128 To 127
short 16 bit signed integer -32768 To 32767
int 32 bit signed integer -2,147,483,648 To
2,147,483,647
long 64 bit signed integer -9,223,372,036,854,775,808 To
9,223,372,036,854,775,807
float 32 bit floating-point 1.4E-045 To 3.4E+038
double 64 bit floating-point 4.9E-324 To 1.8E+308
char 16 bit Unicode
character
0 To 65535
boolean Stores a true or false True/False
13. Data Type Description
Array A collection of several items of the same data types.
Class A collection of variables and methods that operates
on the variables.
Interface A type of class that contains method declarations
and constants.
Reference Data Types also called Derived Data Types.
There are three reference data types in Java.
14. /* program to show the usage of all data types */
class DataTypes {
public static void main(String [ ] args){
byte byteValue=127;
short shortValue=32767;
int intValue=2147483647;
long longValue=9223372036854775807L;
float floatValue=123.456F;
double doubleValue=123456.123456;
char charValue='X';
boolean boolValue=true;
System.out.println("Byte Value : " +byteValue);
System.out.println("Short Value : " +shortValue);
System.out.println("Int Value : " +intValue);
System.out.println("Long Value : " +longValue);
System.out.println("Float Value : " +floatValue);
15. System.out.println("Double Value : " +doubleValue);
System.out.println("Char Value : " +charValue);
System.out.println("Boolean Value: " +boolValue);
}
}
____________________________________________________________
Program Output:
Byte Value : 127
Short Value : 32767
Int Value : 2147483647
Long Value : 9223372036854775807
Float Value : 123.456
Double Value : 123456.123456
Char Value : X
Boolean Value : true
16. /** program to calculate simple interest using the equation
I=PNR/100
Here P is the deposit amount, N is the years of deposit, R is the rate
of interest */
class SimpleInterest{
public static void main(String [ ] args){
long amount = 100000; //P
int years = 5; //N
float rate=14.5; //R
double simpleInterest = amount * years * rate / 100;
System.out.println(“Deposited Amount : “+amount);
System.out.println(“Duration : “+years);
System.out.println(“Rate of Interest : “+rate);
System.out.println(“Simple Interest : “+simpleInterest);
}
}
18. Scanner Class
The Scanner class allows the user to read values of various types.
To use the Scanner class create an object of Scanner as follows:
Scanner input = new Scanner(System.in);
To create a Scanner object,
pass the InputStream object
to the constructor.
System.in is the
InputStream Object
Here input is an object of
Scanner class.
The Scanner class belongs to the java.util package. (A package is a
collection of classes). The Scanner looks for tokens in the users input. A
token is a series of characters that ends with delimiters. A delimiter can
be a whitespace, a tab character or a carriage return.
19. Methods of Scanner class that can be used to accept numerical values
from the keyboard.
Method Description
nextByte( ) Return the next token as a byte value.
nextShort( ) Return the next token as a short value.
nextInt( ) Return the next token as an int value.
nextFloat( ) Return the next token as a float value.
nextDouble( ) Return the next token as a double value.
nextLine( ) Return the inputs as a String value.
nextBoolean( ) Return the next token as a boolean value.
20. // program to demonstrate key board reading
import java.util.Scanner;
class Reading{
public static void main(String ... args){
Scanner scan=new Scanner(System.in);
System.out.print("Enter a byte value : ");
byte b=scan.nextByte();
System.out.print("Enter a short value : ");
short s =scan.nextShort();
System.out.print("Enter an int value : ");
int i=scan.nextInt();
System.out.print("Enter a long value : ");
long l=scan.nextLong();
System.out.print("Enter a float value : ");
float f=scan.nextFloat();
22. Program Output:
Enter a byte value : 127
Enter a short value : 9847
Enter an int value : 9847903
Enter a long value : 9847903805
Enter a float value : 12.25
Enter a double value : 123.456
Enter boolean value : false
The Values You Entered Are:
Byte : 127
Short : 9847
Int : 9847903
Long : 9847903805
Float : 12.25
Double : 123.456
Boolean : false
23. /* program to read strings*/
import java.util.Scanner;
class ReadString{
public static void main(String [ ] args){
String firstName;
String lastName;
Scanner scan=new Scanner(System.in);
System.out.print("Enter First Name : ");
firstName=scan.nextLine();
System.out.print("Enter Last Name : ");
lastName=scan.nextLine();
System.out.println(firstName + " " +lastName);
}
}
24. /* program to show pow( ) and sqrt( ) methods in Java Math class
* Usage is Math.pow(m,n) where m is the base and n is the index/power
* Eg:- Math.pow(10,2) will give the result 100
Math.sqrt(m) where integer is an integer, sqrt will return the square
root of ‘m’
Math.PI is a constant in Math class that contains PI value.*/
import java.util.Scanner;
class JavaMaths {
public static void main(String [ ]args){
Scanner read=new Scanner(System.in);
int base,index;
System.out.print("Enter base and index : ");
base=read.nextInt();
index=read.nextInt();
double result=Math.pow(base,index);
System.out.print("Enter an Integer : ");
int number=read.nextInt();
double root=Math.sqrt(number);
25. Program Output:
Enter base and index : 2 10
Enter an Integer : 100
2 raised to the power 10 is 1024.0
The square root of 100 is 10.0
PI = 3.141592653589793
System.out.println(base+" raised to the power "+index+
" is "+result);
System.out.println("The square root of "+number+
" is "+root);
System.out.println("PI = "+Math.PI);
}
}
26. //program to calculate compound interest using the equation
CI=P*[1+R/100]^N-P
class CompoundInterest
{
public static void main(String [ ]args)
{
long amount=7500;
float rate=4;
int years=2;
double compoundInterest;
//calculating CI
compoundInterest=amount*Math.pow((1+rate/100),years)-amount;
System.out.println(“Deposited Amount : “+amount);
System.out.println(“Duration : “+years);
28. //program to calculate the distance travelled by light in specified days
import java.util.Scanner;
class LightSpeed{
public static void main(String [ ] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Number of Days : ");
int days=s.nextInt();
long seconds=days*60*60*24; //convert to seconds
int lightSpeed=186000;//approx.speed of light in miles/sec
long distance=seconds*lightSpeed; //calculate the distance
System.out.print("In "+days);
System.out.print(" Days Light Will Travel About ");
System.out.println(distance+" Miles");
}
}
30. Operators.
All programming language provides some mechanisms for performing
various operations on data stored in variables.
A set of symbols is used to indicate the kind of operations to be
performed on data. These symbols are called Operators.
Operators are classified as follows:
Arithmetic Operators.
Assignment Operators.
Equality & Relational Operators.
The Conditional Operators.
Unary Operators.
Bitwise & Bit Shift Operators.
31. Arithmetic Operators.
Operator Description Example
+ Addition- Returns the sum of its
operands
SUM=A+B
_ Subtraction- Return the difference of its
operands
DIF=A-B
* Multiplication- Return the product of its
operands.
PDT=A*B
/ Division- Return the result of division
operation of its operands.
DIV=A/B
% Remainder- Return the remainder from
the division operation of its operands.
REM=A%B
32. /** program to show all arithmetical operations */
class Arithmetic
{
public static void main(String [ ]a)
{
int firstNumber=100, secondNumber=30;
int sum = firstNumber + secondNumber;
int difference = firstNumber – secondNumber;
int product = firstNumber * secondNumber;
int quotient = firstNumber / secondNumber;
int remainder = firstNumber % secondNumber;
// printing the result
System.out.println(firstNumber + “+” +secondNumber+ “=” + sum);
System.out.println(firstNumber + “-” +secondNumber+ “=” +
difference);
System.out.println(firstNumber + “x” +secondNumber+ “=” +
product);
34. Assignment Operator ( = )
This operator is used to assign the value on its right to the operand on
its left.
Egs:-
int age=24;
assigns the value 24 to the variable age.
String course=“MASTER OF COMPUTER APPLICATIONS”;
assigns a string to the variable course.
35. Equality & Relational Operators.
Equality and Relational Operators test the relation between two
operands. An expression involving relational operators always
evaluates to a boolean value.(either true or false).
Operator Description
== Check equality between two operands.
!= Check inequality between two operands.
> Greater than- check if the value on its left side is greater
than the value on its right.
< Less than- check if the value on its left side is less than
the value on its right.
>= Greater than or Equal to- check if the value on its left
side is greater than or equal to the value on its right.
<= Less than or Equal to- check if the value on its left side
is less than or equal to the value on its right.
36. Conditional Operators.
Conditional operators works on two boolean expressions. Second
expression is evaluated only if needed.
Operator Description
&& An expression will be on its left side and another
expression will be on its right side. Return true only if
both the expression are true.
|| An expression will be on its left side and another
expression will be on its right side. Return true if either
expression is true, or both the expressions are true.
37. Unary Operators.
Operator Description
+ Unary plus operator; indicates positive value
(numbers are positive without this, however)
- Unary minus operator; negates an expression .
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of
a boolean
38. // program to demonstrate unary operators
class UnaryDemo {
public static void main(String[] args){
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}
39. The increment/decrement operators can be applied before (prefix) or
after (postfix) the operand. The code result++; and ++result; will both
end in result being incremented by one.
The only difference is that the prefix version (++result) evaluates to the
incremented value, whereas the postfix version (result++) evaluates to
the original value.
If you are just performing a simple increment/decrement, it doesn't
really matter which version you choose. But if you use this operator in
part of a larger expression, the one that you choose may make a
significant difference.
40. /* program to demonstrate pre increment/post increment
* and predecrement/post decrement
*/
class PrePost{
public static void main(String []args){
int a=1,b=1,c;
c=a++; //first assign a to c, then increment a. now c=1 a=2
System.out.println(a+" "+c);
c=++b; //first increment b then assign b to c. now c=2 b=2
System.out.println(b+" "+c);
a=1; // now a = 1
b=1; // now b = 1
c=a--; //first assign a to c, then decrement a. now c=1 a=0
System.out.println(a+" "+c);
c=--b; //first decrement b then assign b to c. now c=0 b=0
System.out.println(b+" "+c);
}
}
41. Bitwise & Bit shift Operators.
Bitwise operators works on binary representations of data. Theses are
used to change individual bits in an operand.
Bitwise shift operators are used to move all the bits in the operand left
or right a given number of times.
Operator Description
& Bitwise And- Compares two bits, and generate a result
1 if both bits are 1, otherwise it returns 0.
| Bitwise Or- Compares two bits, and generate a result 0
if both bits are 0, otherwise, it returns 1.
^ Exclusive Or- Compares two bits, and generate a result
1, if exactly one bit is 1, otherwise it returns 0.
~ Bitwise Not- Complement – Used to invert all of the bits
of the operand.
42. Operator Description
>> Shift Right- Moves all bits in a number to the right a
specified number of times.
<< Shift Left- Moves all bits in a number to the left a
specified number of times.
43. Assignments
1. Write a program to set two numbers and display the results of the
following operations.
(a). Number1 & Number 2
(b). Number1 | Number 2
(c). ~(Number1)
(d). ~(Number2)
(e). ~(Number1) & ~ (Number2)
(f). ~(Number1) ! ~ (Number2)
(g). (Number1>>Number2)
(h). (Number1<<Number2)
44. Java Conditional Statements.
Java program is a set of statements which are executed sequentially in
the order in which they appear.
Decision making/ Conditional statements enable us to change the flow
of the program based on the evaluation of a condition.
The decision making or conditional statements supported by Java are:
if..
switch
The if statement.
if statements can be implemented in three forms based on the
complexity of the condition to be tested.
simple if
if… else
if…..else if……..else
45. Simple If:
Here a condition is tested and if it is true, a statement/ block of
statements associated with if is executed. If the condition is false, the
control is transferred directly outside the if block.
Syntax:
if(condition){
//statement(s) to be executed if the condition is true
}
Example:
int age=scan.nextInt( );
if(age>=18){
System.out.println(“You are an adult “);
System.out.println(“Please do your vote”);
}
46. if………else……..
Here a condition is evaluated and if it is true, the code/block of
code associated with if is executed.
If the condition evaluated to be false, then the code/block of code
associated with else is executed.
Syntax:
if(condition){
//statement(s) to be executed if the condition is true
}
else{
//statement(s) to be executed if the condition is false
48. /* program to read two numbers and print the largest*/
import java.util.Scanner;
class Larger{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter 2 Integers :”);
int a= s.nextInt( );
int b= s.nextInt( );
if(a>b){
System.out.println(“Largest is “+a);
}
else{
System.out.println(“Largest is “+a);
}
}
}
49. /* read three numbers and print its largest */
import java.util.Scanner;
class Largest{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter 3 Integers :”);
int a= s.nextInt( );
int b= s.nextInt( );
int c= s.nextInt( );
int largest;
if(a>b)
largest=a;
else
largest=b;
if(c>largest)
largest=c;
System.out.println(“Largest number is “+largest);
}
}
50. /* Read an year and test whether it is a leap year or not
Leap Year- a year that can be (divisible by 4 and not divisible by 100) or
divisible by 400 */
import java.util.Scanner;
class LeapYear{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter a Year : ”);
int year= s.nextInt( );
if((year%4==0&&year%100!=0)||year%400==0){
System.out.println(year + “Is a Leap Year”);
}
else{
System.out.println(year + “Is Not a Leap Year”);
}
}
}
51. Multiple if statements/ if…else if ladder.
Here many conditions are evaluated sequentially starting from the top
of the ladder and moving downwards. When a true condition is found,
the statement(s) associated with it is executed.
Syntax:
if(condition -1){
//statement(s) to be executed if the condition-1 is true
}
else if(condition-2){
//statement(s) to be executed if the condition-1 is true
}
….
else if(condition-N){
//statement(s) to be executed if the condition-N is true
}
else{
//statement(s) to be executed if all conditions are false
}
52. /* read a day number (1-7) and print it day name */
import java.util.Scanner;
class DayInWords{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter a Day Number(1-7) :”);
int day=s.nextInt( );
if(day==1){
System.out.println(“SUNDAY”);
}
else if(day==2){
System.out.println(“MONDAY”);
}
else if(day==3){
System.out.println(“TUESDAY”);
}
54. // program to read total marks and print the result.
import java.util.Scanner;
class ScoreCard{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter Total Marks : “);
int totalMarks=s.nextInt( );
if(totalMarks>=80){
System.out.println(“First Class With Distinction”);
System.out.println(“Excellent”);
}
else if(totalMarks>=60){
System.out.println(“First Class”);
System.out.println(“Very Good”);
}
56. The switch statement [multiple branching statement]
The switch case statement is used when a variable needs to be compared
against different values.
Syntax:
switch(expression){
case value-1: statement(s);
break;
case value-2: statement(s);
break;
case value-3: statement(s);
break;
………….
………….
case value-N: statement(s);
break;
[default : statement(s)]
}
57. The switch keyword is followed by an integer expression enclosed in
parentheses. The expression must be of type int, char, byte, short.
Each case value must be a unique literal.
The case keyword is followed by an integer constant and a colon.
The case statement might be followed by a code sequence, that are
executed when the switch expression and the case value match.
The switch statement executes the case corresponding to the value of
the expression.
The break statement terminates the statement sequence, and continues
with the statement following the switch.
If there is no corresponding case value, the default clause is executed.
58. Example:
int choice=scanner.nextInt( );
switch(choice){
case 1: System.out.println(“Addition”);
break;
case 2: System.out.println(“Subtraction”);
break;
case 3: System.out.println(“Multiplication”);
break;
case 4: System.out.println(“Division”);
break;
case 5: System.out.println(“Remainder Division”);
break;
default: System.out.println(“No Operation”);
}
59. // Enter a digit and print it in words using switch
import java.util.Scanner;
class NumberInWords{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter a one digit number : “);
int digit=s.nextInt( );
switch(digit){
case 1: System.out.println(“One”);
break;
case 2: System.out.println(“Two”);
break;
case 3: System.out.println(“Three”);
break;
case 4: System.out.println(“Four”);
break;
60. case 5: System.out.println(“Five”);
break;
case 6: System.out.println(“Six”);
break;
case 7: System.out.println(“Seven”);
break;
case 8: System.out.println(“Eight”);
break;
case 9: System.out.println(“Nine”);
break;
case 0: System.out.println(“Zero”);
break;
default: System.out.println(“Not a Digit”);
}
}
}
61. // program to print the seasons using switch
class Season{
public static void main(String [ ]args){
int month=4;
switch(month){
case 12:
case 1:
case 2: System.out.println(“Season : Winter”);
break;
case 3:
case 4:
case 5: System.out.println(“Season : Spring”);
break;
case 6:
case 7:
case 8: System.out.println(“Season : Summer”);
break;
62. case 9:
case 10:
case 11: System.out.println(“Season : Autumn”);
break;
default:
System.out.println(“Bogus Month!!!”);
}
}
}
Assignment.
Assume that USA uses the following tax code for calculating their
annual income:
First US$ 5000 of Income : 0.00 Tax
Next US$ 10000 of Income : 10% Tax
Next US$ 20000 of Income : 15% Tax
An Amount above $ 35000 : 20% Tax
Write a program for the problem given above.
63. Java Iteration Statements[Loops]
A loop repeatedly executes the same set of instructions until a
termination condition is met.
The for loop:
The for statement provides a compact way to iterate over a range of
values.
Syntax:
for (initialization; termination; increment/decrement) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as
the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment/decrement expression is invoked after each iteration
through the loop; it is perfectly acceptable for this expression to
increment or decrement a value.
64. // for loop demonstration
class ForDemo {
public static void main(String[] args){
for(int i =1; i <10; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
65. // read a limit N and sum the series 1+2+3+4+5+……………+N
import java.util.Scanner;
class Sum{
public static void main(String [ ] args){
Scanner s=new Scanner(System.in);
System.out.print(“Enter a limit (N): “);
int limit=s.nextInt( );
int sum=0;
for(int i = 1; i < = limit; i ++){
sum=sum+i;
}
System.out.println(“1+2+3+4+5+…………+”+limit+”=“+sum);
}
}
Program Output:
Enter a limit (N): 15
1+2+3+4+5+.....+15=120
66. Assignment
Write program to sum the following series.
1. 1+3+5+7+9+…………………………………..+N
2. 2+4+6+8+10+…………………………………+N
3. 1+1/2+1/3+1/4+1/5………………………….+1/N
67. The while loop.
The while statement in Java is used to execute a statement or a block of
statements while a particular condition is true.
The condition is checked before the statements are executed.
Syntax:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean
value.
If the expression evaluates to true, the while statement executes the
statement(s) in the while block.
The while statement continues testing the expression and executing its
block until the expression evaluates to false.
69. // read a number and generate its divisors.
import java.util.*;
class Divisors{
public static void main(String [ ] args){
Scanner in=new Scanner(System.in);
System.out.print(“Enter an Integer : “);
int number=in.nextInt( );
int i=1;
while(i<=number/2){
if(number % i==0)
System.out.println(i);
i=i+1;
}
}
}
70. /* write a program to check whether a given number is Armstrong.
*A number is said to be Armstrong if sum of cubes of individual digits
* is equal to the original number. Eg:- 153,371. 1^3+5^3+3^3=153 */
import java.util.*;
class Armstrong{
public static void main(String [ ] args){
Scanner in=new Scanner(System.in);
System.out.print(“Enter an Integer : “);
int number=in.nextInt( );
int digit, sum=0,copy=number;
while(number>0){
digit=number%10;
number=number/10;
sum=sum + (digit*digit*digit);
}
71. if(copy==sum)
System.out.println(copy+ “ Is an Armstrong Number”);
else
System.out.println(copy+ “ Is Not an Armstrong Number”);
}
}
------------------------------------------------------------------------------------------
Program Output:
Enter an Integer : 371
371 Is an Armstrong Number
72. // program to test whether a given number is prime or not
// a number is said to be prime, if it is divisible only by 1 and itself
import java.util.*;
class Prime{
public static void main(String [] args){
int number,i,prime=1;
Scanner in=new Scanner(System.in);
System.out.print("Enter an Integer : ");
number=in.nextInt();
i=2;
while(i<=number/2){
if(number%i==0){
prime=0;
break;
}
i++;
}
73. if(prime==1)
System.out.println(number + " is a prime number!!");
else
System.out.println(number + " is not a prime number!!");
}
}
-------------------------------------------------------------------------------------------
Program Output:
F:WORKSJava>java Prime
Enter an Integer : 17
17 is a prime number!!
F:WORKSJava>java Prime
Enter an Integer : 18
18 is not a prime number!!
74. The do…while loop:
The Java programming language also provides a do-while statement,
which can be expressed as follows:
do {
statement(s)
}
while (expression);
The difference between do-while and while is that do-while evaluates its
expression at the bottom of the loop instead of the top. Therefore, the
statements within the do block are always executed at least once.
75. // program to find the sum of all even numbers up to 100
class SumEven{
public static void main(String args[ ]){
int sum=0,i=2;
do{
sum=sum+i;
i=i+2;
}
while(i<=100);
System.out.println(“2+4+6+8+….+100 = “+sum);
}
}
------------------------------------------------------------------------------------------
Program Output:
2+4+6+8+.....+100 = 2550
76. Nested Loops [Loop inside another loop]
One loop can be placed inside another loop. In this case the inner loop
is completely executed in each iterations of the outer loop.
Example:
class InnerLoop{
public static void main(String [ ] args){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
System.out.print(“*”);
}
}
}
}
------------------------------------------------------------------------------------------
Program Output:
*************************
78. // code for E
class Pattern{
public static void main(String []args){
int s=10,n=1,i,j,k;
for(i=1;i<=5; i++){
for(j=1;j<=s; j++)
System.out.print(" ");
for(k=1;k<=n; k++)
System.out.print("*");
System.out.println();
n=n+2;
s=s-1;
}
}
}
79. // program to generate first 20 Fibonacci Numbers .
// in a Fibonacci sequence, the previous two numbers are add to
// generate the instance number
// Eg:- 0,1,1,2,3,5,8,13,21,34………………..
class Fibonacci
{
public static void main(String [] args){
int firstNumber=0,secondNumber=1;
int sum=0,n;
System.out.print(firstNumber+", "+secondNumber);
for(int i=3;i<=20;i++){
sum=firstNumber+secondNumber;
firstNumber=secondNumber;
secondNumber=sum;
System.out.print(", "+sum);
}
}
}
80. // read a four digit number and print it in words
import java.util.*;
class PrintInWords{
public static void main(String []args){
Scanner in=new Scanner(System.in);
System.out.print("Enter a 4 digit number : ");
int number=in.nextInt();
int divisor=1000,digit;
while(divisor>0){
digit=number/divisor;
number=number%divisor;
divisor=divisor/10;
switch(digit){
case 0:System.out.print("Zero "); break;
case 1:System.out.print("One "); break;
case 2:System.out.print("Two "); break;
case 3:System.out.print("Three "); break;
81. case 4:System.out.print("Four "); break;
case 5:System.out.print("Five "); break;
case 6:System.out.print("Six "); break;
case 7:System.out.print("Seven "); break;
case 8:System.out.print("Eight "); break;
case 9:System.out.print("Nine "); break;
}
}
}
}
------------------------------------------------------------------------------------------
Program Output:
Enter a 4 digit number : 1234
One Two Three Four
Enter a 4 digit number : 9847
Nine Eight Four Seven