Академический Документы
Профессиональный Документы
Культура Документы
The for loop is the easiest among other loops. All its parts are gathered in one
place. It is an entry-controlled loop.
An infinite loop is a loop that never terminates. It can be created in for loop by
omitting the test expression. For other loops, the test expression should always
evaluate to true.
An empty loop is one that does not contain any loop body.
The while loop is another entry-controlled loop. In this loop, the loop control
variable is initialized before the loop begins, and the variable is updated inside
the loop body.
The do-while loop is an exit-controlled loop. it evaluates the test expression at
the bottom of the loop, after executing the loop body.
A nested loop is one in which a loop may contain another loop within its body.
The break keyword is used to exit from loops, by skipping the rest of the
statements in the loop body.
The continue keyword skips the rest of the statements in the loop body and
starts the next iteration of the loop.
Labels can be used with break and continue in cases where nested loops are
present, and we want to specify which loop to target with break/continue.
Java Fundamentals
Character set is a set of valid characters that a language can recognize. Java uses
the Unicode character set.
Unicode is a 16-bit character code set that has characters representing almost all
characters in almost all human alphabets.
Token is the smallest individual unit in a program. Keywords, identifiers, literals,
punctuators and operators are various types of tokens.
Keywords are the words that convey a special meaning to the language
compiler.
Identifiers are used as the general terminology for the names given to different
parts of the program.
Rules for naming identifiers:
a) It can include alphabets, digits, underscore and dollar sign.
b) It must not be a keyword.
c) It must not begin with a digit.
d) It can be of any length.
e) It is case-sensitive.
Literals are constants, which are data values that are fixed.
Java supports three types of integer literals: decimal, octal and hexadecimal.
Octal literals are preceded with 0. Hexadecimal literals are preceded with 0x or
0X.
Real literals in exponent for has two parts: a mantissa and an exponent. The
mantissa can be an integer or real literal. The exponent must be an integer.
Boolean literal can be either true or false.
Character literal is a single character, enclosed in single quotes. Escape
sequence is a non-graphic character that cannot be typed directly from
keyboard. An escape sequence is always preceded by a backslash.
String literal is a sequence of zero or more characters, enclosed in double
quotes.
Data types are means to identify the type of data and its associated operations.
There are two types of data types in Java:
a) Primitive data type
b) Reference data type
Primitive data types are basic data types. Java provides eight primitive data
types:
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
float (4 bytes)
double (8 bytes)
char (2 bytes)
boolean (1 byte)
float data type has a precision of up to 6 digits, whereas double has a precision
of up to 15 digits.
Reference data types are constructed from primitive data types. They mainly
store memory addresses. Examples include classes, arrays, interfaces.
Variable is a named memory location which holds a data value of a particular
data type.
A class variable of boolean type has the default value true. A char variable will
have a default value ‘\u0000’. All reference types are initialized with null. Other
numeric variables are initialized with 0.
The keyword final makes a variable constant.
Operators represent the operations being carried out in an expression.
Arithmetic operators allows us to perform arithmetic operations. +, -, *, / and %
are arithmetic operators.
Unary operators are operators that act on one operand. Binary operators are
operators that act on two operands.
The + operator with strings is used for concatenating strings.
The increment operator (++) adds 1 to the operand, whereas the decrement
operator (–) subtracts 1 from the operand. Both of them have two variations:
prefix (change then use) and postfix (use then change).
Relational operators determine the relation between different operands. <, <=,
>, >=, == and != are relational operators.
Logical operators are also known as conditional operators. They allow us to
construct complex decision making expressions. &&, || and ! are logical
operators.
Conditional operator (?:) is also known as ternary operator because it requires
three operands. It is a shorthand alternative for if-else statement.
The [] operator is used to declare arrays. The . (dot) operator allows us to access
members of an object or a class. The () operator is used in methods.
The (type) operator is used in type-casting. The new operator is used to create a
new object for a class, or a new array.
Operator precedence determines the order in which expressions are
evaluated. Associativity rules determine grouping of operands and operators in
an expression with more than one operator of the same precedence.
An expression in Java is any valid combination of operators, constants and
variables.
Arithmetic expressions can be either pure or mixed. In pure expressions, all the
operands are of same type. In mixed expressions, the operands are of different
data types.
Math class is in java.lang package that provides us with several mathematical
functions. Following are some of the commonly used mathematical functions:
a) sin(x) returns the sine of the angle x in radians.
b) cos(x) returns the cosine of the angle x in radians.
c) tan(x) returns the tangent of the angle x in radians.
d) asin(y) returns the angle whose sine is y.
e) acos(y) returns the angle whose cosine is y.
f) atan(y) returns the angle whose tangent is y.
g) atan2(x, y) returns the angle whose tangent is x / y.
h) pow(x, y) returns x raised to y.
i) exp(x) returns e raised to x.
j) log(x) returns the natural logarithm of x.
k) sqrt(x) returns the square root of x.
l) ceil(x) returns the smallest whole number greater than or equal to x.
m) floor(x) returns the largest whole number less than or equal to x.
n) rint(x) returns the rounded value of x.
o) abs(x) returns the absolute value of x.
p) max(a, b) returns the greater value among a and b.
q) min(a, b) returns the smaller value among a and b.
Type casting is the process of converting one predefined type into
another. Implicit type conversion is performed by the compiler without
programmer’s intervention. Explicit type conversion is user-defined that forces
an expression to be of specific type. The implicit type conversion in which data
types are promoted is known as coercion. You cannot typecast boolean type to
another primitive type and vice-versa.
A statement forms a complete unit of execution. They always terminate with a
semicolon. Assignment expressions, using ++ or –, method calls, object creation
expressions are various kinds of statements.
Without classes, there can be no objects, and without objects, no computation
can take place. Thus, class forms the basis of all computation.
A class is declared using the keyword class. Java file can only have one public
class. A class variable/static variable is one which is shared by all objects of that
class type. Instance variable is one that is created for every object of the class.
Java Programs:
Question 1: Write the programs in Java to display the first ten terms of the
following series:
a) 1, 4, 9, 16, …
b) 1, 2, 4, 7, 11, …
c) 3, 6, 9, 12, …
d) 4, 8, 16, 32, …
e) 1.5, 3.0, 4.5, 6.0, …
f) 0, 7, 26, …
g) 1, 9, 25, 49, …
h) 4, 16, 36, 64, …
i) 0, 3, 8, 15, …
j) 24, 99, 224, 399, …
k) 2, 5, 10, 17, …
class Series1{
public static void main(String args[]){
for(int i = 1; i <= 10; i++)
System.out.print(i * i + "\t");
System.out.println();
}
}
class Series2{
public static void main(String args[]){
int value = 1;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += i;
}
System.out.println();
}
}
class Series3{
public static void main(String args[]){
for(int i = 1; i <= 10; i++)
System.out.print((i * 3) + "\t");
System.out.println();
}
}
class Series4{
public static void main(String args[]){
int value = 4;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value *= 2;
}
System.out.println();
}
}
class Series5{
public static void main(String args[]){
double value = 1.5;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += 1.5;
}
System.out.println();
}
}
class Series6{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
int term = (int)(Math.pow(i, 3) - 1);
System.out.print(term + "\t");
}
System.out.println();
}
}
class Series7{
public static void main(String args[]){
int value = 1;
for(int i = 1; i <= 10; i++){
int term = value * value;
System.out.print(term + "\t");
value += 2;
}
System.out.println();
}
}
class Series8{
public static void main(String args[]){
int value = 2;
for(int i = 1; i <= 10; i++){
int term = value * value;
System.out.print(term + "\t");
value += 2;
}
System.out.println();
}
}
class Series9{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
int term = i * i - 1;
System.out.print(term + "\t");
}
System.out.println();
}
}
class Series10{
public static void main(String args[]){
int value = 5;
for(int i = 1; i <= 10; i++){
int term = value * value - 1;
System.out.print(term + "\t");
value += 5;
}
System.out.println();
}
}
class Series11{
public static void main(String args[]){
int value = 2;
int add = 3;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += add;
add += 2;
}
System.out.println();
}
}
Question 2: Write a program to input any 50 numbers (including positive and
negative) and perform the following tasks:
a) Count the positive numbers.
b) Count the negative numbers.
c) Sum of positive numbers.
d) Sum of negative numbers.
import java.io.*;
class Counting{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int cp = 0;
int cn = 0;
int sp = 0;
int sn = 0;
System.out.print("Enter 50 numbers: ");
for(int i = 1; i <= 50; i++){
int n = Integer.parseInt(br.readLine());
if(n >= 0){
cp++;
sp += n;
}
else{
cn++;
sn += n;
}
}
System.out.println("Number of positive numbers: " + cp);
System.out.println("Sum of positive numbers: " + sp);
System.out.println("Number of negative numbers: " + cn);
System.out.println("Sum of negative numbers: " + sn);
}
}
Question 3: Write a program to calculate the sum of all odd numbers and even
numbers between a range of numbers from m to n (both inclusive) where m < n.
Input m and n.
import java.io.*;
class Sum{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int odd = 0;
int even = 0;
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m < n){
for(int i = m; i <= n; i++){
if(i % 2 == 0)
even += i;
else
odd += i;
}
System.out.println("Sum of positive numbers: " + even);
System.out.println("Sum of negative numbers: " + odd);
}
else
System.out.println("Invalid range!");
}
}
Question 4: Write a program to enter any 50 numbers and check whether they
are divisible by 5 or not. If divisible, then perform the following tasks:
a) Display all the numbers ending with the digit 5.
b) Count those numbers ending with 0.
import java.io.*;
class Five{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int zero = 0;
for(int i = 1; i <= 50; i++){
System.out.print("Number = ");
int n = Integer.parseInt(br.readLine());
if(n % 5 == 0){
if(n % 10 == 5)
System.out.println(n + " ends with 5.");
else
zero++;
}
}
System.out.println("Number of values ending with zero: " + zero);
}
}
Question 5: Write a program to display all the numbers between m and n input
from the keyboard where m < n, m > 0 and n > 0. Check and print the numbers
that are perfect square. Example: 25, 36, 49 are perfect square numbers.
import java.io.*;
class PerfectSquares{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int zero = 0;
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m < n && m > 0 && n > 0){
for(int i = m; i <= n; i++){
System.out.println("Number = " + i);
double s = Math.sqrt(i);
if(s == (int)s)
System.out.println(i + " is a perfect square.");
}
}
else
System.out.println("Invalid range!");
}
}
Question 6: Write a program to display all the buzz numbers between p and q
where p < q. A buzz number is the number which either ends with 7 or is divisible
by 7.
import java.io.*;
class Buzz{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("p = ");
int p = Integer.parseInt(br.readLine());
System.out.print("q = ");
int q = Integer.parseInt(br.readLine());
if(p < q){
for(int i = p; i <= q; i++){
if(i % 10 == 7 || i % 7 == 0)
System.out.print(i + "\t");
}
System.out.println();
}
else
System.out.println("Invalid range!");
}
}
Question 7: Write a program to input marks in English, Math and Science of 40
students who have passed ICSE Examination 2019. Now perform the following
tasks:
a) Number of students who have secured 95% or more in all the subjects.
b) Number of students who have secured 90% or more in English, Math and
Science.
import java.io.*;
class Student{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int math = 0;
int science = 0;
int english = 0;
int all = 0;
for(int i = 1; i <= 40; i++){
System.out.print("Math: ");
int m = Integer.parseInt(br.readLine());
System.out.print("Science: ");
int s = Integer.parseInt(br.readLine());
System.out.print("English: ");
int e = Integer.parseInt(br.readLine());
if(m >= 95 && s >= 95 && e >= 95)
all++;
if(m >= 90)
math++;
if(s >= 90)
science++;
if(e >= 90)
english++;
}
System.out.println("95% or above in all subjects: " + all);
System.out.println("90% or above in Math: " + math);
System.out.println("90% or above in Science: " + science);
System.out.println("90% or above in English: " + english);
}
}
Question 8: Write a program in Java to find the sum of the given series:
a) 1 + 4 + 9 + … + 400
class Sum1{
public static void main(String args[]){
int s = 0;
for(int i = 1; i <= 20; i++)
s += i * i;
System.out.println("Series sum: " + s);
}
}
b) 1 + 1/2 + 1/3 + … + 1/20
class Sum2{
public static void main(String args[]){
double s = 0.0;
for(int i = 1; i <= 20; i++)
s += 1.0 / i;
System.out.println("Series sum: " + s);
}
}
c) 1 + 1/3 + 1/5 + … + 1/19
class Sum3{
public static void main(String args[]){
double s = 0.0;
for(int i = 1; i <= 19; i += 2)
s += 1.0 / i;
System.out.println("Series sum: " + s);
}
}
d) 1/2 + 2/3 + 3/4 + … + 19/20
class Sum4{
public static void main(String args[]){
double s = 0.0;
for(double i = 1.0; i <= 19.0; i++)
s += i / (i + 1);
System.out.println("Series sum: " + s);
}
}
e) 2 – 4 + 6 – 8 + … – 20
class Sum5{
public static void main(String args[]){
int s = 0;
int sign = 1;
for(int i = 2; i <= 20; i += 2){
s += i * sign;
sign *= -1;
}
System.out.println("Series sum: " + s);
}
}
f) (1 * 2) + (2 * 3) + … + (19 * 20)
class Sum6{
public static void main(String args[]){
int s = 0;
for(int i = 1; i <= 19; i++)
s += i * (i + 1);
System.out.println("Series sum: " + s);
}
}
Question 9: Write a program to input a number and count the number of digits.
The program further checks whether the number contains odd number of digits
or even number of digits.
import java.io.*;
class Digits{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int count = 0;
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
if(num == 0)
count = 1;
for(int i = num; i > 0; i /= 10)
count++;
if(count % 2 == 0)
System.out.println("It has even number of digits.");
else
System.out.println("It has odd number of digits.");
}
}
Question 10: Write a program to input a number and display the new number
after reversing the digits of the original number. The program also displays the
absolute difference between the original number and the reversed number.
import java.io.*;
class Reverse{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int rev = 0;
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
for(int i = num; i > 0; i /= 10)
rev = rev * 10 + i % 10;
System.out.println("Reverse = " + rev);
int diff = Math.abs(num - rev);
System.out.println("Absolute difference = " + diff);
}
}
Question 11: The Greatest Common Divisor (GCD) of two integers is calculated
by the continued division method. Divide the larger number by the smaller, the
remainder then divides the previous divisor. The process repeats unless the
remainder reaches to zero. The last divisor results in GCD.
import java.io.*;
class GCD{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int rev = 0;
System.out.print("Enter first number: ");
int a = Integer.parseInt(br.readLine());
System.out.print("Enter second number: ");
int b = Integer.parseInt(br.readLine());
int rem = a % b;
while(rem != 0){
a = b;
b = rem;
rem = a % b;
}
System.out.println("GCD = " + b);
}
}
Question 12: Write a program in Java to find the sum of the given series:
a) s = a2 + a2/2 + a2/3 + … + a2/10
import java.io.*;
class Series{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
double sum = 0.0;
System.out.print("a = ");
int a = Integer.parseInt(br.readLine());
for(double i = 1.0; i <= 10.0; i++)
sum += a * a / i;
System.out.println("Sum = " + sum);
}
}
Question 13: In order to reach the top of a pole, a monkey in his first attempt
reaches to a height of 5 feet and in the subsequent jumps, he slips down by 2%
of the height attained in the previous jump. The process repeats and finally, the
monkey reaches the top of the pole. Write a program to input height of the pole.
Calculate and display the number of attempts the monkey makes to reach the
top of the pole.
import java.io.*;
class Monkey{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int attempts = 1;
double a = 5.0;
System.out.print("Height of the pole = ");
double height = Double.parseDouble(br.readLine());
while(a < height){
a += 5.0;
a -= 2.0 / 100 * a;
attempts++;
}
System.out.println("Number of attempts: " + attempts);
}
}
Question 14: Write a program to input principal, rate and time. Calculate and
display the amount which is compounded annually for each year by using the
formula:
SI = PRT / 100 and P = P + SI
import java.io.*;
class Interest{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Principal: ");
double p = Double.parseDouble(br.readLine());
System.out.print("Rate: ");
double r = Double.parseDouble(br.readLine());
System.out.print("Time: ");
int t = Integer.parseInt(br.readLine());
double si = 0.0;
double amt = 0.0;
for(int i = 1; i <= t; i++){
si = p * t * r / 100;
amt = p + si;
p = amt;
}
System.out.println("Amount = " + amt);
}
}
Question 15: Write a menu-driven program to input two positive numbers m and
n where m > n and perform the following tasks:
a) Find the sum of two numbers without using ‘+’ operator.
b) Find the product of two numbers without using ‘*’ operator.
c) Find the quotient and remainder of two numbers without using ‘/’ and ‘%’
operator.
import java.io.*;
class Menu{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1. Sum");
System.out.println("2. Product");
System.out.println("3. Quotient and Remainder");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(br.readLine());
switch(choice){
case 1:
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m > n){
int sum = (m * m - n * n) / (m - n);
System.out.println("Sum = " + sum);
}
else
System.out.println("Invalid range!");
break;
case 2:
int prod = 0;
System.out.print("M = ");
m = Integer.parseInt(br.readLine());
System.out.print("N = ");
n = Integer.parseInt(br.readLine());
if(m > n){
for(int i = 1; i <= n; i++)
prod += m;
System.out.println("Product = " + prod);
}
else
System.out.println("Invalid range!");
break;
case 3:
int quo = 0;
int rem = 0;
System.out.print("M = ");
m = Integer.parseInt(br.readLine());
System.out.print("N = ");
n = Integer.parseInt(br.readLine());
if(m > n){
while(m > n){
m -= n;
quo++;
}
rem = m;
System.out.println("Quotient = " + quo);
System.out.println("Remainder = " + rem);
}
else
System.out.println("Invalid range!");
break;
default:
System.out.println("Invalid choice!");
}
}
}
Question 16: Write a menu-driven class to accept a number from the user and
check whether it is a palindrome or a perfect number.
a) A number is palindrome which when read in reverse order is same as in the
right order.
b) A number is perfect if it is equal to the sum of its factors other than the
number itself.
import java.io.*;
class Menu2{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1. Palindrome");
System.out.println("2. Perfect");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(br.readLine());
switch(choice){
case 1:
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
int rev = 0;
for(int i = num; i != 0; i /= 10)
rev = rev * 10 + i % 10;
if(num == rev)
System.out.println(num + " is palindrome.");
else
System.out.println(num + " is not palindrome.");
break;
case 2:
int sum = 0;
System.out.print("Enter the number: ");
num = Integer.parseInt(br.readLine());
for(int i = 1; i < num; i++){
if(num % i == 0)
sum += i;
}
if(num == sum)
System.out.println(num + " is a perfect number.");
else
System.out.println(num + " is not a perfect number.");
break;
default:
System.out.println("Invalid choice!");
}
}
}