Summarize Java Notes
Summarize Java Notes
Computer programming is the act of writing computer programs, which is a sequence of instructions
written using a Computer Programming Language to perform a specified task by the computer.
1. Go straight
2. Drive half kilometer
3. Take left
4. Drive around one kilometer
5. Search for KFC at your right side
Just like we above did, in computers, we write a set of instructions written using a Computer
Language to perform a specified task by the computer known as a sequence of instructions.
For example to add two numbers and display their sum we need to write the following sequence of
instructions:
a=10
b=20
c=a+b
print(c)
The above program will give result 30 after executing the above sequence of instructions.
Does not support any principle Supports various principles such as encapsulation,
abstraction, inheritance, polymorphism.
Object
1. It is a real-world tangible entity that has some state and behavior.
2. It is also known as an instance of a class.
3. It exists in the real world.
4. It is made using a class.
5. Every object must belong to at least one class.
6. It contains attributes,state and behavior.
7. Objects communicate with each other via messages.
Attribute (variables) – It refers to the data members of a class that will store the state(values) of an
object.
State (Values stored in the variables) – It refers to the set of values stored in the data members of
a class.
Behavior (methods) – It refers to the activities or processes which the object can perform.
How to define a class in Java? How to create an object in java?
1. Stand Alone Java Application – Those programs that run on itself on a machine without internet
are called Stand Alone Java Application.
a. CUI (Character User Interface) – These programs accept input in texts as well as give output
in text only.
b. GUI (Graphical User Interface) – These programs contain graphical elements such as
textboxes, labels, buttons, icons, dropdown menu, pop up menu.
2. Java Applets - These programs run in a java enabled web browser along with html code within a
website. They need a java enabled web browser along with the internet.
Language translators
It is a program that converts programs written in one language into another language. It is of three
types:
It converts complete code at a It converts one line at a time or It converts complete code at a
time. we can say it works line by line. time.
Java Compilation Process
Java uses both compiler and interpreter to convert source code written in java language into machine
code. By using this compilation process, java becomes a platform independent language which
means programs written on one machine can be run on different machines.
Source Code - Code or program written in High Level Language such as Java
Byte Code - Intermediate code generated by the java compiler.
Machine Code - Code in machine language which is understandable by the cpu
Java Compiler - It converts Source Code(written in Java Language) into Byte Code
JVM - It converts Bytecode into machine code
Full Forms
JVM - Java Virtual Machine JDK - Java Development Kit
JIT - Just In Time Compiler JRE - Java Runtime Environment
WORA - Write Once Run Anywhere
________________________________________________________________________________
Chapter 4 Values and Datatypes
Character Set
A set of characters recognized by a language is known as a Character Set.
1. ASCII (American Standard Code for Information Interchange) – Contains only English
language characters. It takes 7 bits in memory. It includes 128 characters.
2. Extended ASCII – Contains only English language characters. It takes 8 bits in memory. It
includes 256 characters.
3. UNICODE(Universal Coded Character Set) – It contains the characters of all the world's
languages. It takes 2 bytes in memory. It includes 65536 characters. Java supports Unicode
character set.
ASCII Codes
ASCII Values of Uppercase Letters:
A - 65 B - 66 C - 67 D - 68 E - 69 F - 70 G - 71 H - 72 I - 73 J - 74 K - 75 L - 76 M - 77
N - 78 O - 79 P - 80 Q - 81 R - 82 S - 83 T - 84 U - 85 V - 86 W - 87 X - 88 Y - 89 Z - 90
Escape Sequence
Characters followed by a backslash(\) that has special meaning to the language compiler are known
as Escape Sequence.
Identifiers
These are the names given to the different components in a program such as variables, constants,
classes, objects, etc.
Rules for making identifiers
1. A java is a case sensitive language in which a and A are treated individually.
2. They cannot start with a digit. Ex. a4 is valid and 4a is invalid.
3. Any special symbol cannot be used in an identifier except _ and $.
4. Reserved words can not be used to make an identifier.
Keywords
These are the reserved words that have special meaning to the java compiler and cannot be used as
an identifier or literal. All the keywords remain in lowercase.
Literals
A set of characters that represent a value which can be stored in a variable is called literal. Ex. 345
In java, it is of 8 types:
Punctuators
These are the symbols used for grouping and separating the code in a program.
Grouping – (), {}, [], ‘’, “” Separating – , : ;
Note - semicolon(;) is also known as statement terminator as it is used to end the statement.
Operators
These are the symbols that represent an operation which can be
performed on operands by CPU.
Operands : These are the values on which operations are performed.
Data Type
A datatype is a classification that specifies
● which type of value a variable can store.
● which set of operations can be performed on it
● how much space it will require to store in memory
Variables
A variable is a named and reserved location in memory
where values are stored. It means that when you
create a variable, you reserve some space in the
memory. For example-
int a; //variable declaration-command given to the cpu
to create a variable in memory(RAM)
a=10; //variable initialisation-giving initial value to the
variable
Constants
A constant is a named and reserved location in memory
where values are stored. Unlike variables, their value
can not be changed once initialized. For example-
final int a; //constant declaration-command given
to the cpu to create a constant in memory(RAM)
a=10; //constant initialisation-giving initial value
to the constant
a=20; //updating constant will raise an error
Note : final keyword is used to make constants in java
Initialization
The process of giving initial value to the variable or constant is called initialization. It is of two types:
When a variable is assigned a value at compile When a variable is assigned a value at run time
time i.e before the execution of a program, it is i.e during the execution of a program, it is called
called static initialization. dynamic initialization. For example,
For example,
a=sc.nextInt(); or a=b+c;
a=10;
Comments
Those lines in a program which are ignored by the java compiler and not treated as a program
instruction are known as comments. They are used to give information about the program code in a
program. It is of 3 types in java:
Types of Operators
1. Arithmetic 3. Logical 5. Increment / Decrement
2. Relational 4. Assignment 6. Conditional
Arithmetic Operators
An arithmetic operator takes two operands and performs a calculation on them and results in some
numeric i.e integer or floating point values.
Operator Operator name Operation Result Examples
+ Plus Addition Sum 5+6 11 2+4 6
- Minus Subtraction Difference 10-4 6 14-5 9
* Asterisk Multiplication Product 5*3 15 9*3 27
25/5 5 27/5 5
/ Forward Slash Division Quotient 27.0/5 5.4 27/5.0 5.4
5/27 0 5/25.0 0.2
% Modulus Division Remainder 27%5 2 5%27 5
Relational Operators
They require two operands to perform a comparison on them. They result in boolean values i.e True
or False.
Operator Operator Name Operation Examples
< less than Check if left operand is less than the 4<5 true 5<4 false -10<-5 true
right operand
> greater than Check if left operand is greater than 5>4 true 4>5 false -8>-10 true
the right operand
<= less than or equal to Check if left operand is less than or 4<=5 true 5<=5 true 6<=5 false
equal to the right operand
>= greater than or equal to Check if left operand is greater than 5>=4 true 5>=5 true 5>=6 false
or equal to the right operand
== equal to Check if left operand is equal to the 5==5 true 4==5 false -5==-5 true
right operand
!= not equal to Check if left operand is not equal to 4!=5 true 5!=5 false -4!=-5 true
the right operand
Logical Operators
A logical operator takes boolean operands and performs a logical operation on them and results in
boolean values i.e true or false.
Operator Operator Name Operation Examples
4<3 && 3>4 false
Logical AND 4<3 && 4>3 false
&& Results in true when both operands are true
(&-Ampersand) 3<4 && 3>4 false
3<4 && 4>3 true
4<3 || 3>4 false
Logical OR 4<3 || 4>3 true
|| Results in true when any of the operand is true
(| - Pipe) 3<4 || 3>4 true
3<4 || 4>3 true
Logical NOT ! 3<4 false
! It inverts the result of an expression
(Exclamatory) ! 3>4 true
Assignment Operators
These operators are used to assign values to the variables. Except =, all the assignment operators
are also known as shorthand operators.
Conditional Operator
It is a ternary operator that tests a condition and assigns a value to the variables accordingly.
Syntax:
Variable name=Test Condition?Value if true:Value if false;
Examples:
int a=10,b=20; int a=10,b=20,c=30; boolean c=true;
int c = a>b ? a : b; int d = a>b && a>c ? a : b>c?b:c; int d=c?a:b;
Dot(.) Operator
It is also known as member of operator because it is used to access the members of a class or
packages.
Ex. System.out.println(); import java.util.Scanner; int a=sc.nextInt();
New Operator
It is a keyword used to dynamically(run time) allocate memory for an object and an array. Also we can
say, the new keyword is to create an object/instance of a class.
Syntax:
ClassName objectname = new ClassName();
Example:
Scanner sc=new Scanner(); //Object Creation
Precedence of Operator
It refers to the order in which operators operate on operands in an expression like the BODMAS rule.
1. Brackets ( ),[ ],{ }
2. Increment/Decrement(++,--)
3. Not operator(!)
4. Division/Multiplication(%,/,*)
5. Addition/Subtraction(+,-)
6. Relational Operator(<,>,<=,>=,==,!=)
7. Logical Operator(&&,||)
8. Conditional Operator(?:)
9. Assignment(=,+=,-=,*=,/=,%=)
Expressions
An expression is a combination of constants, variables, operators and method calls which evaluates
to a single value termed as result.
Types of Expressions
Arithmetic Expression
An expression which contains arithmetic operators only is called arithmetic expressions.
Integer Expression
An arithmetic expression which evaluates to an integer result is called integer expression.
System.out.println(10+20); //30
Real Expression
An arithmetic expression which evaluates to a real result i.e decimal value is called real
expression.
System.out.println(10+20.54); //30.54
System.out.println(10.26+20.32); //30.58
Boolean Expression
An expression which evaluates to a boolean result i.e true or false are called boolean expressions.
System.out.println(10<20); //true System.out.println(10>20); //false
System.out.println(true && false); //false System.out.println(10<20 && 20>10); //true
String Expression
An expression which contains string operators only is called string expressions. They evaluate to a
string result.
Assignment Expression
An expression in which the result is assigned to some variable is called assignment expression.
c=a+b;
Type Conversion
The process of conversion of data type of a value from one to other is known as type conversion. It is
of two types:
These conversions are always performed from These conversions can be performed from larger
smaller size data type to larger size datatype. size data type to smaller size datatype.
import java.util.Scanner;
OR
import java.util.*; * => All
Now, To use the methods of the Scanner class, we first need to create the object of the class. For that
purpose, following statement is used:
Errors
These are the mistakes in a program that prevents it from its normal working.
These are also known as bugs and the process of finding and removing these bugs is known as
debugging. It is of three types:
1. Syntax Errors 2. Runtime Errors 3. Logical Error
Syntax Errors
The errors that occur due to incorrect syntax followed to make a program are called Syntax Errors.
These errors occur during the compilation of a program, so they are also called Compile Time
Errors. For ex:
1. Missing semicolon after a statement 5. Incorrect literal
2. Missing brackets 6. Incorrect use of operator
3. Incorrect spelling of keywords 7. Incorrect punctuators
4. Invalid Identifiers 8. Incompatible assignments
Syntax: It refers to the arrangement of tokens in a program to create well formed statements.
Logical Error
It occurs when the program compiles and runs without errors but produces an incorrect result. This
type of error is caused by a mistake in the program logic which is often due to human error.
For example,
1. To get the sum of two numbers, - operator is used.
2. Not getting a desired pattern but getting another pattern.
Runtime Error
Errors which occur during the execution of a program are known as runtime errors. These errors
cause the program execution to end at a point where error occurs. These are also known as
exceptions and the process of handling these errors is called exception handling. For example,
1. Dividing a number by 0.[DivideByZeroException]
2. Accessing an index in an array which does not exist. [ArrayIndexOutOfBoundException]
3. Not inputting a desired type of value[InputMismatchException]
________________________________________________________________________________
Chapter 7 Mathematical Library Methods
Math is a library class defined java.lang package which contains various predefined static methods
to perform various mathematical operations.
1. pow() - It returns the power of the given arguments
Return type - double
Ex. Math.pow(2,5) - 32.0
System.out.println(Math.pow(2,5)); //2*2*2*2*2 => 32.0
System.out.println(Math.pow(-2,5)); //-2*-2*-2*-2*-2 => -32.0
System.out.println(Math.pow(-2,6)); //-2*-2*-2*-2*-2*-2 => 64.0
System.out.println(Math.pow(2,-2)); //1/(2*2) => 1/4 => 0.25
System.out.println(Math.pow(25,0.5)); //square root of 25 => 5.0
System.out.println(Math.pow(25,1/2)); //Power 0 of 25 => 1.0
System.out.println(Math.pow(125,1/3)); //Power 0 of 125 => 1.0
System.out.println(Math.pow(25,1/2.0)); //square root of 25 => 5.0
System.out.println(Math.pow(125,1/3.0));//cube root of 125 => 5.0
2. sqrt() - It returns the square root of a given number
Return type - double
Math.sqrt(25) => 5.0 Math.sqrt(-25) => NaN
3. cbrt() - It returns the cube root of a given number
Return type - double
Math.cbrt(125) => 5.0 Math.cbrt(-125) => -5. 0
4. min() - It returns the minimum tvalue between two arguments.
Return type - same as argument
Math.min(3,4) => 3 Math.min(3.5, 5) => 3.5 Math.min(3, 4.5) => 3.0
5. max() - It returns the maximum value between two operands.
Return type - same as argument
Math.max(3,4) => 4 Math.max(3, 4.5) => 4.5 Math.max(3.5, 4) => 4.0
6. abs() - It returns the absolute value of the given argument or we can say it converts the
argument into the positive number and returns it.
Return type - same as argument
Math.abs(-5) => 5 Math.abs(5) => 5 Math.abs(-5.4) => 5.4
7. round() - It returns the rounded value of the given argument.
Return type - Integer if argument is float, Long if argument is double
Math.round(5.4) -> 5 Math.round(5.5) -> 6
Math.round(-5.4) -> -5 Math.round(-5.5) -> -6
8. rint() - It returns the rounded value of the given argument. In case _.5, it rounds to the
nearest even integer.
Return type - double
Math.rint(5.45) -> 5.0 Math.rint(5.5) -> 6.0 Math.rint(6.5) -> 6.0
Math.rint(-5.45) -> -5.0 Math.rint(-5.5) -> -6.0 Math.rint(-6.5) -> -6.0
9. floor() - It returns the floor value(nearest smaller integer value) of the given argument.
Moves left side on the number scale.
Return type - double
Math.floor(5.1) -> 5. 0 Math.floor(5.9) -> 5.0
Math.floor(-5.1) -> -6.0 Math.floor(-5.9) -> -6.0
10.ceil() - It returns the ceil value(nearest greater integer value) of the given argument.
Moves right side on the number scale.
Return type - double
Math.ceil(5.1) -> 6.0 Math.ceil(5.9) -> 6.0
Math.ceil(-5.1) -> -5 Math.ceil(-5.9) -> -5
11.random() - It returns the random number between 0.0 and 1.0.
Return type - double
Ex. Math.random() - 0.4947807115137014
12.PI - It gives the value of PI
Return type - double
Ex. Math.PI -> 3.141592653589793
________________________________________________________________________________
Chapter 8 Statements in Java
Statements
These are the instructions in a program that instructs the cpu to perform a certain task. These
statements are terminated by a symbol semicolon(;) which is also known as a statement terminator. It
is of 5 types:
1. Sequential 2. Conditional 3. Unconditional 4. Looping 5. Jump
Sequential Statement
Those statements which execute in a defined sequence i.e one after another are called sequential
statements. It is of two types: Simple and Compound
IF
It is a conditional statement that tests a condition and executes the statement or a block of
statements written after it if the condition is true.
Syntax: Example:
if(condition) if(age>=18)
{ {
Statements will execute if the condition is true System.out.println(“You can vote”);
} }
IF ELSE
It is a conditional statement that tests a condition and executes the statement or a block of
statements written after it if the condition is true otherwise execute the statements written under the
else block.
Syntax: Example:
if(condition) if(age>=18)
{ {
Statements which will execute if the condition is true System.out.println(“You can vote”);
} }
else else
{ {
Statements which will execute if the condition is false System.out.println(“You can not vote”);
} }
IF ELSE Ladder
It is a conditional statement that tests a condition and executes the statement or a block of
statements written after it if the condition is true, otherwise tests the next condition and executes the
statements written after it otherwise moves to the next condition and so on.
Nested IF
It is a conditional statement that tests a condition, enters in the body and checks another condition
and so on.
If within another if is known as nested if.
Syntax:
if(condition1)
{
Statements which will execute if the condition1 is true
if(condition2)
{
Statements which will execute if the condition 2 is true
if(condition3)
{
Statements which will execute if the condition 3 is true
}
else
{
Statements which will execute if the condition 3 is false
}
}
else
{
Statements which will execute if the condition 2 is false
}
}
else
{
Statements which will execute if the condition 1 is false
}
Question: Write a program to accept three angles of a triangle and check whether a triangle is
possible or not. If possible then display whether it is an Acute Angled Triangle, an Obtuse
Angled Triangle or a Right Angled Triangle otherwise, display “Triangle is not possible”.
Sample Input:
Enter the first angle of a triangle:40
Enter the second angle of a triangle:110
Enter the third angle of a triangle:30
Sample Output:
The triangle is possible and it is An Obtuse-Angled Triangle
import java.util.Scanner;
class Triangle
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the first angle of a triangle:");
int a = sc.nextInt();
System.out.print("Enter the second angle of a triangle:");
int b = sc.nextInt();
System.out.print("Enter the third angle of a triangle:");
int c = sc.nextInt();
if(a+b+c==180 && a>0 && b>0 && c>0)
{
System.out.println("Triangle is possible");
if(a<90 &&b<90 &&c<90)
System.out.println("It is an acute angled triangle");
else if(a>90||b>90||c>90)
System.out.println("It is an obtuse angled triangle");
else if(a==90||b==90||c==90)
System.out.println("It is an right angled triangle");
}
else
System.out.println("Triangle is not possible");
}
________________________________________________________________________________
Chapter 10 - Unconditional Statements in Java
Unconditional Statement
These statements test for the equality of given choice with the available choices and executes a
statement or a block of statements accordingly. There is one conditional statements in java:
Switch
It for the equality of given choice with the available choices and executes a statement or a block of
statements accordingly.
Note:break and default is optional whereas case is mandatory in switch.
Syntax: Example:Display Equivalent Week Day Name
Write a program to check whether a character is a vowel or not using switch(fall through).
import java.util.Scanner;
class Vowel
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the character:");
char ch = sc.next().charAt(0);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':System.out.println("It is a vowel");
break;
default:System.out.println("It is not a vowel");
}
}
}
Write a program to check whether a character is a vowel or not using if else.
import java.util.Scanner;
class Vowel
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the character:");
char ch = sc.next().charAt(0);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'||ch=='a'||ch=='e'||ch=='i'||
ch=='o'||ch=='u')
System.out.println("It is a vowel");
else
System.out.println("It is not a vowel");
}
}
switch(a) if(a==1)
{ System.out.println(“Red”);
case 1:System.out.println(“Red”); else if(a==2||a==3)
break; System.out.println(“Blue”);
case 2: else
case 3:System.out.println(“Blue”); System.out.println(“Yellow”);
break;
default:System.out.println(“Yellow”);
}
Chapter 11 - Looping Statements in Java
Looping Statement
These statements are used to execute a statement or a block of statements repeatedly. It is of two
types:
Entry Controlled Loop Exit Controlled Loop
These loops test a condition at the entry point of These loops test a condition at the exit point of
the loop. the loop.
This loop will not execute even once if the This loop will execute at least once even if the
condition is false in the first iteration. condition is false in the first iteration.
Syntax: Example:
do int i=1;
{ do
statement(s); {
} System.out.println(“Vikas”);
while(test-condition); i++;
Note: Here do and while are keywords }
while(i<=10); i=1,2…..10
Empty Loop
A loop which does not contain a loop body is called empty loop. For example,
1. for(int i=1;i<=10;i++); 3. while(i<=10);
2. for(int i=1;i<=10;i++){} 4. while(i<=10) { }
Infinite Loop
A loop which executes infinite times i.e keeps on executing is called infinite loop. For example,
1. for(;;) 2. while(true) 3. do
Statement(s) { {
Statement(s) Statement(s)
} }
while(true);
Jump Statements
These statements are used to transfer the program control from one point to another in a program.
There are three jump statements supported in java.
1. Break 2. Continue 3. Return
Break
It is a keyword used to take the program control out of the construct. For example,
for(int i=1;i<=10;i++) 1
{ 2
if(i==5) 3
break; 4
System.out.println(i);
}
Continue
It is a keyword used to transfer the program control to the next iteration by skipping the current
iteration. For example,
for(int i=1;i<=10;i++) 1
{ 3
if(i%2==0) 5
continue; 7
System.out.println(i); 9
}
Return
It is a keyword used to transfer the program control from called method to the calling method.
We can also use it to terminate the execution of a method.
System.exit(0)
This method is used to terminate the execution of a program.
________________________________________________________________________________
Chapter 12 Methods in Java
Methods
A method is a named block of statements that can be called and executed anywhere and any number
of times in a program.
class Factorial
{ 1.int -> return type
int factorial(int n) =>called method
2.factorial -> method name or identifier
{
int f=1; 3.int n -> parameters(formal)
for(int i=1;i<=n;i++)
f*=i; 4.{} -> Method body
return f; 5.return f -> return statement
} (return -> keyword, f -> variable name)
public static void main(String ar[]) //calling method
{ 6.Factorial f=new Factorial() =>
Factorial f=new Factorial(); Object creation (Factorial->class name,
int a=5; f->object name, new -> keyword)
System.out.println(f.factorial(4));
7.f.factorial(4) => method call statement
System.out.println(f.factorial(a));
} 8.4 or 5 => actual parameter or argument
}
Method Header or Prototype:The first line of a method definition in which return type, method name,
and list of parameters are defined is called method header or prototype.
Method Signature:The list of formal parameters defined in method header or prototype which
includes number of parameters and type of each parameter is called method signature.
Return Type:It determines the type of value which will return after execution and if any method does
not return any value, then void is used.
Method Definition or Body:It refers to the block of statements in which statements are written to
perform certain tasks just below the method header or prototype.
Return Statement:It refers to the line of a method with return keyword and is used to return a value
or to terminate the method execution.
Method Call:It refers to the statement where the method is called to execute its code and to perform
a certain task.
Some more examples of method based program
Write a program to define a method that accepts Write a program to define a method that
a number and check whether it is a prime or not. accepts a number and displays its table.
Parameters
It refers to the variables or values written in a method header/prototype or a method call statement.
Types of Parameters
Formal Parameters Actual Parameters
Those variables which are defined in a method Those variables or values(literals) which are
header or method prototype are called formal defined in a method call are called actual
parameters. parameters.
They receive values from actual parameters. Their values are copied to the formal parameters.
Types of Methods
It is of two types:
1. Pre defined Methods or Library Methods or Built-in Methods - Those methods which are
pre defined in a language are known as Predefined methods.
2. User defined Methods - Those methods which are defined by the programmer are called user
defined methods.
Types of Methods(On the basis of calling)
Static methods Non static methods
They are also known as class methods They are also known as instance methods
They are defined with static keyword They are defined without using static keyword
They can be called without creating the object of They need an object to call.
a class
They can be called with the help of class name They are called with the help of object name
as well as object name.
They load in memory when the class is They load in memory when the object of its class
compiled. is made.
These methods can access static members only. These methods can access static members as
well as non-static members.
Sample Program
class Method
{
static void display()
{
System.out.println("This is a static method");
}
void show()
{
System.out.println("This is a non-static method");
}
public static void main()
{
display();
Method.display();
Method m=new Method();
m.display();
m.show();
}
}
Sample Output: This is a static method
This is a static method
This is a static method
This is a non-static method
Types of methods(On the basis of updation)
Pure Methods Impure Methods
They do not change the state(values stored in These methods change the state of an object.
the data members of a class) of an object.
Any changes in formal parameters do not reflect Changes in formal parameters do reflect in actual
in actual parameters. parameters.
Method Overloading
When a class contains more than one method having the same name but different signature, it is
called method overloading and these methods are called overloaded methods. For example,
Design a class to overload a method area that can calculate the area of square, circle,
rectangle and triangle.
public class Overload OUTPUT:
{ Area of square:25
int area(int s) Area of circle:95.03317777109123
{ Area of rectangle:20
return s*s; Area of triangle:6.0
}
double area(double r)
{
return Math.PI*r*r;
}
int area(int l,int b)
{
return l*b;
}
double area(int a,int b,int c)
{
double s=(a+b+c)/2.0;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public static void main(String[] args)
{
Overload o=new Overload();
System.out.println("Area of square:"+o.area(5));
System.out.println("Area of circle:"+o.area(5.5));
System.out.println("Area of rectangle:"+o.area(4,5));
System.out.println("Area of triangle:"+o.area(3,4,5));
}
}
this keyword
This keyword is used to refer to the members of the current object.
It is used to differentiate between local members and instance members in a method.
________________________________________________________________________________
Chapter 13 Constructors
Constructor
● A constructor is a method that has the same name as its class has.
● It does not return any value so there is no return type in it.
● It is automatically called when the object of the class is created.
● They are called constructors because they are responsible for the construction of objects.
● If we do not create a constructor for a class then java compiler itself provides a default constructor
which initializes all the data members of a class with their default values depending on their data
types.
They can be called without creating the object of Object creation is a must to call the constructors.
a class.
________________________________________________________________________________
Chapter 14 Arrays
An array is a data structure in which elements are stored. Previously, we have stored values in
variables but there are some limitations with them.
Arrays
An array is a collection of elements of the same data type stored at a contiguous memory location
under a common identifier. It is of two types:
1. Single Dimensional Array 2. Multi-Dimensional Array
Subscript - The index number through which every element of an array is accessed is known as
subscript.
int ar[]={10,20,30,40,50};
System.out.println(ar[2]); //30
int ar[]={{10,20,30,40},{50,60,70,80},{90,100,110,120}};
System.out.println(ar[2][1]); //100
Subscripted variable - The name of an array with which we must specify the index number to fetch
any element of an array is called subscripted variable.
int ar[]={10,20,30,40,50};
It is of two types:
1. Single subscripted variable - The name of a single dimensional array is called single
subscripted variable because we need to specify only a single index number to fetch any
element with the subscripted variable.
int ar[]={10,20,30,40,50};
2. Double subscripted variable - The name of a double dimensional array is called a double
subscripted variable because we need to specify two index numbers(row index and column
index) to fetch any element with the subscripted variable.
int ar[][]={{10,20,30,40},{50,60,70,80},{90,100,110,120}};
Searching - The process of finding an element in an array is called searching. It can be performed
using two techniques:
1. Linear Search - In this technique, a key element is compared with every element of an array
starting from 0 index and this process continues until the element found.
2. Binary Search - In this technique, an array is divided into two halves and then the existence of
an element is checked by further dividing these halves into two halves.
Sorting - The process of arranging up of array elements in ascending or descending order is known
as sorting. It can be performed using various techniques, some of those are:
1. Selection Sort
2. Bubble Sort
Double Dimensional Array
An array in which elements are stored along rows and columns and each element of an array can be accessed
via two index numbers one is row index and the other is column index.
It can be made in two ways:
Code to Display the Array Elements Code to accept elements through user input
for(int i=0;i<arr.length;i++) for(int i=0;i<arr.length;i++)
for(int j=0;j<arr[0].length;j++) for(int j=0;j<arr[0].length;j++)
System.out.println(arr[i][j]); arr[i][j]=sc.nextInt();
________________________________________________________________________________
Chapter 15 Strings
String
● A string is a group of characters enclosed within double quotes.
● Traditionally, we store multiple characters in character arrays.
● In java, to handle these character arrays string class is provided which contains various
predefined methods to perform various operations on strings.
● String in java is immutable.
System.out.println(s1==s2); //false
System.out.println(s1==s3); //false
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//false
It is used to compare the reference of two It is used to compare two strings whether they contain
strings. the same characters in the same case or not.
String Methods
1. length() - This method is used to get the length of string i.e number of characters in it.
Argument type - No argument
Return type - int
String s=”Hello World”;
System.out.println(s.length()); //11
System.out.println("watch".length()); //5
It is used to get the length of an array. It is used to get the length of strings.
2. charAt() - This method returns the character at a given index in a string.
Argument type - int
Return type - char
String s=”Hello World”;
System.out.println(s.charAt(4)); //o
System.out.println(s.charAt(40)); //Error:StringIndexOutOfBound Exception
3. indexOf() - This method returns the index number of first occurence of a given character or string.
Argument type - char, char-int , string , string-int
Return type - int
String s=”Hello World”;
System.out.println(s.indexOf(‘o’)); //4
System.out.println(s.indexOf(‘ ’)); //5
System.out.println(“malayalam”.indexOf(‘a’)); //1
System.out.println(s.indexOf(‘x’)); //-1
System.out.println(s.indexOf(‘o’,5)); //7
System.out.println(“My name is Vivek”.indexOf(“is”)); //8
System.out.println(“My name is Saksham”.indexOf(“am”)); //4
System.out.println(“My name is Saksham”.indexOf(“am”,5)); //16
4. lastIndexOf() - This method returns the index number of last occurence of a given character or
string.
Argument type - char, char-int , string , string-int
Return type - int
String s=”Hello World”;
System.out.println(s.lastIndexOf(‘o’)); //7
System.out.println(“malayalam”.lastIndexOf(‘a’)); //7
System.out.println(s.lastIndexOf(‘ ’)); //5
System.out.println(s.lastIndexOf(‘x’)); //-1
System.out.println(s.lastIndexOf(‘o’,6)); //4
System.out.println(“My name is Vivek”.lastIndexOf(“is”)); //8
System.out.println(“My name is Saksham”.lastIndexOf(“am”)); //16
System.out.println(“My name is Saksham”.lastIndexOf(“am”,15)); //4
5. toUpperCase() - This method returns a new string after converting the case of all the letters to
uppercase.
Argument type - no arguments
Return type - string
String s=”Hello World@123”;
String y=s.toUpperCase();
System.out.println(y); //HELLO WORLD@123
System.out.println(“Watch”.toUpperCase()); //WATCH
6. toLowerCase() - This method returns a new string after converting the case of all the letters to
lowercase.
Argument type - no arguments
Return type - string
String s=”Hello World@123”;
String y=s.toLowerCase();
System.out.println(y); //hello world@123
System.out.println(“Watch”.toLowerCase()); //watch
7. equals() - This method is used to test the equality of two strings i.e whether they are the same are
not. It performs case sensitive comparison.
Argument type - string
Return type - boolean
String s=”Hello”;
String t=”Hello”;
String u=”hello”;
String v=”World”;
System.out.println(s.equals(t)); //true
System.out.println(t.equals(s)); //true
System.out.println(t.equals(u)); //false
System.out.println(u.equals(v)); //false
8. equalsIgnoreCase() - This method is used to test the equality of two strings i.e whether they are
the same or not irrespective of their cases. It performs case insensitive comparison.
Argument type - string
Return type - boolean
String s=”Hello”;
String t=”Hello”;
String u=”hello”;
String v=”World”;
System.out.println(s.equalsIgnoreCase(t)); //true
System.out.println(t.equalsIgnoreCase(u)); //true
System.out.println(s.equalsIgnoreCase(v)); //false
9. compareTo() - This method is used to determine the difference of two strings. It returns the
difference of ascii values of two different characters in both strings at respective indexes.
Argument type - string
Return type - int
A - 65 a - 97
B - 66 b - 98
. .
. .
. .
Z - 90 z - 122
String s=”abcde”;
String t=”abcde”;
String u=”abcx”;
String v=”aBcde”;
String w=”abcdefgh”
System.out.println(s.compareTo(t)); //0 (if both strings are exactly same)
System.out.println(s.compareTo(u));
//100(d) - 120(x)=-20(-ve result if string 1 is smaller than string 2)
System.out.println(u.compareTo(s));
//120(x) - 100(d)=20(+ve result if string 1 is greater than string 2)
System.out.println(s.compareTo(v)); //98(b) - 66(B)=32
Difference of lengths will be returned if the one string occurs in the beginning of second
string
System.out.println(s.compareTo(w)); //5-8=-3
System.out.println(w.compareTo(s)); //8-5=3
System.out.println(“abcde”.compareTo(“abcDefgh”));//100(d)-68(D)=32
System.out.println(“abcde”.compareTo(“wxyz”));//97(a)-119(w)=-22
System.out.println(“abcde”.compareTo(“Wxyz”));//97(a)-87(W)=10
10.compareToIgnoreCase() - This method is used to determine the difference of two strings in
lexicographical order(alphabetical order).
Argument type - string
Return type - int
A - 1 a - 1 0 - 48
B - 2 b - 2 1 - 49
. .
. .
. .
Z - 26 z - 26 9 - 57
String s=”abcde”;
String t=”abcde”;
String u=”abcx”;
String v=”aBcde”;
String w=”abcdefgh”
System.out.println(s.compareToIgnoreCase(t)); //0
System.out.println(s.compareToIgnoreCase(u)); //4(d) - 24(x)=-20
System.out.println(u.compareToIgnoreCase(s)); //24(x) - 4(d)=20
System.out.println(s.compareToIgnoreCase(v)); //0
System.out.println(s.compareToIgnoreCase(w)); //5-8=-3
System.out.println(w.compareToIgnoreCase(s)); //8-5=3
System.out.println(“abcde”.compareToIgnoreCase(“abcDefgh”));//5-8=-3
System.out.println(“abcde”.compareToIgnoreCase(“Wxyz”));//1(a)-23(W)=-22
11.trim() - This method returns a new string after removing the leading and trailing spaces from the
string.
Argument type - no arguments
Return type - String
String s=” hello world ”;
System.out.println(“$“+s+”#”);//$ hello world #
System.out.println(“$“+s.trim()+”#”);//$hello world#
12.split() - This method returns an array of strings after separating each word from a given string.
Argument type - string
Return type - String array
String s=”My name is Animesh”;
String ar[ ]=s.split(“ ”);
String s=”My_name_is_Animesh”;
String ar[ ]=s.split(“_”);
System.out.println(ar[1]) ; // name
13.startsWith() - This method tests whether the string starts from a given string or not.
Argument type - string
Return type - boolean
String s=”Mr Vivek Kumar”;
System.out.println(s.startsWith(“Mr”)); //true
System.out.println(s.startsWith(“mr”)); //false
System.out.println(s.startsWith(“Miss”)); //false
14.endsWith() - This method tests whether the string ends with a given string or not.
Argument type - string
Return type - boolean
String s=”Mr Vivek Gupta”;
System.out.println(s.endsWith(“Gupta”)); //true
System.out.println(s.endsWith(“gupta”)); //false
System.out.println(s.endsWith(“Sharma”)); //false
15.concat() - This method is used to join two strings.
Argument type - String
Return type - String
String s=”Hello”;
String t=”World”;
System.out.println(s.concat(t)); //HelloWorld
System.out.println(s.concat(“ ”).concat(t)); //Hello World
System.out.println(s+t); //HelloWorld
System.out.println(s+” ”+t); //Hello World
16.replace() - This method replaces all occurrences of given substring with the new substring in a
given string.
Argument type - String-String, char-char
Return type - String
System.out.println(“Malayalam”.replace(‘a’,’b’)); //Mblbyblbm
System.out.println(“Malayalam”.replace(“m”,”b”)); //Malayalab
System.out.println(“My name is Saksham”.replace(“am”,”mb”)); //My nmbe is Sakshmb
17.substring() - This method returns a part of a given string.
Argument type - int, int-int
Return type - String
System.out.println(“hello world”.substring(3)); //lo world
System.out.println(“hello world”.substring(3,7)); //lo w
System.out.println(“hello world”.substring(3,70)); //lo world
18.valueOf() - This method converts any primitive type value into string. It is a static method that's
why it is called by using class name.
Argument type - any primitive type value
Return type - String
Wrapper Classes
These classes are used to perform boxing and unboxing. These are defined in the java.lang package.
There are 8 wrapper classes provided corresponding to 8 primitive data types -
Primitive Data Type Wrapper Classes Primitive Data Type Wrapper Classes
1. parseInt() - It is used to convert String value 2. parseLong() - It is used to convert String
to integer. value to Long.
For example, For example,
String a=”12”; String a=”1234”;
String b=”34”; String b=”5678”;
System.out.println(a+b); //1234 System.out.println(a+b); //12345678
int x=Integer.parseInt(a); long x=Long.parseLong(a);
int y=Integer.parseInt(b); long y=Long.parseLong(b);
System.out.println(x+y); //46 System.out.println(x+y); //2468
3. parseFloat() - It is used to convert String 4. parseDouble() - It is used to convert String
value to float. value to double.
For example, For example,
String a=”12.34”; String a=”12.34”;
String b=”54.78”; String b=”54.78”;
System.out.println(a+b); //12.3456.78 System.out.println(a+b); //12.3456.78
float x=Float.parseFloat(a); double x=Double.parseDouble(a);
float y=Float.parseFloat(b); double y=Double.parseDouble(b);
System.out.println(x+y); //67.12 System.out.println(x+y); //67.12
3. parseFloat() - It is used to convert float value 4. parseDouble() - It is used to convert double
to String. value to String.
For example, For example,
float a=2.3f; double a=2.3;
String b=Float.toString(a); String b=Double.toString(a);
System.out.println(a+a); //4.6 System.out.println(a+a); //4.6
System.out.println(b+b); //2.32.3 System.out.println(b+b); //2.32.3
Chapter 17 Encapsulation and Inheritance
Access Specifier
These are the keywords which control the accessibility of members of a class and class itself.
Public
● They can be accessed everywhere.
Protected
● They can be accessed within a class
● They can be accessed within a package
● They can be accessed outside the package
but the class outside the package has
inherited it.
Private
● They can be accessed within a class only
Default(Private package)
● It is applied when no specifier is mentioned.
● They can be accessed within a class and package only.
Scope of Variables
It is of 4 types:
Local Variables
● It can be accessed only within the block in which it is defined.
● They are declared inside a method body, loop body, body of if or else, etc.
Class Variables
● They are also known as static variables.
● They are also known as Global variables.
● These are defined using static keywords.
● They are defined in a class body.
● They are associated with the class.
● Their common copy is shared among all the instances of a class as these members are related
to class and class only created once.
Instance Variables
● They are also known as non-static variables.
● They are also known as Global variables.
● These are defined without using static keyword.
● They are defined in a class body.
● They are associated with an instance or object of a class.
● They have separate copy among each object of a class as these members are related to
instances and instances can be created as many as we want.
Parameter or Argument Variables
● They are only accessible within the method in which they are defined.
● They are declared in the header/prototype of a method.
Example,
class Sample
{
int a; //instance or non-static variable
static int b; //class or static variable
void method(int c) //parameter or argument variable
{
int d; //local variable
}
}