SlideShare a Scribd company logo
2. Java Language Basics
Variables.
Data Types.
Operators.
Java Decision Making
Statements.
 Java Iteration Statements.
Jumping Statements.
Type Casting.
Escape Sequences.
Arrays.
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;
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;
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
Program Output:
The value of variables before exchange :
A = 100 B = 200
The value of variables after exchange :
A = 200 B = 100
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
Program Output:
The value of variables before exchange :
A = 100 B = 200
The value of variables after exchange :
A = 200 B = 100
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 */
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 ).
 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.
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
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
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.
/* 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);
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
/** 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);
}
}
Program Output:
Deposited Amount : 100000
Duration : 5
Rate of Interest : 14.5
Simple Interest : 72500.0
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.
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.
// 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();
System.out.print("Enter a double value : ");
double d=scan.nextDouble();
System.out.print("Enter boolean value : ");
boolean bool=scan.nextBoolean();
System.out.println("nThe Values You Entered Are:");
System.out.println("Byte : "+b);
System.out.println("Short : "+s);
System.out.println("Int : "+i);
System.out.println("Long : "+l);
System.out.println("Float : "+f);
System.out.println("Double : "+d);
System.out.println("Boolean : "+bool);
}
}
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
/* 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);
}
}
/* 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);
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);
}
}
//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);
Program Output:
Deposited Amount : 7500
Duration : 2
Rate of Interest : 4
Compound Interest : 611.9994049072375
System.out.println(“Rate of Interest : “+rate);
System.out.println("Compound Interest = "+
compoundInterest);
}
}
//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");
}
}
Program Output:
Enter Number of Days : 100
In 100 Days Light Will Travel About 1607040000000 Miles
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.
 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
/** 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);
Program Output:
100 + 30 = 130
100 -- 30 = 70
100 x 30 = 3000
100 / 30 = 3
100 % 30 = 10
System.out.println(firstNumber + “/” +secondNumber+ “=” +
quotient);
System.out.println(firstNumber + “%” +secondNumber+
“=” + remainder);
}
}
 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.
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.
 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.
 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
// 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
}
}
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.
/* 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);
}
}
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.
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.
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)
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
 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”);
}
 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
Example:
int age=scan.nextInt( );
if(age>=18){
System.out.println(“You are an adult “);
System.out.println(“Please do your vote”);
}
else{
System.out.println(“You are a minor”);
System.out.println(“Please wait till you pass 18”);
}
/* 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);
}
}
}
/* 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);
}
}
/* 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”);
}
}
}
 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
}
/* 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”);
}
else if(day==4){
System.out.println(“WEDNESDAY”);
}
else if(day==5){
System.out.println(“THURSDAY”);
}
else if(day==6){
System.out.println(“FRIDAY”);
}
else if(day==7){
System.out.println(“SATURDAY”);
}
else{
System.out.println(“Invalid Day Number!!!”);
}
}
}
// 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”);
}
else if(totalMarks>=50){
System.out.println(“Second Class”);
System.out.println(“Average”);
}
else{
System.out.println(“Failed”);
System.out.println(“Better Try Next Time”);
}
}
}
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)]
}
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.
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”);
}
// 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;
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”);
}
}
}
// 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;
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.
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.
// 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
// 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
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
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.
Example:
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
/* program to print sum of first 100 numbers */
class WhileDemo {
public static void main(String[] args){
int count = 1,sum=0;
while (count <= 100) {
sum=sum + count;
count++;
}
}
}
// 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;
}
}
}
/* 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);
}
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
// 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++;
}
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!!
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.
// 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
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:
*************************
Assignment Write programs to generate the following outputs.
A) * * * * *
* * * * *
* * * * *
* * * * *
* * * * *
B) *
* *
* * *
* * * *
* * * * *
C) * * * * *
* * * *
* * *
* *
*
D) *
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
E) *
* *
* * *
* * * *
* * * * *
// 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;
}
}
}
// 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);
}
}
}
// 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;
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
Java Programming Tutorials Basic to Advanced 2
Ad

More Related Content

Similar to Java Programming Tutorials Basic to Advanced 2 (20)

C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
Abou Bakr Ashraf
 
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
UNIT - 1-  Ood ddnwkjfnewcsdkjnjkfnskfn.pptxUNIT - 1-  Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
datypes , operators in c,variables in clanguage formatting input and out put
datypes , operators in c,variables in clanguage formatting input  and out putdatypes , operators in c,variables in clanguage formatting input  and out put
datypes , operators in c,variables in clanguage formatting input and out put
MdAmreen
 
Class 8 - Java.pptx
Class 8 - Java.pptxClass 8 - Java.pptx
Class 8 - Java.pptx
sreedevi143432
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
Lovely Professional University
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
Lovely Professional University
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
Programming_in_C_language_Unit5.pptx course ATOT
Programming_in_C_language_Unit5.pptx course ATOTProgramming_in_C_language_Unit5.pptx course ATOT
Programming_in_C_language_Unit5.pptx course ATOT
jagmeetsidhu0012
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
ahmed abugharsa
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer farooq
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Java Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdfJava Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdf
Aditya Kumar
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
WondimuBantihun1
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
Abou Bakr Ashraf
 
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
UNIT - 1-  Ood ddnwkjfnewcsdkjnjkfnskfn.pptxUNIT - 1-  Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
datypes , operators in c,variables in clanguage formatting input and out put
datypes , operators in c,variables in clanguage formatting input  and out putdatypes , operators in c,variables in clanguage formatting input  and out put
datypes , operators in c,variables in clanguage formatting input and out put
MdAmreen
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
Programming_in_C_language_Unit5.pptx course ATOT
Programming_in_C_language_Unit5.pptx course ATOTProgramming_in_C_language_Unit5.pptx course ATOT
Programming_in_C_language_Unit5.pptx course ATOT
jagmeetsidhu0012
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer farooq
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Java Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdfJava Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdf
Aditya Kumar
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 

Recently uploaded (20)

apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Ad

Java Programming Tutorials Basic to Advanced 2

  • 1. 2. Java Language Basics Variables. Data Types. Operators. Java Decision Making Statements.  Java Iteration Statements. Jumping Statements. Type Casting. Escape Sequences. Arrays.
  • 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); } }
  • 17. Program Output: Deposited Amount : 100000 Duration : 5 Rate of Interest : 14.5 Simple Interest : 72500.0
  • 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();
  • 21. System.out.print("Enter a double value : "); double d=scan.nextDouble(); System.out.print("Enter boolean value : "); boolean bool=scan.nextBoolean(); System.out.println("nThe Values You Entered Are:"); System.out.println("Byte : "+b); System.out.println("Short : "+s); System.out.println("Int : "+i); System.out.println("Long : "+l); System.out.println("Float : "+f); System.out.println("Double : "+d); System.out.println("Boolean : "+bool); } }
  • 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);
  • 27. Program Output: Deposited Amount : 7500 Duration : 2 Rate of Interest : 4 Compound Interest : 611.9994049072375 System.out.println(“Rate of Interest : “+rate); System.out.println("Compound Interest = "+ compoundInterest); } }
  • 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"); } }
  • 29. Program Output: Enter Number of Days : 100 In 100 Days Light Will Travel About 1607040000000 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);
  • 33. Program Output: 100 + 30 = 130 100 -- 30 = 70 100 x 30 = 3000 100 / 30 = 3 100 % 30 = 10 System.out.println(firstNumber + “/” +secondNumber+ “=” + quotient); System.out.println(firstNumber + “%” +secondNumber+ “=” + remainder); } }
  • 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
  • 47. Example: int age=scan.nextInt( ); if(age>=18){ System.out.println(“You are an adult “); System.out.println(“Please do your vote”); } else{ System.out.println(“You are a minor”); System.out.println(“Please wait till you pass 18”); }
  • 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”); }
  • 53. else if(day==4){ System.out.println(“WEDNESDAY”); } else if(day==5){ System.out.println(“THURSDAY”); } else if(day==6){ System.out.println(“FRIDAY”); } else if(day==7){ System.out.println(“SATURDAY”); } else{ System.out.println(“Invalid Day Number!!!”); } } }
  • 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.
  • 68. Example: int i=1; while(i<=10){ System.out.println(i); i++; } /* program to print sum of first 100 numbers */ class WhileDemo { public static void main(String[] args){ int count = 1,sum=0; while (count <= 100) { sum=sum + count; count++; } } }
  • 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: *************************
  • 77. Assignment Write programs to generate the following outputs. A) * * * * * * * * * * * * * * * * * * * * * * * * * B) * * * * * * * * * * * * * * * C) * * * * * * * * * * * * * * * D) * * * * * * * * * * * * * * * * * * * * * * * * * E) * * * * * * * * * * * * * * *
  • 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