Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

ICSE CLASS 10

COMPUTER NOTES

LESSON 1
Concept of OOPs
Object-oriented programming: Object-Oriented Programming or OOPs refers to languages that uses objects
in programming. Object-oriented programming aims to implement real-world entities like abstraction ,
inheritance, encapsulation , polymorphism etc in programming. Java is an example of object oriented
language.

Ques What are the basic OOP (object oriented programming) concepts? OR Name OOPs principles
Ans : The basic OOP concepts are Abstraction, Encapsulation, Inheritance, Polymorphism

Ques What is an object ? Give eg.


Ans An object is an identifiable entity with some characteristics and behaviour. For e. g. Orange is an
object. Its characteristics are its spherical shape and its orange colour. Its behaviour is that it is citrus in
nature and tastes sweet and sour.

Ques What is an abstraction? Give example .


Ans Abstraction is an act of representing essential features without including background details or
explanations. For Eg If a person is driving a car he is required to know the essential features like use
of gear, clutch, brakes, accelerator and steering handling etc. He is not required to know the internal
details like wiring , functioning of engine etc.

Ques What is Encapsulation ? Give eg


Ans The wrapping up of data and functions in a single unit is called encapsulation.
For eg . a group of car’s part (such as seats, steering ,engine ,brakes etc.) does not make a car ; they have
to be connected in proper way in one unit in order to have proper functionality i.e behaviour. ; then only
it may be termed as a car.

Ques What is Polymorphism?


Ans: Polymorphism is the ability of an object to behave differently in different circumstances.
For eg operation move behaves differently when applied to MS windows than when applied
to a chess game.

Ques What is inheritance ?


Ans: Inheritance is the capability of one class to inherit the properties from another class .A class from which
another class is inheriting the properties is Base/ Super class and the class that inherits the properties is known
as Derived / Sub class

Ques Can there be multiple abstractions of a real world entity?


Ans Yes, There can be multiple abstractions of a real-world entity as an abstraction is relative to the purpose
or user e. g., If we talk about student , we talk about anything belong to him like his name, brothers
,sisters, parent’s profession, address etc. but in terms of result tracking system the abstraction would be –
his roll no, name, marks obtained etc, for extra curricular activities , the abstraction would be – her roll
no , talents and awards etc.

ICSEIMPNOTES
Ques How are objects implemented in software terms? Ans
The objects are implemented in software terms as
(i) Characteristics (attributes ) are implemented through member variables . (ii)
Behaviour is implemented through member functions called methods.
(iii) The values of these member variables defines the state of an object
(iv) Data and methods are encapsulated into one unit and given a unique name to give it identity.

Ques What is state of object?


A In software objects , the values of the characteristics(member variables) determine the state of object.
For eg the switch may be in two state either on or off.

Ques How do object encapsulate state and behavior?


Ans An object binds together the characteristics and behaviour which cannot be separated i.e. The
state and behaviour are encapsulated by the object as the state is nothing but the set of values of
the characteristics at a certain time.

Ques What is message passing among object ?


Ans The interaction between objects by means of function calls is termed as message passing

Ques What is information hiding?


Ans. Information hiding means restricting the accessibility of data associated with an object in such a way that it can be
used only through the member methods of the object.

Ques Why methods are so important for the description of objects?


Ans All the real world entities do have behaviour associated with them, so the objects, which basically represent these
entities, must have methods that implements this behaviour..

Ques How are classes and abstraction interlinked?


Ans. An Abstraction is a named collection of characteristics and behaviour required to represent an entity or concept
for some particular domain . And a class is logical implementation of an abstraction. When it comes to represent
an abstraction in software terms, it is represented through a class.

Ques How do you map an abstraction into software?


Ans . Abstractions are mapped into software terms by means of classes. A class wraps up characteristics and behavior of
an abstraction into one unit by representing characteristics(attributes) through data members and behaviour
through methods.

Ques What is class ?


Ans A class represents a set of objects that share common characteristics and behaviour.
For eg Student is a class but the students JOHN , RAM are objects.

Ques What is an object factory ?


Ans Class is an object factory that accepts some information and creates objects based on this information.

Ques How are objects and classes related to each other ?


Ans Class is a set of objects with common characteristics and behaviour, while an object is an instance of the class.

ICSEIMPNOTES
Ques. Why are classes and object needed ?
Ans: Classes are defined as a blueprint of its object. We need classes because they contain all the statements and
functions that can be used by the objects of the class.
Objects are the instances of class .They are needed because they are used to access the data member and the member
function of the class without disturbing the actual structure of the class.

Ques Why is a class called an object factory ?


Ans class is called can object factory because it contains all the statements needed to define an object its behavior ,
attributes as well as its functions that the object will be able to perform. A class can produce any number of
objects.

Ques Why is an object called the instance of the class ?


Ans An object is called an instance of a class as it has the same structure and behaviour as that of a class. A class
can have many instances or objects which have same structure and behaviour but differ only in their state.

INTRODUCTION TO JAVA

Java is a powerful object oriented third generation programming language It was developed in 1991 by

James Gosling at Sun Microsystem by the name Oak and later renamed as Java.

Platform refers to the combination of hardware and system s/w . For eg. Windows NT on Intel Pentium 4.

Source Code: The program /code written in any language by the programmer to solve a problem is called source code.

Compilation : The process of converting source code into machine code is called compilation.

Compiler translates the program all at once ,

Interpreter translates it instruction by instruction.

Java Byte code: When java programs are compiled, the java compiler converts the source code into platform
independent code called Java byte Code. This byte code is further interpreted and executed by JVM.

JVM: Programs written in Java are compiled into Platform independent JBC which is then interpreted by a
special Java interpreter for a specific platform. This java interpreter is known as JVM.

Ques How is ordinary compilation different from java compilation?


Ans In ordinary compilation the source code is converted to a machine code, which is dependent upon the
machine or platform .This resultant machine code is called native executable code.
Whereas, the Java compiler does not produce native executable code for a particular machine. Instead it
produces java byte code which is same for every machine.

Ques: Explain different characteristics of Java.

Ans : Different characteristics of Java are


1. Write Once Run Anywhere (WORA) : Programs written once can be made to run on different platforms
without making any changes in Java Program.
2. Light Weight Code : In Java we can create big and useful application with very light code.
ICSEIMPNOTES
3. Security : Java offers many security features to make programs safe and secure.
4. Built-In-Graphics : Java offers built-in-graphic features which can be used to make Java applications more
attractive.
5. Support Multimedia : Java is ideally suited for integration of video , audio ,animation and graphics in Internet
Environment.
6. Platform Independent : It is platform independent ,since change in platform does not affect the original Java
program or application.
7. Open Product : It is freely available.
8. Object Oriented Language: It is because it is very close to the real world.

Ques Explain Stand Alone Application & Internet Applets .


Ans : Stand Alone Application
It is a software application that does not require low level operating system or hardware access . It
can run independently on any System.
Internet Applets
They are small programs that are embedded in the web pages and are made to run on the viewers
machine in a secure manner by Java capable browsers.

Ques: Mention different styles of writing comment in Java


Ans : Comments are written to explain the logic of the program. Comments are ignored and not executed
during compilation.
Different styles of writing comments are

(i) // comments Single line comment

(ii) /*………comments………..
………………………… ……….*/ Multiline comments

(iii) /**………comments………………..*/ Documentation comments

Ques : What do you know about blue J?


Ans : BlueJ is a java development environment. It is an IDE (Integrated Development Environment),
which includes an editor, a debugger and a viewer.

ICSEIMPNOTES
Values and Types

Character set: is set of valid characters that a language can recognize. Java uses
Unicode character set. Unicode is two-byte character set.

Keyword
identifier
class Area
Punctuators/Seperator
{
void main( )
{ Literal/constant
int l=2, b=3, a;

a=l*b;

operator
System.out.println(“area=”+a);
}

Tokens : The smallest unit in a program is known as token Java


has following tokens:

1. Keywords: are the words that convey a special meaning to language compiler.
These are reserved for special purpose and cannot be used as an identifier. For
e.g. if, int , float, do, while, for etc .
2. Identifiers: Identifiers are the name given to different parts of program e.g.
variables, function, classes etc
Identifier forming rules of Java state the following:
a) Can contain alphabets, digits, dollar sign and Underscore.
b) Must not start with digit.
c) Cannot be Java keywords.
d) Can be of any length and are case sensitive i.e upper case and lower case
letters are treated differently.

Identify Invalid Identifiers, Give reason


(i) Abc Valid
(ii) Book1 Valid
(iii) 1book Invalid since Identifier cannot start with no
(iv) My class Invalid since Identifier cannot have space
(v) My_class Valid
(vi) My.var Invalid since Identifier cannot have .
(vii) Ar1ea Valid

ICSEIMPNOTES
3. Literals : Literals are the constants .Constant is a value that remains fixed.
Java allows several kinds of literals
a) Integer Literals : Integer constants are the whole numbers without any decimal
parts.
An integer constant must have at least one digit and cannot contain a decimal
point. It may contain a + or – sign. A number with no sign is interpreted to be
positive. No other symbol is allowed. For eg int x=2; here 2 is integer literal

Java has three types of integer literals


(i). Decimal Integer Literal (base 10): is sequence of digits taken to be decimal
integer constant unless it begins with 0 (zero). For e.g 123, 41, -98., -18
are decimal literals

(ii) Octal Integer Literal (base 8): is sequence of digits starting with 0 (zero).It
can contain numbers from 0 to 7.
For e.g 012

(ii) Hexadecimal Integer Literal (base 16): is sequence of digits starting with
0X.It can contain numbers from 0 to 9 and A to F. For e.g 0XC.

b) Floating Literals: Floating Literals or constants are the real numbers. A


floating Literal can either be in fractional or in exponent form. Eg float
x=2.5f;
double y =2.5; // or double y =2.5d;

