Java Theory Till Iteration
Java Theory Till Iteration
Application of OOPs:
➢ Object oriented database
➢ Parallel programming
➢ Networking
➢ Computer aided design system
➢ Decision support system
The first two generations are called low level languages. The next three
generations are called high level languages.
Interpreter
Interpreter is a translator which is used to convert programs in high-level language
to low-level language. Interpreter translates line by line and reports the error once
it encountered during the translation process. It gives better error diagnostics
than a compiler.
Assembler
Assembler is a translator which is used to translate the assembly language code
into machine language code.
i) Super Class:The class from which the properties are getting inherited is known as Super Class. It is also
known as Parent Class or Base Class. ii) Sub Class: The class which inherits the properties of other class is
known as Sub Class. It is also known as Child Class or Derived Class.
Ex: Heredity is the example of Inheritance in which child get characteristics of their parent.
Polymorphism:If a function behaves differently for different objects then it is known as polymorphism. Function
overloading is an example of polymorphism.
Ex: void shape (), void shape(int , int) , void shape(int), void shape(int, float)
Application of OOPs:
Introduction To Java
Java is a popular third generation programming language which can be used to create various types of computer
applications. It is a high level language based on OOP concepts. It was originally named as OAK and was developed at
Sun Microsystem in 1991. Features Of Java:
Byte Code:The java compiler translates the source code to an intermediate code called Byte Code. It is independent of
operating system. Java interpreter called JVM(Java Virtual Machine)reads this byte code and convert it into machine
code for different platforms i.e. OS. Due to Byte code java is platform independent language.
Ordinary Compilation: Ordinary compiler converts the source code into machine executable code i.e. binary.
Compiler:It is a software which converts source code to machine code at once and it will show all the errors if any. Its
speed is fast.
Interpreter:It is software which converts source code to machine code line by line. Control will reach to the next line
after removing the errors (if any) of the previous line. Its speed is slow
Access Specifier:Access specifier is a tool to determine whether a method or data member can be accessed by another
method or not. There are three types of access specifier are provide by java:
i) public:If data members are declared as public they can be access inside the class, outside the class, in sub
classes i.e. any where in the program.
ii) private: if data members are declared as private they can be accessed inside the class only not outside.
iii) protected: If data members are declared as protected, they can accessed inside all the classes of the
same package or any sub classes in other package.
Keywords:These are the reserved words that convey a special meaning to the java compiler. Keywords must be written
in small letters because java is case sensitive language. Any change in keywords causes a syntax error. Ex: byte, int, if,
break, else etc. Java has 50 keywords.
true, false,null are reserved words but not keywords
Identifier:A symbolic name used for various data items is known as identifier. It is a fundamental building block of a
program and is used to give name to different parts of a program like name for variables, class, object, array, functions
etc.
Rules for naming an identifier:
1. Integer literal:The numeric values which are represented without decimal points are called integer literals. They
are numbers having +ve or –ve sign. Ex: 142, -898, 20 etc. It is following types:
I.Decimal literals (Base 10)
II.Octal literals (Base 8)
III.Hexadecimal literals (Base 16)
2. Real literals: These are also called floating point literals. They represent numbers with decimal point literals. It
must have at least one digit before the decimal point and one after the decimal point. Ex: 24.6, 0.0056, 1.6 E -19
3. Character literals: A character literal contains a single character at a time enclosed within single quotes. It may
be alphabet, digit or any special character. Ex: ‘a’, ‘8’, ‘@’ etc.
4. String literal: A set of one or more than one character enclosed within double quotes is known as string literal.
Ex: “XYZ”, “rjp17”, “public” etc.
5. Boolean literal: The Boolean literals stores only true or false.
6. Null literals: Null literal can store always one value i.e. null.
Separator: Separator is also called punctuator. There are 9 separators used in java like ( ) { } [ ] : ; ,
Operator: Operator is the symbol used to perform specific operation on the operands. There are following types of
operators:
1. Unary Operator : An arithmetic operator which applied on a single operand is called operator. It is different
types:
Unary(+) Operator: Ex. +a=10,a=-8, +a=-8
Unary (-) Operator: Ex: a=10, -a=-10,a=-8, -a=8
Unary (++) Operator:It is used to increment the value of operand by 1.
Unary (--) Operator: It is used to decrement the value of operand by 1.
Prefix: “change then use”. Eg:- int a=4,b=9,r; r= ++a ; r and a both will be 5
Postfix: “Use the change” Eg:- int a=4,b=9,r; r= a-- ; r will be 4 and a will be 5
2. Binary Operator:The operator which requires minimum two operands is called binaryoperator.
I. Arithmetic operator: The operator which is applied to perform arithmetic operation or mathematical
calculation is called arithmetic operator. The result of arithmetic is numeric. Ex. +, -, *, /, % + sign is also used
with string Ex: “5” + “b”=”5b”
II. Relational operator: A relational operator compares two operands and determines the relationship between
them. The result of relational operator is in Boolean value i.e. true or false. Ex: <, <=, >, >=, ==, ! =
III. Logical operator: Logical operator is used to connect existing relational operator. There are three logical
operators are use in java which are AND (&&), OR (||) and NOT (!).
IV. Assignment operator: Assignment operator is used to assign the value of expression on the right side to
variable on the left side. Ex: a=8
V. Shorthand assignment operator: This assignment operator allows performing arithmetic operation and both
using one operator. Ex. +=, -=, *=, /=, %=
3. Ternary operator: This operator which requires three operands is called ternary operator. It is also called
conditional operator. Syntax: result= expression1? expression2 :expression 3
Operand: The value(constant), variable or object on which an operation is performed by operator is called operand.
Expression : Combination of operands and operators is called Expression.
Types of expression
1. arithmetic expression:The expression which Represents a numeric value.
there are three types of arithmetic expressions
a. Integer expression : The expression containing all integer constants and variables joined with arithmetic
operators.
b. real expression : The expression containing all real constants and variables joined with arithmetic
operators.
c. mixed expression : Combination of integer and real expression
2. String expression: A expression which represents a string value is called string expression.
3. Boolean or Logical expression:
An expression which contains boolean values i.e. true or false is called Boolean expression. It can contain
arithmetic, relational as well as well as boolean or logical operators.
Escape Sequence Character:These are non graphical characters which can not be typed directly from keyboard. An
escape sequence characters are represented by backslash (\) followed by one or more characters.
Ex: \n, \t, \”,\\
Precedence of operators:An order of operators which is followed to evaluate an expression. Java follows BEDMASin
which * ,% and /, + and – have same precedence and they are evaluated from left to right.
Associativity: When more than one operator has same precedence then their associativity is checked for evaluation.
Comments: A comment is a remark to explain some aspect of the code of a program which are ignored by the compiler.
It if 3 types:
I.Single line comment: it is used make a line as comment. It is denoted by //.
II.Multiline comment: It spread over many lines. It begins with /* and ends with */.
III.Documentation comment: It is used to produce HTML file. It begins with /** and ends with */.
Data Type:To identify the type of data that a variable can hold is known as data type. Data type is classified as
follows:
I. Primitive data type: The data type which is defined by java and is not composed of any
other data type is known as primitive data type. These are also known as predefined or Intrinsic
data type. There are 8 primitive data type .
DATA TYPE SIZE(in DEFAULT RANGE
Bytes) VALUE
byte 1 0 -128 to +127
short 2 0 -32768 to +32767
int 4 0 -231 to +231-
long 8 0l or 0L -263 to +263-1
float 4 0.0F or 0.0f -3.4 E38 to + 3.4E
38
double 8 0.0d or 0.0D -1.7 E308 to + 1.7
E308
char 2 ‘\u0000’ 65536 Unicode
characters
Boolean 1byte(uses false true/false
only 1 bit)
III.Non primitive Data Type: These data types are formed with the help of primitive data types. Ex. array,
class, interfaces. This data type is also called derived or reference or user defined data type. Default value
of String is “” or null
Variable: Variable is a name of memory location to store a value,this value can be changed during the execution of
program. Syntax: datatype variablename; Ex: int x;
Initialization of variable: To provide actual value to the declared variable of same data type as needed is known as
initialization of variable. It is of two types:
Static Initialization:To initialize a variable at compile time is called static initialization.
Dynamic Initialization:To initialize a variable at run time i.e. during the execution of program is called dynamic
initialization.
int a=5; // static initialization int
b=a*a;// dynamic initialization
Scope of variable: The part of program up to which a variable can be used, is called scope of variable.
Life time of variable: The time period till which a variable lives in the memory is known is life time of variable.
Types of variable:
i) Local variable: A variable which is declared in a particular block is called local variable. It can be access in that
bock only.
ii) Instance variable: A variable or data member which is declared in class that can be access in whole class is
called Instance variable. These variables maintain different copy for different objects of a class.
iii) Static variable/Class variable: The data member or variable declared once for a class is known as static/class
variable. These variables maintain a single copy for all the objectsand all objects can share it. static keyword is
used to make a variable as class variable.
Ex: class ABC
{ int x; // instance variable
static int y; // class variable
}
i) Data value/ r value:It is data value stored at some location in the memory. This is also called r value. ii)
Location value/l value: It is the address of memory at which data value is stored. It is also called l value.
final keyword: This is used to convert variable to constant.
Example final double pi=3.14; now the value of pi can’t be updated.
Expression: An expression in java is any combination of operator, constants and variables i.e. legal combinations of
tokens.
Pure Expression An expression which contains all the operands of same type is known as Pure Expression. Mixed
Expression An expression which contains the operands areof mixed or different data types known as mixed
Expression. final Keyword: final keyword is used to make a variable as constant i.e. if we add final keyword before
a variable declaration its value can not be change during the execution of program.
finalint x=10;
x=x+5; // error
Type Conversion: When a primitive data type is converted in another data type is known as Type Conversion. It is of two
types:
i) Implicit Type Conversion: when in an expression having different data type, all data types are automatically
converted in bigger data type by compiler itself without programmer intervention, is known as Implicit Type
Conversion.It is also known as Type Promotion or Coercion.
ii) Explicit Type Conversion: When a primitive data type is converted in another data type forcefully using typecast
operator ()is known as Explicit Type Conversion. It also known as Type Casting. Ex: double x=15.8; int y=(int) x;//15 double
value is forcefully converted into int
The following syntax declares Scanner class and creates its object.
Scanner sc= new Scanner(System.in);
Here Scanner is a class, sc is an object name, System.in an InputStream.
Sequence Constructs: The sequence construct, means the statements are being executed sequentially i.e. line by line.
Selection Construct: The selection constructs means the execution of statements depending upon a condition-test.
This construct is also called decision construct or conditional construct.
Iteration Construct: The iteration construct means repetition of a set of statements depending upon a condition test.
Conditional Constructs are of following types:
i) if: This statement is used to check one or more than one condition. If condition is true then set of statements
inside the block of ‘if’ will execute otherwise not. Syntax:
if(condition)
{
Statements;
}
ii) if-else: If condition is true then set of statements inside the block of ‘if’ will execute otherwise statements
inside the block of ‘else’ will execute.
Syntax:
if(condition)
{
Statements;
}
else
{
Statements;
}
iii) Nested if-else (if-elseif): It is also called ladder if-else. It is used to check a series of condition where only
one condition executes and if all the condition are false then the last ‘else’ statement executes. Syntax:
if(condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
----------
----------
else
statementN;
iv) Nested if: Presence of ‘if’ or more ‘if’ statements inside one
‘if’ statement is known as nested-if statement. Syntax:
if(condition)
{
if(condition)
{
Statements;
}
}
Dangling else problem: In the nested if-else , the number of ‘if’ statements are more than the number of
‘else’ statements then an ambiguous situation arises which is known as dangling else problem.
Example: if(a>b)
If(a>c)
System.out.println(a);
else
System.out.println(b);
In this example there is a confusion that given ‘else’ is related with which ‘if’.
To overcome this problem curly braces {} are used.
switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Some Important rules for switch statements:
• Expression can be of type byte, short, int or char. Beginning with JDK7, expression can also be of type
String.
• Duplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the next case.
Example:
class SwitchCaseDemo
{
public static void main(String args[])
{ int i = 9;
switch (i)
{ case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Output:
i is greater than 2.
break Statement in switch case
break statement is used to control the flow of the execution. The break statement can be used as the last
statement in each case statement list. When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no
break appears, the flow of control will fall through to subsequent cases until a break is reached.
switch(grade) {
case 'A’:
System.out.println("Excellent!");
break;
case 'B’:
case 'C’:
System.out.println("Well done");
case 'D’:
System.out.println("You passed");
break;
case 'F’:
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade"); }
System.out.println("Your grade is " + grade);
} }
Output:
Well done
You passed
Your grade is C
default case:
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can
be used for performing a task when none of the cases is true. No break is needed in the default case.
Compound statement or Block Statement: A Sequence of statements grouped together within a pair of curly braces { }
is called compound statement. Eg: { x = 1; y = 0; }
• for Loop: A ‘for’ loop is used when number of iterations is fixed and known. It is a fixed or known looping
construct.
Syntax
Example :
int i;
for ( i= 0 : i< 5 ; i++)
{
System . out .println ( "Hello !" ) ;
}
• while loop: A ‘while’ loop is used when number of iterations is unfixed or unknown. In this looping construct, a
block of statements gets executed repeatedly unless the given condition is false. It is a unfixed or unknown
looping construct.
Syntax
initialisation
while(condition)
Statement(s)
updation;
}
Example while loop
int i= 0 ;
while ( i< 5)
{
System .out .println (i);
i++ ;
}
Exit Controlled Loop: A Looping construct in which the condition is checked at the end of the body of the loop. Since
the test-condition is not evaluated until the end of the loop, the body of an exit-controlled loop is always executed at
least once.
• do-while: do-while is an exit-controlled loop that repeats a statement or a block of statements until its
test condition remains true.
Syntax
initialisation
do
{
Statement(s)
updation; } while(condition);
int i = 20 ;
do
{
System . out . println ( i) ;
i ++ ;
}
while ( i < 10 ) ;
This includes the missing pieces of the loop definition. An interesting trait of the for loop is that pieces of the
loop definition need not be there.
For example,
for (x=0; x!=456; )
System.out.println(x);
Here, when each time the loop repeats, x is tested to check if it equals 456. The loop conditions become false
and terminates the loop, when 456 is entered.
3. Infinite loop :
This includes the infinite loop. If all of the pieces in the loop definition are missing, an infinite loop is created or
there is incorrect condition or incorrect updation. The break statement is used to break out of the loop, as in
an example given below −
for(;;){
if(ch == 'A')
break;
}
4. Empty loop or Time Delay loop:
A loop that contains no statements is called empty loop.
Example:
b) int i;
for ( i=10; i<=100 ;i++); c) int i=1;
{ do
System.out.println(i); {
} }
while (++i<=50);
Jump Statements: Java has three types of jumping statements they are break, continue, and
return. These statements transfer execution control to another part of the program.
i. break: In Java,break statement is used for termination of the loop in which it get executed
Example:
Example:
ii. return statement:- This jump statement is used to terminate the function in which it get
executed and also it returns a value to function calling statement.
MATH CLASS AND ITS FUNCTIONS
Math class is pre-defined inside java.lang(default package) and all itsfunctions given
below are static. These functions are used for performing mathematical operations in java.
4. Math.abs(x) same as Calculate the absolute or positive value of int x=-84; int r=Math.abs(x);
paramet given parameter=|x| r=84; int a=90; int
er r2=Math.abs(a); r2=90;(If
the value is already positive
then no change
5. Math.min(x,y) same as Finds the smallest value between the 2 int x=4,y=6; int
paramet parameters i.e. x and y r=Math.min(x,y);
ers r=4;
6. Math.max(x,y) same as Finds the largest value between the int x=4,y=6; int
paramet 2 parameters i.e. x and y r=Math.max(x,y);
ers r=6;
Math.ceil(x) double Gives the nearest larger value of the double x=14.8,y=16.5;
parameter(after making decimal as 0) doubler=Math.ceil(x); r=15.0;
double r=Math.ceil(y);
r=17.0;
9. Math.round(x) int Gives the rounded off value (sme as in doublex=14.5,y=16.43; int
mathematics) r=Math.round(x); r=15;
If decimal part is less than 5 then intr=Math.round(y);
smaller value otherwise the nearest r=16;
largest value
10. Math.rint(x) double Gives the rounded off value (sme as in double
mathematics) x=14.5,y=16.43,z=18.98;
If decimal part is less than 5 then doubler=Math.rint(x); r=14.0;
smaller value and if greater than 5 then doubler=Math.rint(y); r=16.0;
gives the nearest largest value doubler=Math.rint(z); r=19.0;
12. Math.random() double This function returns any random double r=Math.random();
value between [0 -1) where 0 is r=any value between 0 to 1 in
inclusive and 1 is exclusive i.e. double
value>=0 and value<1