Rule for writing real constant in fractional form:


A real literal in fractional form must have at least one digit before a decimal
point and at least one digit after the decimal point .It may also have either + or
– sign preceding it. A real Literal with no sign is assumed to be positive. Eg
12.35 ,-35.45
A real Literal in exponent form has two parts : a mantissa and an exponent. The
mantissa must be either an integer or a proper real literal.. the mantissa is
followed by a letter E or e and the exponent. The exponent must be an integer.
For eg 1.02*1023.can be written as 1.02E23 where 1.02 is mantissa and 23 is
exponent.

c) Boolean Literal : The Boolean type has two values, represented by literals
true and false.
boolean x=true;

d) Character Literals: A character Literal in java is a character enclosed in


single quotes. Non graphic characters can be represented using escape
sequence for eg ‘\n’ , ‘\t’.ICSEIMPNOTES
char x= ‘d’;
e) String Literals: A string literal is a sequence of zero or more characters
enclosed in double quotes. For eg “abcd”
“\ta”
String x=”java”;

g) Null Literal : The null literal is a reserved constant used to represent a


void reference, i.e a variable contains the reference to a location that does not
contain any object.

Separators/Punctuators: punctuators are special symbols used for grouping and


separating the data values written in java programs. Separators are as follows ( ) { }
[ . ] ; ,

Operators : are special symbols that carry out certain pre-defined operations / tasks .On
the basis of operations carried out, operators can be categorized as
Arithmetic operators e.g +. -,*,\ Relational
operators e.g >, <, <=, >=, != Logical
operators e.g && , | | , ! .

Data type : are the means of to identify the type of data and associated operations
of handling it .
Java supports eight types of primitive datatypes
(1) Primitive Datatype (Intrinsic, predefined or fundamental) : Primitive
datatype are the basic datatypes. Java supports following eight types of Primitive
datatypes
(i) Numeric Integral types
The numeric datatypes that are used to store numeric values fall under this
category .There are four numeric integral types in java.
Type Size Range Default Value
byte 1 byte -128 to +127 0
short 2 byte -32,768 to +32,768 0
int 4 byte -231 to 231-1 0
( - 2,147,483,648 to
2,147,483,647)

long 8 byte -263 to 263-1 0L


( -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)

L (or l) suffix on an integer means integer is of long datatype thus 546 is int
datatype but 546L is long datatype

ICSEIMPNOTES
(ii) Fractional Numeric Data type(or floating datatypes): can store
fractional numbers i.e numbers having decimal points.
Type Size Range Default Precisio
Value n Digits
float 4 bytes -3.4E+38 to +3.4 6 digits
0.0f
E+38
double 8 bytes -1.7E+308 to +1.7 15 digits
0.0d
E+308

By default, Java treats fractional number as double datatype. To explicitly


specify it to be float type use suffix f or F. for double use d or D.
(iii) Character Type : is used to store characters. A character in Java can
represent all ASCII character as well as Unicode character .

Type Size Range Default Value


character 2 bytes 0 to 65,536 null character i.e ‘\u0000’

(iv) Boolean Type: It is used to represent a single


true/false value.
Type Size Range Default Value

boolean Java reserve 1byte , true or false


but uses 1 bit false

Reference datatype (or derived Datatype) are constructed from primitive datatypes for
e.g classes, array etc.
Default value of reference datatype is null.

Variables : A variable is a named memory location, which holds a data value of a


particular data type.

Declaration of variable :Naming a variable along with its datatype is


known as variable declaration.
Syntax:
datatype variablename1, variblename2;
eg int a, b;
double x, y;

ICSEIMPNOTES
Initialization of variables: Assigning an initial value to the variable while
declaration. datatype varname=constant value; eg int a=5;
Dynamic initialisation: The value assigned to a variable during run time
is called dynamic initialization. For eg. if int a=5.0,b=4.0;
double c=Math.pow(a,b) , here value of c is dynamically initialized by the
return value.

Variable Scope : Refers to the program region within which the variable is
accessible.
Class xyz
{ Variable of outer block are
accessible within inner block.
void main( )
Variable of inner block is not
{ accessible in outer block
int a,b;
for(……….)
Scope { Scope of
of p,q int p, q; variable a,b
}
}

Ques What is a use of final keyword?


Ans Final keyword makes a character constant ,i.e the value of variable canot
be changed in the program.
for eg final int x=2; (now value of x cannot be changed )

public class xyz


{
public static void sampleMethod()
{
final int x=19;
x=x+4;
System.out.print(x);
}}
//cannot assign a value to final variable

ICSEIMPNOTES
Operators in java

Operators : are special symbols that carry out certain pre-defined operations /
tasks .On the basis of operations carried out, operators can be categorized as

Arithmetic operators are used to perform Arithmetic operations e.g +.-, *, \ (division
gives quotient), % (reminder )
For eg 7/3=2, 7%3=1

Relational operators are used to perform relational operations e.g >, <, <= , >= ,= =, ! =
and results in true or false.
For eg
System.out.print(5>2)
Output will be true.

Logical operators are used with relational expressions to combine them eg. && ,||, !

Logical AND Operator( && ): It results into true if all its operands are true

Eg : (5= =5) && (5>3) will results into true


(5>3)&&(2>1) will results into true

Logical OR Operator(||): it results into true if any one of its


operands are true. Eg : (5= =15) || (5>3) will results into true

Logical Not ( ! ) :is an unary operator and negates the value i.e. true
becomes false and vice versa Eg !(5==5) will results into false.

Assignment operator : is used to assign the value at its right to the


variable at its left Eg int a=2;

Relational operator = = is used to check whether the values on both its sides are equal
or not.

Java Operators can be classified as unary , binary or ternary based on the number
of operands .

Q Distinguish between a unary ,binary & a ternary operator.


A A unary operator : requires one operand for eg unary+ , unary -,++,- -.
A binary operator : requires two operand for eg +,-/,% etc
ICSEIMPNOTES
Ternary operators: requires 3 operands for eg ?:(also called conditional operator)

Compound Assignment operator (Shorthand operator) are combination of assignment


and other operator.These operators modify the value of a variable by performing an
operation on the value currently stored in that variable.
For eg
a+=10 is same as
a=a+10; b*=10 is same as
b=b*10;
Q What is type conversion? In java Type conversion can in how many forms ?
Ans:The process of converting one predefined type to another is called type
conversion.Type conversion can be of two type: Implicit and Explicit.
Implicit conversion is automatically carried out by the compiler, whereas Explicit
conversion is explicitly specified by the programmer using typecast operator.

Q What do you mean by type casting ? What is type cast operator?


Ans The explicit conversion of an operand to a specific type is called type casting .the
operator that converts its operand to the specified type is called the typecast
operator . The typecast operator is ( ) in java is used as (type) expression,where
type is datatype to be converted in.

Eg int x= (int ) 2.5;

Q Why do think that type compatibility is required in assigning values ?


Ans If the type compatibility is not taken care of before assigning values then the
assignment might lead to loss of precision of data.
Q What is type promotion?
Ans : The java compiler converts all operand upto the type of largest operand is called type
promotion.
For eg int A; double B;
Then resultant datatatype of the expression A+B
will be double Q What is Coercion ?
Ans The implicit conversion wherein data types are promoted is known as coercion.
For eg int A; double B;
Then resultant datatatype of the expression A+B will be double

ICSEIMPNOTES
Q What are the potential problems in type
conversions? Ans Potential problems are as
follows
Conversion Problem
Bigger floating type to smaller floating type Loss of precision
(e.g double to float)
Floating point to integer type Loss of fractional part.
Bigger integer type to smaller integer type Original
value may be out of range for the target type
leading to the loss of information.

Ques What is an expression?


Ans: An expression is any valid combination of operators ,constants ,and variables i.e. legal
combination java tokens
Arithmatic expression can either be pure integer expression, pure real expression or
mixed expression Pure integer expression: are formed by connecting integer
constants and /or integer variables using integer arithmetic operators. For eg int i,j,k;
i*j+k is an pure integer expression.
Pure real expression: are formed by connecting real constants and /or real
variables using real arithmetic operators(for eg % is not a real operator). For eg
double p,q; float r; here p*q+r is an pure real expression.
Mixed Expression : is mixture of integer & real. For eg i*j+q

Ques What is operator precedence and Associativity?


Ans Determines the order in which the expression is evaluated . For eg
Operator Precendence Associativity
[ ] , () Left to Right

++,-- Right to left


*, /, % Left to Right
+,- Right to left
< > <= >= Left to Right
= =, != Left to Right
&& Left to Right
|| Left to Right
?: Right to left
=,+=,*=,/=,%= Right to left

Associativity : When the operator have same precedence rating than associativity rule
determines the order of evaluation.

ICSEIMPNOTES
Ques What is rvalue & lvalue
Ans rvalue : data value stored at some location in memory is
rvalue lvalue (location value ): address in memory at
which its data value is stored . a
for eg
5
(rvalue)
8088 (lvalue)

Ques What do you mean by operator + with string?


Ans Operator + with strings concatenates
For eg 5+6 will result into 11 , “5”+6 will results into 56 similarly “5”+ “6” will be 56

Ques Explain [], (), . , new, (type) operators .


Ans The [] operator : is used to declare arrays
The . dot operator: is used to access instance members of a class.
The () operator: is used in accessing or calling method
The new operator : is used to create a new object or a new array.
The (type) operator: converts casts ( i.e converts ) a value to the specified type.
Q Explain class variable & instance variable.
Ans: class variables(static variables): is a data member that is declared once for a
class . All object of a class share these data members , as there is a single copy of
them available in the memory . instance variables:A data member that is
created for every object of the class .For eg if there are 5 objects there wil be 5 copies
of instance variable one for each object .
Ques What is block?
Ans A block is a group of zero or more statement with in balanced braces.

Ques What are escape sequences? Give eg


Ans Escape sequences is represented by a backslash(\) followed by one or more character .These are non
graphic character For eg \n for newline, \t for horizontal tab.

Ques What is a difference between ‘x’


and “x”? Ans ‘x’ is character literal &
“x” is string literal.

Ques Name reserved words which are not keyword


Ans. True, false, null are reserved word but not keyword

Ques Name the package in which Math class is defined


Ans. Math class is defined in java.lang package

Math class methods (functions)


ICSEIMPNOTES
Arithmetic Expression Java Expression

2xy 2*x*y

|x| Math.abs(x)
𝒙𝒚
(x*y)/z
𝒛
√x Math.sqrt(x)

Math.cbrt(x)

𝒙𝒚 Math.pow(x,y)

𝒆𝒙 Math.exp(x)

sin(x) Math.sin(x)

cos(x) Math.cos(x)

tan(x) Math.tan(x)

sin(2x) Math.sin(2*x)

𝐬𝐢𝐧−𝟏 𝒙 Math.asin(x)

𝐜𝐨𝐬−𝟏 𝟐𝒙 Math.acos(2*x)

𝐭𝐚𝐧−𝟏 𝟐𝒙 Math.atan(2*x)

public class MathFUN


{
ICSEIMPNOTES
public static void main()
{
System.out.println("Math.pow(2,3)= "+Math.pow(2,3) );
System.out.println("Math.sqrt(16)= "+Math.sqrt(16));
System.out.println("Math.cbrt(8)= "+Math.cbrt(8));
System.out.println("Math.ceil(5.3)= "+Math.ceil(5.3));
System.out.println("Math.ceil(5.7)= "+Math.ceil(5.7));
System.out.println("Math.ceil(-5.3)= "+Math.ceil(-5.3));
System.out.println("Math.ceil(-5.7)= "+Math.ceil(-5.7));
System.out.println("Math.ceil(5.0)= "+Math.ceil(5.0));
System.out.println("Math.floor(5.3)= "+Math.floor(5.3));
System.out.println("Math.floor(5.7)= "+Math.floor(5.7));
System.out.println("Math.floor(-5.3)= "+Math.floor(-5.3));
System.out.println("Math.floor(-5.7)= "+Math.floor(-5.7));
System.out.println("Math.floor(5.0)= "+Math.floor(5.0));
System.out.println("Math.abs(-5.5)= "+Math.abs(-5.5));
System.out.println("Math.abs(5.5)= "+Math.abs(5.5));
System.out.println("Math.rint(7.5)= "+Math.rint(7.5));
System.out.println("Math.rint(7.3)= "+Math.rint(7.3));
System.out.println("Math.rint(-7.8)= "+Math.rint(-7.8));
System.out.println("Math.rint(7.0)= "+Math.rint(7.0));
System.out.println("Math.round(7.5)= "+Math.round(7.5));
System.out.println("Math.round(7.3)= "+Math.round(7.3));
System.out.println("Math.round(-7.8)= "+Math.round(-7.8));
System.out.println("Math.round(7.0)= "+Math.round(7.0));
System.out.println("Math.random()= "+Math.random());
System.out.println("Math.random()= "+Math.random());
System.out.println("Math.random()= "+Math.random());
System.out.println("Math.min(5.5,6.9)= "+Math.min(5.5,6.9));
System.out.println("Math.max(5.5,6.9)= "+Math.max(5.5,6.9));
System.out.println("Math.min(5,6)= "+Math.min(5,6));
}
}
ICSEIMPNOTES
OUTPUT
Math.pow(2,3)= 8.0
Math.sqrt(16)= 4.0
Math.cbrt(8)= 2.0

Math.ceil(5.3)= 6.0
Math.ceil(5.7)= 6.0
Math.ceil(-5.3)= -5.0
Math.ceil(-5.7)= -5.0
Math.ceil(5.0)= 5.0

Math.floor(5.3)= 5.0
Math.floor(5.7)= 5.0
Math.floor(-5.3)= -6.0
Math.floor(-5.7)= -6.0
Math.floor(5.0)= 5.0

Math.abs(-5.5)= 5.5
Math.abs(5.5)= 5.5

Math.rint(7.5)= 8.0
Math.rint(7.3)= 7.0
Math.rint(-7.8)= -8.0
Math.rint(7.0)= 7.0

Math.round(7.5)= 8
Math.round(7.3)= 7
Math.round(-7.8)= -8
Math.round(7.0)= 7

Math.random()= 0.4579719825200854
Math.random()= 0.9869581480576484
Math.random()= 0.3398321903307846
Math.min(5.5,6.9)= 5.5
Math.max(5.5,6.9)= 6.9
Math.min(5,6)= 5

ICSEIMPNOTES
Conditional Constructs in Java
Three construct that govern statement flow are :- 1.
Sequence : means statement are executed sequentially
2. Selection : means the execution of statements depending upon a test condition.
3. Iteration : means repetition of set of statements depending on the test condition .Till
the time a condition is true set of statement repeats again and again . When condition
becomes false the repetition stops.

Selection statements
if statement : syntax
if(expression)
statement;
Syntax of if-else statement
if (test condition)
{ statement1;

} else {
statement3;

}
The { } can be ignored if only a single statement is associated with either part.

Ques Explain nested if with example.


Ans Nested if means that it has another if in its if part or its else part.
for eg.
if(a>0) {
if(a<10)
System.out.println(“single digit no”); else
System.out.println(“not single digit no”);
} else
System.out.println(“negative no”);

Conditional statement(ternary operator): ?:


Syntax
expression1 ? expression2 : expression3 expression1 is evaluated if it is true expression2 gets
executed and its value becomes the value of the entire expression otherwise . expression3 gets
ICSEIMPNOTES
executed and its value becomes the value of the entire expression for eg
if a=20,what will be the value of
int x= a>10?50:100 since condition is true therefore the
value of x will be 50.

The switch statement: is multi-branch selection statement. It is used to test the


value of an expression against a list of integer or character constants when a
match is found the statements associated with that constants are executed . Syntax
: switch(expression)
{ case
constant1:
statement sequence 1:
break;
case constant2:
statement sequence 2:
break; [
default :
statement sequence n; ]
}
If we do not give break after each case, then it will start executing the statements
from matching case and keep on executing statements for the following cases as
well as until either until a break statement is found or switch statement’s end is
encountered.
Ques Explain fall-through.
Ans If the control flows to next case below the matching case, in the absence of break this is called
fall-through

Ques : WAP to calculate the area of rectangle or circle according to user’s choice.

import java.util.*;
public class AreaCal
ICSEIMPNOTES
{
void main( )
{
double l,b,r,ar,ac;
int ch;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 1 to calculate Area of rectangle \nEnter 2 to calculate Area of
Circle");
System.out.println("Enter choice ");
ch=sc.nextInt();
switch(ch)
{ case
1:
System.out.println("Enter length");
l=sc.nextDouble();
System.out.println("Enter breadth");
b=sc.nextDouble();
ar=l*b;
System.out.println("Area of Rect="+ar);
break;
case 2:
System.out.println("Enter radious of circle");
r=sc.nextDouble(); ac=3.14*r*r;
System.out.println("Area of Circle="+ac);
break; default:
System.out.println("Invalid Input");
}
}
}

OUTPUT
Enter 1 to calculate Area of rectangle
Enter 2 to calculate Area of Circle
Enter choice
1
Enter length
2
Enter breadth
3.0
Area of Rect=6.0
----- ----- ------
Enter 1 to calculate Area of rectangle
Enter 2 to calculate Area of Circle
Enter choice
ICSEIMPNOTES
2
Enter radious of circle
2.0
Area of Circle=12.56

---- ------ ----- -------


Enter 1 to calculate Area of rectangle
Enter 2 to calculate Area of Circle
Enter choice
3
Invalid Input

Ques : WAP to calculate the area of rectangle or circle according to user’s choice.
(same program but here we have taken choice of user as char input)

import java.util.*; public


class AreaCal2
{
void main()
{
double l,b,r,ar,ac; char
ch;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a to calculate Area of rectangle \nEnter b to calculate Area of
Circle");

System.out.println("Enter choice ");


ch=sc.next().charAt(0);
switch(ch)
{
case 'a':
System.out.println("Enter length");
l=sc.nextDouble();
System.out.println("Enter breadth");
b=sc.nextDouble();
ar=l*b;
System.out.println("Area of Rect="+ar);
break;
ICSEIMPNOTES
case 'b':
System.out.println("Enter radious of circle");
r=sc.nextDouble(); ac=3.14*r*r;
System.out.println("Area of Circle="+ac);
break; default:
System.out.println("Invalid Input");
}
}
}

A tech number has even number of digits. If the number is split in two equal
halves, then the square of sum
of these halves is equal to the number itself. Write a program to input and
check a four digit tech numbers. Example :
Consider the number 3025
Square of sum of the halves of 3025 = (30+25)
= (55)
(55)2= 3025 is a tech number.

Solution.

class TechNumber n x y s
{
public void main (int n)
3025 30 25 55
{ int x,y,s;
x=n/100; y=n%100; s=x+y;
if((int)Math.pow(s,2)==n)
System.out.println(n+” is a tech
no”); else
System.out.println(n+” is not a tech no”);
}
}
Write a program to calculate commission for the salesman. The
commission is calculated according to following rates :
ICSEIMPNOTES
Sales Commission Rate

30001 onwards 15%


22001 - 30000 10%
12001 - 22000 7%
5001 - 12000 3%
0 - 5000 0%
Program accepts the sales made by the salesman and displays the
calculated commission.

class commission
{
public void main(double sales)
{
double com=0;
if(sales>=0 && sales<=5000)
{
com=0;
}
else if(sales>5000 && sales<=12000)
{
com=sales*3.0/100;
}
else if(sales>12000 && sales<=22000)
{
com=sales*7.0/100;
}
else if(sales>22000 && sales<=30000)
{
com=sales*10.0/100;
}
else if(sales>30000)
{
com=sales*15.0/100;
}
System.out.println("Commission = "+com);
}
}
ICSEIMPNOTES
Write a program in java to perform the following calculation of
Library fine :
For the first 5 days late Rs. 1 per book per day
For the next 5 days Rs. 2 per book per day
Late more than 10 days Rs. 5 per day per book

class libraryfine
{
void main(int d)
{
double fine=0.0 ; if
(d<=5) fine=d*1.0;
if (d>=5 &&
d<=10)
fine=5*1+(d-5)*2.0;
if (d>=10) fine=5*1.0+5*2.0+(d-
10)*5.0;
System.out.println(“Fine=”+fine);
}
}

ICSEIMPNOTES
Iterative Constructs in Java
Ques What are iteration statement? Name them.
Ans. Iteration statements (also known as looping statements or loops)are the
statements that allows a set of instructions to be executed repeatedly till
some condition is true. They are of three types for, while & do while.
Ques What are the elements needed to control the loop
Ans (i) The initialization expression (ii) The test expression (iii) The update
expression (iv) The loop body.

Initialization Statement : It is a statement that initializes the controlling variable with legal initial value.
Test Condition/ Test Expression : It is the expression which checks for a condition and executes the
loop until the condition becomes false.
Updation Statement : The statement which changes the value of the controlling variable is called
updation statement.
Body of the loop : contains the set of statement to be executed repeatedly .
[Controlling Variable : The variable which is responsible for the flow of the control within the loop is
called controlling variable. ]

Ques What is meant by entry controlled loop? Which java loops are
entry controlled ?
Ans An entry control loop is one for which the test expression is evaluated
before each iteration. The
for( initialization exp; test exp; update expression)
{body of loop} and the while
(condition) {body of the
loop} are the entry
controlled loops.
Q What is meant by exit controlled loop ? Which java loops are exit
controlled loop?
Ans. An exit control loop is one for which the test expression is evaluated after
each iteration. This loop always execute at least once.
do
{
body of the loop} }while
(condition); do while is the exit
controlled loop.
Q What do you mean by nested loop?
A A loop inside another loop is called nested loop.
ICSEIMPNOTES
For eg eg for(int i=0;i<5 ;i++)
{
for(int j=0;j<5 ;j++)
{
System.out.print(j);
}}

Ques What is infinite or endless loop?


Ans: A loop which runs endlessly or infinetly is infinite or endless loop.
For eg for(int i=0; ;i++)
{ }
Ques What are time delay loops?
Ans Time delay loops are created with the help of empty loop body . For
eg.
for(int i=1;i<=100;i++);
Here the loop will run for 100 times without performing anything
Q Give similarity and differences between switch and if-else statement
Ans switch and if-else both are selection statements and are used to select an
alternative out of different alternatives , following are the differences between
two
switch if-else
switch cannot handle floating if-else can handle floating
point tests. (it can only handle point test.
integer and character tests)
It cannot handle ranges It can handle ranges

Q Compare between if and ?: (also known as ternary or conditional


operator)
?: operator if else statement
The conditional operator ?: The if statement can have
produces an expression and multiple assignments and
hence a single value can be expressions in the form of
assigned to a larger expression compound statements.

?: becomes complex when If in nested form is not so


used in nested form. complex
ICSEIMPNOTES
Q Explain break and continue statement with example
Ans : break statement terminates the loop and takes the control out of the loop
to the first statement after the loop . break statement is used in while , do
while, for and in switch statement. In switch case statement it is used to skip
subsequent case conditions. For ex:
int i ;
for(i=1;i<=4;i++)
{ if(i=
=3)

System.out.print(i );

break;

Here output will be


1
2
Her loop will terminate when i= =3, since break will be executed

continue statement : is used to skip rest of the statement after it and takes the
control to the next iteration of the loop. For eg int i ;
for(i=1;i<=4;i++)
{ if(i=
=3)
continue;
System.out.print(i );
}
Here output will be
1
2 4 when i= =3, since continue will be executed then it will take the control
to the next iteration i.e i++, and the statement below it will be skipped thus
3 will not be printed.
ICSEIMPNOTES
Q Give similarity and differences between while and do while statement
Ans: while and do while both are iterative statements Following are the
differences between two
While do-while
In while loop, test expression is In do-while loop, test expression is
evaluated first and if in the evaluated in last thus it will be
beginning condition is false do loop executed at least once even if the
will not work. condition is false
while is an entry control loop do while is an exit control loop

WAP to input a no and check whether it is a


prime no or not.
public class primeno
{
public void main(int n)
{ ICSEIMPNOTES
int i,c=0; for eg if n=7
for(i=1;i<=n;i++) n i n%i c
7 1 0 1
{ 7 2 1 1
7 3 1 1
if(n%i==0) 7 4 3 1
7 5 2 1
{ c++; 7 6 1 1
} 7 7 0 2

}
if(c==2)
System.out.println(n+ " is prime");
else
System.out.println(n+ " is not prime");
}}

Q WAP to input a no and check whether it is a perfect no or


not.
A no is said to be perfect if sum of factors excluding no is
equal to the no Eg 6=1+2+3
public class perfectno
{
public void main(int n)
{ ICSEIMPNOTES
int i,s=0; n i n%i s
6 1 0 0+1
for(i=1;i<n;i++)
2 0 0+1+2
{ 3 0 0+1+2+3
if(n%i==0) 4 2
5 1
{
s=s+i;
}
}
if(s==n)
System.out.println(n+ " is perfect no");
else
System.out.println(n+ " is not perfect no");
}
}

Write a menu driven class to accept a number from the user and check
whether it is a Prime or a Perfect number.
(a) Prime number— (a number is a Prime which is only divisible by 1
and itself ). Eg 7,13 etc
(b) Perfect number— (a number is called Perfect if it is equal to the
sum of its factors other than the number
itself.) Example : 6 = 1 + 2 + 3

import java.util.*;
class number
{ ICSEIMPNOTES
public static void main()
{
int ch,n,c=0,i,s=0;
Scanner sc=new Scanner (System.in);
System.out.println(“Enter 1 to check prime \n 2. to check perfect
no”); ch=sc.nextInt();
switch(ch)
{ case
1:
System.out.println(“Enter the Number :”); n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
System.out.println(n+ " is prime");
else
System.out.println(n+ " is not prime");

break;
case 2:
System.out.print(“Enter the Number :”);
n=sc.nextInt();
for(int i=1; i<n; i++)
{
if(n%i==0)
{ s=s+i;
}
} if(s==n)
System.out.println(n+“ is Perfect Number”); else
ICSEIMPNOTES
System.out.println(n+“ is Not a Perfect Number”);
break; default:
System.out.println("Invlid Input");
}
}
WAP to input a no and print its sum of digits.
For Eg Input 125
(1+2+5)
Output
8

public class sod


{ n r s
0
public void main(int n)
{ int s=0,r; while(n>0) 125 5 0+5
{
r=n%10; s=s+r; 12 2 0+5+2
n=n/10; 1 1 0+5+2+1
}
System.out.println("sum of digits= "+s);
0
}}

WAP to input a no and print largest digit present in the no.


For Eg Input 1275
Output 7

public class largestdigit


{

public void main(int n)


{
int s=0,r,max=n%10;
while(n>0) ICSEIMPNOTES
{
r=n%10;
if(r>max)
{
max=r;
}
n=n/10;
}
System.out.println("largest digit= "+max);
}
}

WAP to input a no and count total no of digits.

public class digitcount


{
n c
public void main(int n) 0
{ int c=0; while(n>0) 123 1
{ 12 2
c++; n=n/10;
}
1 3
System.out.println("no of digits= "+c); 0
}
}

WAP to input a no and print the sum of even and odd digits separately. Eg
Input 1245
Sum of even digits=6
Sum of odd digits=7

public class evenodd


{

public void main(int n)


{
ICSEIMPNOTES
int ev=0,od=0,r;
while(n>0)
{
r=n%10;
if(r%2==0)
{
ev=ev+r; //ev=4+2
}
else
{
od=od+r; //5+1
}
n=n/10;
}
System.out.println("Sum of even digits= "+ev +"\nSum of odd digits= "+od);
}
}

WAP to input a no and check whether it is an


Armstrong no or not.
Eg 153=13+53+33
=1+125+27

public class armstrongno


{
ICSEIMPNOTES
public void main(int n)
{
int s=0,r,t=n;
while(n>0)
{
r=n%10;
s=s+r*r*r; //s=s+(int)Math.pow(r,3);
n=n/10;
}
if(t==s)
System.out.println(t+ " is armstrong no");
else
System.out.println(t+ " is not an armstrong no");
}
}

WAP to input a no and print the sum of first and last digit.
Eg
Input 2347
Output 9

ICSEIMPNOTES
n f
public class sumfirstlast1
{ 2347 7
234 4
public void main(int n) 23 3
{ 2 2
0
int s=0,f=0,l=n%10;
while(n>0)
{
f=n%10;
n=n/10;
}
s=f+l;
System.out.println("sum of first and last digits= "+s);
}
}
oR
public class firstlast
{ n=2347
c=4
public void main(int n)
{
2347/103
int t=n,c=0,f,l=n%10; =2347/1000
while(t>0) =2
{ c++; t=t/10;
}
f=n/(int)Math.pow(10,c-1);
System.out.println("sum of first and last digits= "+(f+l));

}
}

ICSEIMPNOTES
WAP to input a no and check whether it is an
automorphic no or not
152 =225 (15 is not an automorphic no)
52 =25 ( 5 is automorphic no)
252 =625( 25 is automorphic no

public class automorphicno


{

public void main(int a)


{ a=25 b=625
int t=a,c=0,b=a*a,ex; c=2
while(t>0) ex=625%102
{ c++; t=t/10; =625%100=25

}
ex=b%(int)Math.pow(10,c);
if(a==ex)
System.out.println(a+" is Automorohic no");
else
System.out.println(a+" is not an Automorohic no");

}
}

Nested Loop : A loop inside another loop is called nested loop.


For eg

public class nestedloop


ICSEIMPNOTES
{ 1 1
public void main()
1 2
{ int i,j; 2 1
for(i=1;i<=3;i++) 2 2
{ 3 1
for(j=1;j<=2;j++)
{
3 2
System.out.println(i+" "+j);
}
}
}
}

//WAP to print the sum of following series 1+2+3+4+......n public


class series1
{
public void main(int n)
{
int i,s=0;
for(i=1;i<=n;i++)
{
s=s+i;
}
System.out.println("sum of series="+s);
}}
// WAP to print the sum of following series 1!+2!+3!+4!+......n!
public class series2
{
public void main(int n)
{
int i,j,s=0,f;
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++) ICSEIMPNOTES
{
f=f*j;
}
s=s+f;
}
System.out.println("sum of series="+s);
}
}
//WAP to print the sum of following series 1!-2!+3!-4!+......n!
public class series3
{
public void main(int n)
{
int i,j,s=0,f;
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++)
{
f=f*j;
}
if(i%2==0)
s=s-f; else
s=s+f;
}
System.out.println("sum of series="+s);
}}

//WAP to print the sum of following series x/1 + x2/2 +x3/3+…… xn/n
ICSEIMPNOTES
public class series4
{
public void main(int n,double x)
{ int
i,j,f;
double s=0.0;
for(i=1;i<=n;i++)
{
s=s+Math.pow(x,i)/i;
}
System.out.println("sum of series="+s);
}
}

WAP to print the sum of following series x/1! - x2/2! + x3/3! -…… xn/n! public
class series5
{
public void main(int n,double x)
{ int
i,j,f;
double s=0.0;
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++)
{
f=f*j;
}
if(i%2==0) s=s-
Math.pow(x,i)/f;
else
s=s+Math.pow(x,i)/f;
}
System.out.println("sum of series="+s);

ICSEIMPNOTES
}}
WA
P to
print
all
perf
ect
num
bers
from
a to
b
6=1+2+3 , 6 is a perfect no

public class perfectbetweentwono


{
public void main(int a,int b)
{ int
i,j,s;
for(i=a;i<=b;i++)
{
s=0;
for(j=1;j<i;j++)
{
if(i%j==0)
{ s=s+j;
}
}
if(s==i)
System.out.println(i);

}
}
}

ICSEIMPNOTES
WAP to print all prime numbers from a to b

public class primebetweentwonum


{

public void main(int a,int b)


{ int i,j,c;
Let a=3 and b=20
for(i=a;i<=b;i++)
Outer loop of i is executing from
{ c=0; a =3 to b=20
for(j=1; j<=i; j++)
{ if(i%j==0)
Inner loop of j is checking
{ c++;
whether the numbers provided
}
} by i is prime or not
if(c==2) a=3, b=20 output
3
5 System.out.println(i);
7
} 11
} 13
} 17
19

ICSEIMPNOTES
WAP to print all the armstrong numbers from a to b
153 is Armstrong no

public class armstrongbetweenno


{
public void main(int a,int b)
{ int s,r,n,i;
for(i=a;i<=b;i++)
{ n=i; a=100, b=1000
s=0; while(n>0) output 153
{ 370
371
r=n%10; 407
s=s+r*r*r;
n=n/10;
}
if(i==s)
System.out.println(i);
}
}
}

ICSEIMPNOTES
A tech number has even number of digits. If the number is split in two equal
halves, then the square of sum of these halves is equal to the number itself.
Write a program to print all four digit tech numbers. Example :
Consider the number 3025
Square of sum of the halves of 3025 = (30+25)
= (55)
(55)2= 3025 is a tech number.

public class nestedtech


{
public void main()
{ int
x,y,s,n;
for(int i=1000;i<=9999;i++)
{
OUTPUT
n=i;
x=n/100; //first 2 nos
2025
y=n%100; //last 2 nos s=x+y; 3025
if((int)Math.pow(s,2)==n) 9801
System.out.println(i);
}
}
}

ICSEIMPNOTES
WAP to check whether a no is a special no or not
145 is a special no //0+120+24+1
145=1!+4!+5! n=n/10;
=1+24+120 }
if(s==t
)
public class specialno t n r f s
{ 0
public void main(int n) 145 145 5 120 120
14 4 24 144
{ r will hold
1 1 1 145
int i,f,s=0,r,t=n; extracted
while(n>0) numbers first time 5,then 4
{ then 1
r=n%10; f=1;
Calculating factorial of
for(i=1;i<=r;i++) r , for eg if r=5
{ f=f*i; f=1*2*3*4*5= 120
} s=s+f;
System.out.println(t+" is special no");
else
System.out.println(t+" is not a special no");
}
}

ICSEIMPNOTES
Write a program to compute and display the sum of the
following series:
𝟏+𝟐 𝟏+𝟐+𝟑 𝟏+𝟐+𝟑+⋯..𝒏
+ +………
𝟏∗𝟐 𝟏∗𝟐∗𝟑 𝟏∗𝟐∗𝟑∗……𝒏
class series
{
public static void main (int n)
{
double s=0.0,nr,dr;
for(int i=2; i<=n; i++)
{
nr=0.0; dr=1.0;
for(int j=1; j<=i; j++)
{
nr=nr+j;
dr=dr*j;
}
s=s+nr/dr;
}
System.out.print("Sum of series="+s);
}
}

class xyz

ICSEIMPNOTES
{ Output
public static void main () 1 1
{ int i,j; 1 2
for( i=1; i<=3; i++)
{
2 1
for( j=1; j<=2; j++) 2 2
{ 3 1
System.out.println(i+” “+j); 3 2
}

}
} }

WAP to print the following pattern

1
12
123
1234 12345

class Pattern
{
public static void main ()
{ int i,j;
for( i=1; i<=5; i++)
{
for( j=1; j<=i; j++)
{
ICSEIMPNOTES
System.out.print(j);
}
System.out.println( );
}
}
}

WAP to print the following pattern

1
22
333
4444
55555
public class Pattern
{
public static void main( )
{ int i ,j; for (
i=1;i<=5;i++ )
{
for( j=1;j<=i;j++)
ICSEIMPNOTES
{
System.out.print(i);
}
System.out.println();
}
}
}

WAP to print the following pattern

*
**
***
****
*****

class Pattern
{
public static void main ()
{ int i,j;
for( i=1; i<=5; i++)
{
for( j=1; j<=i; j++)
{ ICSEIMPNOTES
System.out.print("*");
}
System.out.println( );
}
}
}
WAP to print the following pattern

55555
4444
333
22
1 public class
Pattern1
{
public static void main( )
{ int i,j;
for ( i=5;i>=1;i-- )
{
for( j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
} ICSEIMPNOTES
}
}

WAP to print the following pattern

54321 4321 321 21


1

public class Pat2


{
public static void main( )
{ int i,j;
for ( i=5;i>=1;i-- )
{
for( j=i; j>=1 ;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}

ICSEIMPNOTES
WAP to print the following pattern

12345
2345
345
45
5

public class pat3


{
public static void main( )
{ int i,j;
for ( i=1;i<=5;i++ )
{
for( j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}

WAP to print the following pattern

1 ICSEIMPNOTES
23
456
7 8 9 10
Class Pattern
{
public static void main ()
{ int i,j,k=1;
for( i=1; i<=4; i++)
{
for( j=1; j<=i; j++)
{
System.out.print(k+" ");
k++;
}
System.out.println( );
}
}
}

ICSEIMPNOTES
WAP to print the following pattern

****1
***12
**123
*1234
12345

class P6
{
public static void main ()
{
int i,j,k;
for( i=1; i<=5; i++)
{
for( k=4; k>=i; k--) //loop for printing *
{
System.out.print("*");
}
for( j=1; j<=i; j++) //loop for printing numbers
{
System.out.print(j);

}
System.out.println( );
}
}
}

ICSEIMPNOTES
WAP to print the following pattern

1
12
123
1234
12345

class P6
{
public static void main ()
{
int i,j,k; for(
i=1; i<=5; i++)
{
for( k=4; k>=i; k--)
{
System.out.print(" ");
}
for( j=1; j<=i; j++)
{
System.out.print(j);
}
System.out.println( );
}
}
}

ICSEIMPNOTES
WAP to print the following pattern

A
BC
DEF
GHIJ
KLMNO

class Pat7
{
public static void main ()
{ int i,j;
char ch='A';
for( i=1; i<=5; i++)
{
for( j=1 ;j<=i; j++)
{
System.out.print(ch);
ch++;
}
System.out.println( );
}
}
}

ICSEIMPNOTES
Q Explain break and continue statement with example
Ans : break statement terminates the loop and takes the control out of the loop
to the first statement after the loop . break statement is used in while , do
while, for and in switch statement. In switch case statement it is used to skip
subsequent case conditions. For ex:
int i ;
for(i=1;i<=4;i++)
{ if(i=
=3)

System.out.print(i );

break;

Here output will be


1
2
Her loop will terminate when i= =3, since break will be executed

continue statement : is used to skip rest of the statement after it and takes the
control to the next iteration of the loop. For eg int i ;
for(i=1;i<=4;i++)
{ if(i=
=3)
continue;
System.out.print(i );
}
Here output will be
1
2 4 when i= =3, since continue will be executed then it will take the control
to the next iteration i.e i++, and the statement below it will be skipped thus
3 will not be printed.
ICSEIMPNOTES
Write Output

class breout
{
public static void main ()
{ int i,j;
for( i=1; i<=3; i++)
{
for( j=1; j<=3; j++)
{
if(i==j)
break;
System.out.println(i+" "+j);
}
WORKING
} 1 1 break ×
} 1 2 ×
1 3 ×
} 2 1
2 2 break ×
2 3 ×
3 1
3 2
3 3 ×

OP:- 16
3.0 19
3 ICSEIMPNOTES 20
Write Output

class breout
{
public static void main ()
{ int i,j;
for( i=1; i<=3; i++)
{
for( j=1; j<=3; j++)
{
if(i==j)
break;
System.out.println(i+" "+j);
}
break;
}
}
}

Nothing will be printed

ICSEIMPNOTES
Write Output

class contout
{
public static void main ()
{ int i,j;
for( i=1; i<=3; i++)
{
for( j=1; j<=3; j++)
{
if(i==j)
continue;
System.out.println(i+" "+j);
}
WORKING
} 1 1 continue ×
} 1 2
1 3
} 2 1
2 2 continue ×
2 3
3 1
3 2
3 3 continue ×

ICSEIMPNOTES
Output
12
13
21
23
31
32

LESSON- 2
CLASS AS THE BASIS OF ALL
COMPUTATION

A class is a template or an object factory or a Blueprint


of objects.
Characteristics of a class-:
1. It creates objects.
2. May create one or two or more objects.
3. Contains attributes (or variables) and
methods.

ICSEIMPNOTES
An object may be considered to be a material with
physical existence.
• Objects are distinguished from one another as
their sets of values of the attributes or variables are
different.
• They are different on the basis of their states.
• The states of two objects cannot be same.
Two integral features of every object are- State and
Behaviour.
Collection of a number of items into a single entity or
capsule is referred as Encapsulation.
Tokens are the smallest individual units of a
Java program. Example-
i. Literals
ii. Keywords iii. Identifiers iv. Operators
v. Punctuators.
Literals are data items which have constant or fixed
data values. Example-
i. Float
ii. Integer
iii. String iv. Character
ICSEIMPNOTES
v. Boolean
vi. Null literals
Reference variables are data locations which store
memory addresses of reference datatypes.
Initialization is the process of assigning a specific
initial value to a variable. It can be done in three ways-
i. Using a literal. Example- int x=5
ii. Using another variable as reference.
Example- byte y=1 int x=y iii. Calling a method and
using its return value as the initial value (dynamic
initialization)
Initial value-
• 0 for byte, short, int
• 0 l for long
• 0.0 f for float
• 0.0 d for double
• Null character (‘\u 0000’) for char
• False for Boolean
• Null for references type data
Instance variables or object variables are those
attributes which differentiate one object from another.
Illustration: ICSEIMPNOTES
Class studentTenB
{
String name; Int
age;
Int rollno.;
}
The instance variable in this class rollNo. As no two
students in this class can have same rollNo. But names
and ages of two objects may be identical.
Function of new operator- to create new objects
corresponding to a class.
Function of instanceOfoperator checks whether the
first operand (an object) is an instance of the second
operand (a class).
FORMAT: <name of object> instance of <name of a
class>
In Java Library, Math class is included in Java.lang
package. Some mathematical available in Math
class:
Function Description Example

ICSEIMPNOTES
PI Returns the value 3.142…
(double) of π
Log (x) Returns the (double) Log(2)=0.302…
value of log of x w.r.t
base e (natural log.
Returns the absolute
Abs (x) Abs(9.32)=9.32
value of any numeric
type data. Abs(-9.32)=
9.32

Returns the larger


out of x & y.
Max (x,y) Max (9,13) = 13
Returns the smaller
out of x & y. Min (9,13) = 9
Min (x,y) Returns the positive
square root x Sqrt (3) =
(double value) 1.73205…
Sqrt (x)

ICSEIMPNOTES
Pow (x,y) Returns the (double) Pow (3,4) = 81
value of x,y
Round (x) Rounds up to the Round (8.42) =
nearest integer 8
Round (8.74) =
9
Floor (x) Returns the integer Floor (27.92) =
which is less than or 27
equal to x
Ceil (x) Floor (5.07) = 5
Returns the smallest Ceil (2.25) = 3
integer greater than
or equal to x Ceil (2.79) = 3

When different types of variables and constants are


mixed up in an expression, they are converted in one
common type implicitly by the compiler. This is called
Type Conversion.
When are operand are converted into the type of a
higher order type, the process is implicitly undertaken
by the compiler. This is called Type Promotion.
User-defined type conversion is known as Explicit Type
Conversion or Type Casting.
ICSEIMPNOTES
Precision isCLA the extent of numerical accuracy of
floating point and double type members. It refers to
the number of accurate digits after the decimal point.

LESSON-3
User Defined methods(Functions)
Syntax of Function Definiton

[access specifier] [modifier] return type functionname(datatype v1, datatype v2,…)


{
-----body of fn
----
}

Syntax of Function call

Functionname(v1,v2,…);

Calling function through object


Objectname.Functionname(v1,v2,…);

Ques: What is Function(Method):


Ans Function(Method) is a sequence of statements that carry out specific task(s).

Ques. What are advantages of using functions?


Ans: Advantages of using functions are (i) function reduces complexity of programs (ii) functions
enhances reusability of code. (iii)Functions hides the implementation details.

Ques: What are actual parameters ?


Ans : Actual parameters are the parameters that appear in function call.
Eg sum(a,b); here a,b are Actual parameters. Actual parameters can be constants.

ICSEIMPNOTES
Ques: What are formal parameters ?
Ans : Formal parameters are the parameters that appear in function definition.

void sum(int a,int b)


{

here a,b are formal parameters

Ques: Explain the function of return statement.


Ans (i) Return statement causes an immediate exit from the function.
(ii) Return statement is used to return the value to the calling function.
Ques When do we use void as return type?
Ans When the function do not return any value then the return type of the function is declared as void. For eg void
display( )
{
System.out.println(“abc”);
}

Ques : How do we call(invoke or executed) a function?


Ans : A function is called or invoked by providing the function name, followed by parameters being sent enclosed in
parenthesis. For eg to call whose function prototype is as double area(double , double) The function cal will be
area(a,b);
Ques : Differentiate between Pure Function & Impure Function.
Pure Function Impure Function

A function that does not change or modify the A function that change or modify the state of
state of their parameters received are pure their parameters received are Impure function
function

Ques : Differentiate between Call by value & Call by reference.


Call by value Call by reference

In call by value any change in formal parameter In call by reference any change in formal
is not reflected in the actual parameters parameter is reflected in the actual parameters

Primitive data type are passed in call by value Reference data type are passed in call by
reference

Ques : What is function definition?


Ans : The function declaration and the body of the function forms function definition. For eg double
area (double rad )
{
return (3.14*rad*rad);
}
Ques : What is function prototype (or function declaration)?
Ans First line of function definition that tells about the type of value returned by the function & number and
type of arguments passed is called function prototype. Eg double area (double rad )

ICSEIMPNOTES
Ques : What is function signature?
Ans Function signature refers to the number and types of arguments passed and is a part of function prototype.
void area (int l,int b) here int l,int b is Function signature

Ques : How many values can a function can return?


Ans A function can return only a single value.

Ques : How many types of functions are in Java?


Ans : There are three types of functions
1. Computational Functions are the functions that calculate and return calculated value. For eg Math.sqrt(
25 )
2. Manipulative Functions : The functions that manipulate information and return a success or failure code.
3. Procedural Functions : The function that perform an action and have no explicit return value for eg
System.out.println( )

Ques: Explain function overloading with Eg


Ans : Function overloading refers to a class having more than one function with same name but
different function signature(ie different number or types of arguments) is known as function
overloading.
For eg, Following code overloads a function area to compute areas of circle & rectangle.

double area (double rad )


{
return (3.14*rad*rad);
}
double area (double len, double brd )
{
return (len*brd);
}

Ques Define Polymorphism .How is it implemented through function overloading?


Ans: Polymorphism is the ability of an object to behave differently in different circumstances Function overloading
refers to a class having more than one function with same name but different function signature which means same
function behaves differently depending upon the circumstances ( i.e function signature) hence function overloading
is a means through which polymorphism is implemented.

Ques: Why do you think that function overloading must be a part of object oriented language? Ans: A function
overloading is a part of an object oriented language as it is the feature that implements polymorphism in an object
oriented language that is the ability of an object to behave differently in different circumstances.

Ques: Are function with the same name and same function signature but different return type are allowed in java?
Ans Function with the same signature & different return type are not allowed in java.
For eg int area(double a) double area(double b) // error,
since same signature.

Ques: What is the use of static keyword in function prototype?


Ans: If we use static in function prototype the function can be called through class without creating its object.
Ques : What is ‘this’ keyword?
ICSEIMPNOTES
Ans ‘this’ keyword refers to the current object.

Ques: Write the function prototype of the function abc( ) which takes two integer variables as its arguments and
returns a value of double datatype
Ans : double abc(int a,int b)
Ques Write a function call statement for the function whose prototype is void xyz(int a,double b) Ans xyz(a,b);

Ques Write java statement to compare 50 & 500 by calling the function void compare(int m,int n) Ans
compare(50,500);

Ques Write function prototypes for the following:


1. Private access method sum which accepts three int type variables as
parameters and return a float type.
Ans. private float sum(int a,int b,int c)

2. Default access method “length” which accepts a String type variable as


parameter and returns an int type.
Ans. int length(String s)

Public access method “increment” which accepts an object of Myclass type as parameter
and does not return any value.
Ans. public void increment(Myclass ob)
3. Protected access method largest which accepts a float type, int type and
double type data as parameters and have a byte type as return type.
Ans. protected byte largest(float a, int b, double c)
4. Public access static method calculate which accepts a byte and int type
data type as parameters and return float type.
Ans. public static float calculate(byte b, int d)

5. Write the function prototype for the function “sum” that takes an integer
variable (x) asits argument and returns a value of float data type.
Ans. float sum(int x)

6. Write the prototype of a function which takes in 2 integers and 1 String arguments
and returns a value which is either ‘true’ or false’.
Ans. boolean function(int a,int b,String c)

ICSEIMPNOTES
Write the output of the following when main function is called public class
abc1 Output when main()
{ is called
void main( )
{ i am in fun
fun();
System.out.println("i am in main"); fun(); i am in main
System.out.println("i am back in main");
i am in fun
}
void fun( ) i am back in main
{
System.out.println("i am in fun");
}
}
WAP to create a function sum( ) which prints the sum of two numbers. Call this function from main() class xyz
{
void main()
{
sum();
}
void sum()
{
int a=2,b=3,s; s=a+b;
System.out.println(“Sum=”+s);
}}
Here sum() is a function without parameter and without return type

WAP to create a function void sum(int a, int b ) which receives two integer numbers
and prints the sum of two numbers. Call this function from main()
class xyz import java.util.*;
class xyz class xyz
{
{ {
void main()
void main(int x, int y) { void main()
{ sum(2,5);
{
sum(x,y); int x,y;
} Scanner sc =new Scanner (System.in);
} void sum(int a, int b)
void sum(int a, int b) System.out.println(“Enter 2 nos”);
{ x=sc.nextInt();
{ int s=a+b; y=sc.nextInt();
int s=a+b; System.out.println(“Sum=”+s); sum(x,y);
System.out.println(“Sum=”+s); } }
} } void sum(int a, int b)
} {
int s=a+b;
System.out.println(“Sum=”+s);
Here void sum(int ,int ) is a function wi th parameter and without return type }
}

WAP to create a function int sum(int a, int b ) which receives two integer numbers and returns the sum of two numbers. Call this
function from main() and print sum in main function.

ICSEIMPNOTES
class xyz
{
void main(int x, int y)
{
int k=sum(x,y);
System.out.println(“Sum=”+k);
}
int sum(int a, int b)
{ int
s=a+b;
return(s);
}
}

Here int sum(int a, int b) is a function with parameter and with return type

WAP to create a function


(i) double si(double p, double r, int t) which returns simple interest
WAP to create a function int big(int a,int b) (ii) double ci(double p, double r, int t) which returns compound interest
which receives two integer numbers and returns Call this function from main() and print the simple and compound
the bigger of the two numbers if both the interest in the main() function
numbers are same function returns -1. Call this
function from main() and print the bigger no or class SimpleCompoundInt
message both are equal. {
void main(double x,double y,int z)
public class bignum_1 {
double x= si(x,y,z);
{ double y= ci(x,y,z);
void main(int x,int y System.out.println("Simple Intrest ="+x+"\nCompound Intrest="+y);
) }
double si(double p, double r , int t)
{ {
int double s=(p*r*t)/100;
k=big(x,y); return(s);
if(k==-1) }
double ci(double p,double r,int t)
System.out.println("Both are equal"); {
else double b=(1+r/100);
double c=p*Math.pow(b,t) -p;
System.out.println(k+"is bigger"); return (c);
}
} }
int big(int a,int
b)

{
if(a>b)
return(a);
else
if(b>a)
return(b);
else
return (-
1); ICSEIMPNOTES
}

ICSEIMPNOTES
WAP to create a Function int isprime(int n) which
WAP to create a Function boolean
returns 1 if n is prime else returns 0.
isprime(int n) which returns true if n isNow
primecall this function from another function
else returns false. Now call this function from ) and print the message whether a number
main(
is a prime no or not in main( ) fun.
another function main() and print the
message whether a number class
is a prime prime_class_1
no or
not in main() fun. {
void main(int n)
{
class prime_class_1 if(k)
int k= isprime(n);
can be written in
{ place ofif(k==1)
void main(int n) System.out.println(n+" is prime"); else
if(k==true)
{ System.out.println(n+" is not prime");
boolean k= isprime(n); }
int isprime(int n)
if(k==true) { int
System.out.println(n+" is prime"); i,c=0;
else for(i=1;i<=n;i++)
{
System.out.println(n+" is not prime");if(n%i==0)
{
} c++;
boolean isprime(int n) }
{ } if(c==2)
int i,c=0; return(1); else
for(i=1;i<=n;i++) return(0);
{ }
if(n%i==0) }
{
c++;
}

if(c==2)
return(true);
else
return(false);
}
}

ICSEIMPNOTES
WAP to create a Function int isprime(int n) which returns 1 if n is prime else returns 0. Now call this
function from another function void printprime(int a, int b) Which prints all the prime numbers from a
to b
Eg a=6 b=15
Output
7
11
13

public class primenumber


{
int isprime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2) return(1); else
return(0);
}

void printprime(int a, int b)


{
int i;
for(i=a;i<=b;i++)
{
if(isprime(i)==1)
{
System.out.println(i);
}
}
}
}

WAP to create a Function


(i) int isprime(int n) which returns 1 if n is prime else returns 0.
(ii) int ispalin (int n) which returns 1 if n is palindrome else returns 0. (A number is said to be palindrome if it remains same
if its digits are reversed eg 121 ,3223 etc)
Now using these functions create a function printprimepalindrome(int a, int b) which prints all the prime palindromic
numbers from a to b
Eg a=7 b=150 output
7
11
ICSEIMPNOTES
101
131 public class primepalincheck
{
int isprime(int n)
{ int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2) return(1); else
return(0);
}
int ispalin (int n)
{
int r,rev=0,t=n; while (n>0)
{
r=n%10; rev=rev*10+r; n=n/10;
}
if(rev==t) return(1); else
return(0);
}
void printprimepalindrome(int a, int b)
{ int i;
for(i=a;i<=b;i++)
{
if(isprime(i)==1 && ispalin(i)==1)
{
System.out.println(i);
}
}
}
}

WAP to create a Function


(i) int revnum(int n) which returns reverse of n
Now using this function create a function void printpalindrome(int a, int b) which prints all the
numbers from a to b and their reverse in the following format
Eg a=112 b=115
output
Number Reverse
112 211
113 311
114 411
115 511
public class numrev
{ ICSEIMPNOTES
int revnum(int n)
{
int r,rev=0,t=n;
while (n>0)
{
r=n%10; rev=rev*10+r;
n=n/10;
}
return(rev);
}

void printpalindrome(int a, int b)


{ int i;
System.out.println("Number\t Reverse");
for(i=a;i<=b;i++)
{
System.out.println(i+"\t"+revnum(i));
}
}
}

WAP to create a Function int firstlastdigit(int n) which returns sum of first and last digit
Now using this function create a function void main(int a,int b) which prints all the numbers
from a to b and their sum of first and last digit in the following format
Eg a=112 b=115
output
Number Sum of first and last digit
112 3
113 4
114 5
115 6

ICSEIMPNOTES
public class firstlastsumclass
{
void main(int a,int b)
{ int i,k;
System.out.println("Number\tSum of first and last digit"); for(i=a;i<=b;i++)
{
k=firstlastdigit(i);
System.out.println(i+"\t\t"+k);
}
}

int firstlastdigit(int n)
{ int l,f=0; l=n%10;
while(n>0)
{
f=n%10;
n=n/10;
}
return(f+l);
}
}

WAP using concept of function overloading to overload function num_calc( )

(i) void num_calc(int num, char ch)


which prints square of number if character is ‘s’ or ‘S’ otherwise prints its cube.
(ii) void num_calc(int a,int b,char ch) which prints product of two integer
numbers if ch is ‘p’ else prints sum of two numbers.
(iii) void num_calc(int a,int b) which prints bigger of a and b.

public class eclss_1


{
void num_calc(int num, char ch)
{
if(ch=='s'||ch=='S')
System.out.println("Square="+(num*num)); else
System.out.println("Cube="+(num*num*num));
}

void num_calc(int a,int b,char ch)


{
if(ch=='p')
System.out.println("Product="+(a*b)); else
System.out.println("Sum="+(a+b));
}
ICSEIMPNOTES
void num_calc(int a,int b)
{
if(a>b)
System.out.println(a+"is bigger"); else
System.out.println(b+"is bigger");
}
}

public class functionoverloadig_2016


{
void SumSeries (int n, double x)
{
int i;
double s=0.0;
for(i=1;i<=n;i++)
{
if(i%2==0)
s=s- x/i;
else
s=s + x/i;
}
System.out.println("sum of the series="+s);
}

void SumSeries()
{
int i,j,s=0,f;

for(i=1;i<=20;i++)
{
f=1;
for(j=1;j<=i;j++)
{
f=f*j;
}
s=s+f;
}
System.out.println("sum of the series="+s);
}
void main()
{
SumSeries (3,2.0);
ICSEIMPNOTES
SumSeries ();
}
}

public class functionoverloading_2019


void series (int x, int n)
{
double s=0.0;
int i;
for(i=1;i<=n;i++)
{
s=s+Math.pow(x,i);
}
System.out.println("sum of the series="+s);
}
void series (int p)
{
for (int i=1; i<=p; i++)
System.out.print(((int)Math.pow(i,3)-1+","));
}
void series ( )
{
double s=0.0;
for (int i=2; i<=10; i++)
{
s=s+1/(double) i;
}
System.out.println("sum of the series="+s);
}
void main()
{
series(2,3); series(4);
System.out.println(); series();
}

ICSEIMPNOTES
}

public class polygonclass


void polygon()
{
{
void polygon(int n,char ch)
int i,j;
{
for(i=1;i<=3;i++)
int i,j;
{
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
{
{
for(j=1;j<=n;j++)
System.out.print("*");
{
}
System.out.print(ch+" ");
System.out.println();
}
}
System.out.println();
}
}
}
void main()
{
void polygon(int x,int y)
{ polygon(2,'O');
int i,j; polygon(2,5);
for(i=1;i<=x;i++) polygon();
{ }
for(j=1;j<=y;j++) }
{
System.out.print("@ ");
}
System.out.println();
}
}

ICSEIMPNOTES
LESSON-4

Constructors

Ques: What is constructor?


Ans A constructor is a member function with the same name that of its class and it is used to initialize the objects of
that class with legal initial values.

Ques Write characteristics of constructors.


1. Constructor has the same name as that of class.
2. A constructor is invoked automatically when the objects of its class are created.
3. A constructor has no return type, not even void.

Ques What are the 2 types of constructors?Give Examples.


Ans The two types of constructors are
(1) Default Constructor: A constructor that do not accepts any parameter is called default or non parameterized
constructor.
Example public class def
{ int x;
public def()
{
x = 10;
}
public void show ()
{

System.out.println(x);
}
}
(2) Parameterized constructor: A constructor that accepts one or more parameters is called parameterized
constructor.
Eg public class par
{
int x;
public par(int a)
{
x = a;
}
public void show()
{
System.out.println(x);
}
}

Ques. What do you mean by temporary instance of a class?


ICSEIMPNOTES
Ans A temporary instance of a class means an object of a class do not having any name and is required for a short time.

Ques: Explain constructor overloading with Eg.


Ans : When two or more constructors are defined in a class with different number and type of parameters is known
as constructor overloading.

For Example public class abc


{
int x;
public pqr( )
{
x= 5;
}
public pqr(int a)
{
x = a;
}
}

Ques: Differentiate between constructor and methods(functions)

constructor methods(functions)

Constructor is a member function Method(or Function)is a member


having same name as that of class function having different name from its
class
Constructors do not have return type Methods(Fuctions) can return value
hence they have return type.
Constructors are invoked automatically Methods (functions) are required to be
when object is created called.

ICSEIMPNOTES
import java.util.*;
class ElectricBill void print ( )
{ {
String n; int units; double bill; void accept() System.out.println("Name of the customer:"
{ +n+ "\nNumber of units consumed:"+units+
Scanner sc=new Scanner (System.in); "\nBill amount:"+bill);
System.out.println("Enter name of the customer"); }
n=sc.nextLine(); public static void main()
System.out.println("Enter no of units consumed"); {
units=sc.nextInt(); ElectricBill EC=new ElectricBill();
} EC.accept();
void calculate() EC.calculate();
{ EC.print ();
if(units<=100) bill=units*2.0; }
if(units>100 && units<=300) }

bill=100*2.0+(units-100)*3.0; if(units>300)
{
bill=100*2.0+200*3.0+(units-300)*5.0; bill=bill
+(bill*2.5/100);
}
}

ICSEIMPNOTES
void calculate()
import java.util.*; class ShowRoom {
{ if(cost <=10000)
{
dis=0.05*cost;
String name; long mobno; double
}
cost,dis,amount;
else if(cost >10000 && cost <=20000)
{
public ShowRoom() dis=0.1*cost;
{ }
name = ""; cost=0.0; mobno=0l; else if(cost >20000 && cost <=35000)
dis = 0.0; {
amount=0.0; dis=15.0/100*cost;
} }
else if(cost >35000)
{
void input()
dis=0.2*cost;
{
}
Scanner sc=new Scanner (System.in); amount = cost - dis;
System.out.println("Enter Name"); }
name=sc.nextLine(); System.out.println("Enter void display() Mobile
No"); mobno=sc.nextLong(); {
System.out.println("Enter Cost"); System.out.println("Name :"+name);
cost=sc.nextDouble(); System.out.println("Mobile no is :"+mobno);
} System.out.println("Amount :"+ amount);
}
public static void main ()
{
ShowRoom ob = new ShowRoom();
ob.input(); ob.calculate();
ob.display();
} }

ICSEIMPNOTES
import java.util.*; void discount()
{
class FruitJuice
product_price=product_price-10;
{ }
int product_code,pack_size,product_price;
void display()
String flavour,pack_type;
{
public FruitJuice() System.out.println("Product
{ Code="+product_code);
product_code=0; System.out.println("Flavour="+flavour);
System.out.println("Pack type="+pack_type);
pack_size=0;
System.out.println("Pack size="+pack_size);
product_price=0; System.out.println("Product
flavour=""; Price="+product_price);
}
pack_type="";
} public static void main()
{
void input() FruitJuice ob=new
FruitJuice(); ob.input();
{ ob.discount();
Scanner sc=new Scanner(System.in); ob.display();
}
System.out.println("Enter product code");
}
product_code=sc.nextInt();
System.out.println("Enter pack size");
pack_size=sc.nextInt();
System.out.println("Enter product price");
product_price=sc.nextInt();
System.out.println("Enter Flavour ");
flavour=sc.nextLine();

ICSEIMPNOTES
System.out.println("Enter pack type");
pack_type=sc.nextLine();
}

ICSEIMPNOTES
import java.util.*; void display()

{ class
Mobike
System.out.println("Bike No.\t Phone No.\t
Name\t No. of days\t charge");
{
System.out.println(bno+"\t"+phno+"\t"+name+"
\t\t"+days+"\t"+charge);
String bno,name;
long phno; }

int days; public static void main()


double charge; {
Mobike ob=new Mobike();
void input() ob.input(); ob.compute();
{ ob.display();
Scanner sc = new Scanner(System.in); }
}
System.out.println("Enter Bike number");
bno=sc.nextLine();

System.out.println("Enter mobile no");


phno=sc.nextLong();
System.out.println("Enter name of customer");
name=sc.nextLine();
System.out.println("Enter no of days bike is taken on
rent");
days=sc.nextInt();
}
void compute()
{
if(days<=5)
charge=days*500;
if(days>5&&days<=10)
charge=5*500+(days -
5)*400;
if(days>10)
charge=5*500+5*400+(days -10)*200;
}

ICSEIMPNOTES
Programs based on Parameterized Constructor

A class Worker has been defined to store the details of a worker.


Class name : Worker
Data members :
Name :to store the name of the worker
Basic :to store the basic pay in decimal
hrs :stores the hours worked
rate :stores rate per hour
wage : :stores the overall wage of the worker
Member functions
Worker(…..) : parameterized constructor to assign values to the
instance variables
double overtime( ) : calculates and returns the overtime amount as (hours *
rate )
void display() : calculates the wage using the formula wage=overtime
amount +basic pay and displays it along with other details
Specify the class Worker giving details of the constructor(),double overtime() and void display(). Write
main()function to create an object and call the functions accordingly to enable the task.

public class Worker


{ ICSEIMPNOTES
String Name; double
Basic,rate,wage;
int hrs;
public Worker(String N, double B, double r, int h )
{
Name=N;
Basic=Basic; rate=r;
hrs=h;
wage=0.0;
}
double overtime()
{
double ovt= hrs*rate; return(ovt);
}
void display()
{
wage=Basic+overtime();
System.out.println("Name="+Name+"\nBasicSalary="+Basic+"\nHours Worked="+hrs
+ "\n Rate="+rate+"\nWages="+wage);
}
public static void main()
{
Worker W=new Worker("xyz",10000.0,100.0,5);
W.display();
}
}

Design a class name ShowRoom with the following description :

Instance variables/ Data members :


String name – To store the name of the customer long mobno – To
store the mobile number of the customer double cost – To store the
cost of the items purchased double dis – To store the discount amount
double amount – To store the amount to be paid after discount

Member methods: –
ShowRoom(String n, long mob, double c) – parameterised constructor to initialize data members

void calculate() – To calculate discount on the cost of purchased items, based on following criteria
Cost Discount (in percentage)
Less than or equal to Rs10000 5%
More than Rs 10000 and less than or equal to Rs 20000 10%
More than Rs 20000 and less than or equal to Rs 35000 15%
More than Rs 35000 20%

void display() – To display customer name, mobile number, amount to be paid after discount

Write a main method to create an object of the class and call the above member methods.
class ShowRoom
{
String name; long mobno;
ICSEIMPNOTES
double cost,dis, amount;

public ShowRoom(String n, long mob, double c) // parameterised constructor to initialize data members

{
name=n;
mobno=mob;
cost = c;
dis = 0.0;
amount =0.0;
}
void calculate( )
{
if (cost<=10000) dis= cost*5/100;
else if(cost>10000 && cost<= 20000) dis = cost*
10/100;
else if (cost>20000 && cost <= 35000) dis = cost*
15/100; else if (cost > 35000) dis = cost*20/100;
amount=cost-dis;
}

void display()
{
System.out.println("Name " +name);
System.out.println("Mobile No " +mobno);
System.out.println("Amount " +amount);
}

public static void main()


{
ShowRoom ob = new ShowRoom("XYZ",989999999l,10000.0 ); ob.calculate( );
ob.display();
}
}

Autoboxing: Converting a primitive value into an object of the corresponding wrapper class is
called autoboxing.
For example, converting int to Integer class.
int i=100;
Integer j=i ; //Autoboxing
Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called
unboxing.
For Example conversion of Integer to int.
Integer a = new Integer(10); // creating an Integer Object with value 10 int i = a; //
unboxing the Object

ICSEIMPNOTES
import java.util.*;
public class ASCII
{
char ch; void accept()
{
Scanner sc=new Scanner(System.in); System.out.println("Enter a character");
ch=sc.next().charAt(0);
}
public void print()
{
String x;
if(ch>=48&&ch<=57) x="digit"; else
if(ch>=65 && ch<=90) x=" upper case
ICSEIMPNOTES
letter"; else if(ch>=97 && ch<=122) x="
lower case letter"; else
x="special character";
System.out.println("Character \t ASCII value \tType of Character");
System.out.println(ch+"\t\t"+(int)ch+"\t\t"+x);
}
OUTPUT
public static void main()
Enter a character
{
A
ASCII ob=new ASCII(); ob.accept();
Character ASCII value Type of Character
ob.print();
} A 65 upper case letter
}

ICSEIMPNOTES

You might also like