Java Starting Notes
Java Starting Notes
JAVA NOTES
Date
SECTION-NO:-1
1. Standalone application
2. Mobile application
3. Web application
4. Baseness application
The language is a medium which is use to communicate with person
PROGRAMING LANGUAGE :-
Programing language is a medium which is use to communication with the machine we have
1. Low level
2. Middle level
3. High level
In middle level language are sum pre-defined word which is known as mnemonics
Move :- This word is use for moving the data from one place to another place
This words (mnemonics ) are not understandable by machine we have to use a software
called as assembler this assembler will convert middle level language in to low level language so that
The language which is readable execution & understandable by programmer hence it is called
This high level language is not understandable by machine so we will translate the high level
language in to binary language with the help of software compiler so that machine can easy to understand
Page No
JAVA NOTES
Date
FEACHURS OF JAVA :-
Java compiler
1. JAVA COMPILER :-
JRE provide you an environment which is use to successfully execute a java program
JRM is a one vino is responsible for converting byte code instruction into machine and
Standebal language with the help of interpreter and just in time [JIT] compiler
Page No
JAVA NOTES
Date
SOURCE CODE :-
BYTE CODE :-
PLATFORM DEPENDENT :-
The code written on one platform & can be executable on some platform is known as platform
dependent
Example :- c language
Page No
JAVA NOTES
Date
The code written on a one platform of can be executable on any platform is called as platform
Independent
Example :- java
Note:-
drive Name :-
Dir. :-
This command is used to list all the files & directories from current directory
cd.:-
This command is used to come outside the current folder
This command is used to enter in side for given folder given directory.
cis :-
java c :-
Page No
JAVA NOTES
Date
This command is used to compile the java source code with this command use have to pass java
java name:-
This command is used to execute java class file with this command name of file passed without
Extension.
MEMBERS OF A CLASS :-
1. Methods
2. Variables
3. Initialization
1. METHOD :-
2. VARIABLES:-
3. INITIALIZER :-
Program :-
class sub
[Link]("100-50");
}
Page No
JAVA NOTES
Date
Out Put:-
class sub
We can create a class without main method it is compiler time successful and dot class file will
Print l n :-
If we do not pass any value it will not print any think but it will move the cursor on the next line
Page No
JAVA NOTES
Date
Program:-
class numberdisplay
[Link](10);
[Link](20);
[Link](30);
Output:-
Print :-
It is use to print the value & move the cursor on same line
If we do not pass any value it will not move the cursor on the same line but it will give you compile time
error
Program :-
class emty
{s
[Link]();
[Link]();
Page No
JAVA NOTES
Date
[Link]();
output :-
TOKENS :-
1) Keyword
2) Identifier
3) Separator
4) Literals
1) KEYWORD :-
2) IDENTIFIER :-
RULES OF IDENTIFIER :-
Identifier should not start with the number but we can use the number in between & in the end “alpha
Numeric”
Note:-
If any of above rule is not followed we will get compile time error
CONVENTIONS :-
Compiler doesn’t validate the convention there for if convention are not followed we don’t get
If it is a multi-word first word should be in lower case rest can should be in upper case
3) SEPARATOR :-
4) LITERALS :-
Page No
JAVA NOTES
Date
1. Primitive
2. Non-Primitive
1. PRIMITIVE :-
A. NUMBER :-
i. Integer
ii. Float
Example :- 20, 8, 9, 100
B. CHARACTER :-
C. BOOLEAN :-
Ex 1 Write a java program to print name, contact _No ,10th_percentage, Birth_date, gender, status, age .
Program:-
class studentinformation
[Link]("Magesh Patil");
[Link]("7219040074");
[Link](51.48);
[Link]("4-07-1999");
[Link]('M');
[Link]("False");
[Link](23);
Output :-
+ OPERATOR :-
Addition
Concatenation (Marge)
class concatwithboolean
[Link](true+false); //error
[Link](true + "hallow word"); //rune the command print "true hallow word"
Program :-
class concatwithstring
[Link](10+"hellow");
[Link](100 + "hellow");
[Link]("hellow" + 't');
[Link](false + "hellow");
[Link]("hellow" + "java");
Output :-
Page No
JAVA NOTES
Date
Program :-
class concatwithchar
[Link]('a' + "hellow");
[Link]('a' + 10);
[Link]('b' + 45.7);
[Link]('A' + 'A');
Output:-
Program:-
class concatwithnumber
[Link](40 + "ok");
Page No
JAVA NOTES
Date
[Link](50 + 'A');
[Link](60 + 20);
[Link](70 + 10.5);
Output:-
2. NON PRIMITIVE:-
DATA TYPE :-
Data type are used to create variable of specific type in java data types ate classified in to two type
1. Primitive
2. Non-primitive
The data type which is used to create a variable to store primitive value such as number , character,
Note:-
Short 2 byte
Int 4 byte
Long 8 byte
Double 8 byte
The data type which is used to create non-primitive variable is known as non-primitive data type
Example :- string
Note:-
VARIABLE :-
Int a = 10
1. Primitive variable
A. Non-Primitive variable
Page No
JAVA NOTES
Date
1. PRIMITIVE VARIABLE :-
The variable which is used to store primitive value is known as primitive variable.
We can create a primitive variable with the help of primitive data type.
2. NON-PRIMITIVE VARIABLE :-
Example:- string
Program :-
class datatype
[Link](name);
[Link](mobno);
[Link](percentage);
[Link](dob);
[Link](gender);
[Link](status);
}
Page No
JAVA NOTES
Date
SCOPE OF VARIABLE :-
1) Local
2) Static
3) Non-static
1) LOCAL VARIABLE :-
The variable declared in side method block or any other block is known as local variable (accept class)
❷ If we try to use local variable without initialization then we will get compile time error
❸ The scope of local variable is nested inside the block where are it is created hence it can’t be use out
outside the block
OPERATORS:-
Operators are pre-defined symbol which is use to perform specific task on even data the data given as
an input to the operator is known as operators
1. Unary
2. Binary
3. Ternary
1. UNARY OPERATOR:-
The operator which can accept only one operator is known as unary operator
A. Increment
B. Decrement
C. Type cast
Page No
JAVA NOTES
Date
2. BINARY OPERATOR:-
B. Relational
C. Logical
3. TERNARY OPERATOR :-
A. Conditional operator
A. INCRIMENT OPERATOR :-
❶ Increment operator is a unary operator
++ variable name
Example :- int a = 22
[Link] (++a);
Stapes to perform pre increment operator
The increment operator which is suffix to its variable name is known as post increment operator
Syntax:-
Variable name ++
Example :- int a = 22
[Link] (a) ; // 23
Program :-
class incrementoperator
{
public static void main(String[] args)
{
int f = 56;
[Link](f++ + ++f -f + ++f);
}
}
Output :-
Program :-
class incrementoperator1
{
public static void main(String[] args)
{
int a = 10;
int b = 30;
[Link](a+b);
[Link](a++ + ++a + b -a );
[Link](++a + b++ + b++ - ++a);
}
}
Page No
JAVA NOTES
Date
Output :-
B. DECREMENT OPERATOR :-
Example :- class
Int c = 99
[Link] (c);
[Link] (--c);
[Link] (c);
b. POST DECREMENT :-
The decrement operator which suffix to its variable name it’s called as a post decrement operator
❷ Decrement the value present inside the variable by one and update
Program :-
class decrementoperator
{
public static void main(String[] args)
{
char g = 'A';
[Link](g + --g + g--);
[Link](g);
}
}
Output:-
1. Primary
2. Non-primary
1. PRIMARY :-
The process of converting one primary data type in to un-other primary data type
a. Winding
b. Narrowing
a. WINDING :-
The process of converting smallest primary data type in two largest primary data type
It is implicit process
}
}
Output:-
Page No
JAVA NOTES
Date
b. NAROWING :-
The process of converting larger range primary data type in to smaller reang of primitive data type is
known as narrowing
It can be don explicitly by the programmer using type cast operator
TYPE CAST :-
1. Unary
The type cast operator is used to explicitly convert one data type in to un-other data type
Program :-
class narowing
{
public static void main(String[] args)
{
double d = 45.7;
int i = (int)d;
[Link](d);
[Link](i);
}
}
Output :-
2. BINARY OPERATOR:-
A. ARITHMETIC OPERATOR :-
It is binary operator
+,-,/,%, *
Example :-
Page No
JAVA NOTES
Date
Program:-
class arithmaticoperator
{
public static void main(String[] args)
{
int a = 10;
int b = 5;
[Link](a+b);
[Link](a-b);
[Link](a/b);
[Link](a*b);
[Link](a%b);
}
}
Output:-
B. RELATIONAL OPERATOR :-
}
}
Page No
JAVA NOTES
Date
Output:-
C. LOGICAL OPERATER:-
AND OR NOT
&& || !
1 2 RESULT
T T T
T F F
F T F
F F F
Example:-
Program:-
class andoperator
{
public static void main(String[] args)
{
[Link](true && true);
[Link](true && false);
[Link](false && true);
[Link](false && false);
}
}
Output:-
Page No
JAVA NOTES
Date
b. OR (||) OPERATOR:-
1 2 RESULT
T T T
F T T
T F T
F F F
Example:-
Program:-
class oroperator
{
public static void main(String[] args)
{
[Link](true || true);
[Link](true || false);
[Link](false || true);
[Link](false || false);
}
}
Output:-
1 RESULT
T F
F T
Program:-
class notoperator
{
public static void main(String[] args)
{
[Link](!true);
[Link](!false);
}
}
Output:-
3. TERNARY OPERATOR :-
A. CONDITIONAL OPERATOR :-
Syntax:-
WORK FLOW :-
Program:-
class conditionoperator
{
public static void main(String[] args) {
int num1 = 159;
Page No
JAVA NOTES
Date
Output:-
Question Write a java program to check whether the given character is alpha bate or not
Program:-
class alphabateornot
{
public static void main(String[] args)
{
char al = 'A';
String res = (al>='a' && al<='z')||(al>='A' && al<='Z')? "it is alphabate" : "it is not alphabate";
}
}
METHOD :-
A method is a block of instructions which is use to perform a specific task
Syntax:-
Instruction;
A. ACCESS MODIFIER:-
B. MODIFIER :-
C. METHOD SIGNATURE:-
Method signature contains name of method and formal argument
D. METHOD DECLERATION :-
Method declaration contains access modifier, modifier, return type and method signature
E. METHOD DEFINATION :-
The statement which is used to call un-other method is known as method call statement
Note:- A method will get executed only when it is called we can call a method using
method calls statement
a. CALLING METHOD :-
The method which is trying to call another method is known as calling method or caller method
b. CALLED METHOD :-
The method which is called by the un-other method is known as called method
Page No
JAVA NOTES
Date
Diagram:-
Program:-
class methodcallstatement
{
public static void main(String[] args)
{
[Link]("main start");
anjali();
[Link]("main end");
}
public static void anjali()
{
[Link]("anjali like rahul");
rahul();
}
public static void rahul()
{
[Link]("rahul like tina");
tina();
}
public static void tina()
{
[Link]("dead");
}
}
Output:-
Page No
JAVA NOTES
Date
Note:-
G. MAIN METHOD :-
The execution of a program always start from main method
Syntax:-
A method can be execution only when it is call we can call a method any number of
time there for it is said to be a code reusable
TYPE OF METHOD :-
2) Parameterized
1) NO-ARGUMENT METHOD :-
2) PARAMETERIZED METHOD :-
The method which has formal argument is known as parameterized method
A. FORMAL ARGUMENT :-
Page No
JAVA NOTES
Date
The type of actual argument should be same as a type of formal argument , if not compiler try’s to
RETURN STATEMENT :-
❶Return is keyword
❷A method after execution return the data back to the caller with the help of return key word
❹When return statement is executed the execution of current method will get term heated & control is
❹A method can have either void or some other return type (return type mandatory)
❺Void method can have return statement
❻If a method has any other return type except void then there must be a return statement
❾In side method the return statement should be the last execution instruction
Statement :-
1) If
2) If____Else
3) Else_____If ladder
4) Switch
1) IF STATEMENT:- Syntax:- If (condition)
{
task
}
Page No
JAVA NOTES
Date
WORK FLOW :-
If condition is false if block will get skip and instruction which is return after f block will get execution
Program :-
class ifstetment
{
public static void main(String[] args)
{
int a = 10;
if (a<50)
{
[Link](a + "is low ");
}
[Link]("Hello World!");
}
}
Output”-
2) IF_______ELSE:-
SYNTAX:-
If (condition)
{ true/false
Task;
}
Else
{
Task;
}
WORK FLOW:-
❶ If the condition is true if block will be executed of else block will get skipped
❷ if condition is false if block will be skipped it else block will get executed
Page No
JAVA NOTES
Date
Program:-
class ifelse
{
public static void main(String[] args)
{
int a = 10;
if (a<50)
{
[Link](a + "is smaller than 50");
}
else
{
[Link](a+ "is grater than50");
}
}
}
Output:-
3) ELSE IF___LADDER:-
Syntax:-
If (condition)
{ true/false
Task;
}
Else if (condition)
{ true/false
Task;
}
Else if (condition)
{ true/false
Task;
Else (condition)
{
Task;
}
Page No
JAVA NOTES
Date
WORK FLOW:-
❷condition will start checking in top to bottom order which ever condition is true that block will get
other block will get skipped
❸if non-of the condition are true else block will get executed
4) SWITCH():-
Syntax:-
switch(value/variable)
{
Case value:
{
Task;
}
Case value :
{
Task;
}
Break;
Default:
{
}
}
WORK FLOW:-
❶The value variable pass in switch gets compare with value pass in a case from top to bottom or
❷if any case is match that class block will get executed and the blocks below will also get executed
❸If no case is match default case will get executed after each case we can use break statement which is
BREAK KEYWORD:-
❶Break keyword is a control transfer statement break can be used inside switch and loop
Page No
JAVA NOTES
Date
❷When the break statement executed the executed the execution of current block will be stop and control
Program:-
class switchvowel
{
public static void main(String[] args)
{
char ch ='i';
switch (ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
{
[Link]("it is vowel");
}
break;
default:
{
[Link]("28 days");
}
}
}
}
Output:-
Program:-
class dasynmonth
{
public static void main(String[] args)
{
int a =1;
switch (a)
{
case 1:
Page No
JAVA NOTES
Date
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
{
[Link]("31 days");
}
break;
case 2:
{
[Link]("28 days");
}
break;
case 4:
case 6:
case 9:
case 11:
{
[Link]("30 days");
}
break;
default:
{
[Link]("invalid input");
}
}
}
}
Output:-
LOOP:-
Loops are used to perform the set of instruction repeatedly there are four of loop
1) While
2) Do while
Page No
JAVA NOTES
Date
3) For
4) For each
1) WHILE :-
Syntax:-
Initialization
While (condition)
{ true/false
Task;
Updation;
WORK FLOW:-
❶First condition will get check if condition is true the control will go inside while loop and it will
perform task after task the value get updated and again it will go to check the condition if condition is
2) DO WHILE:-
SYNTAX:- Initialization
Do
{
Task;
Updation;
}
While (condition)
{ true/false
Task;
}
WORK FLOW:-
❶First control will enter inside do block and perform the task after performing a task the value will get
Updation condition will get check if the condition is true control will again enter in a do block and same
❷If the condition is false control will enter in do block to perform a task and update the value at least once
{
public static void main(String[] args)
int a = 5;
int fact = 1;
while (a>=1)
fact = fact * a;
a--;
[Link]("factorial is :"+fact);
}
Page No
JAVA NOTES
Date
Output:-
Program:-
Output:-
Program:-
//write a java program to cut the last digit of number //
class cutlastno
{
public static void main(String[] args)
{
int num =6754;
int last=num/10;
Program:-
//write a java program to cheek whether the given number palindrome//
class palindrom
{
public static void main(String[] args)
{
int num = 1321;
int sum = num;
int rem = 0;
int rev = 0;
while (num!=0)
{
rem = num%10;
rev = (rev*10)+rem;
num = num/10;
}
if (sum==rev)
{
[Link]("no is palindrom : "+rev);
}
else
{
[Link]("no is not palindrom : "+rev);
Page No
JAVA NOTES
Date
}
}
}
Output:-
Program:-
class patternsymbol
{
public static void main(String[] args)
{
for (int i = 1; i<=4; i++)
{
for (int a = 1; a<=4; a++ )
{
[Link]('*');
}
[Link]();
}
}
}
Output:-
Program:-
class patte10101
{
public static void main(String[] args)
{
Page No
JAVA NOTES
Date
int k = 1;
for (int i = 1; i<=5; i++)
{
for (int a = 1; a<=5; a++ )
{
[Link](k);
if (k==1)
{
k--;
}
else
{
k++;
}
}
[Link]();
}
}
}
Output:-
Program:-
class patte12345
{
public static void main(String[] args)
{
int k = 1;
for (int i = 1; i<=5; i++)
{
for (int a = 1; a<=5; a++ )
{
[Link](k);
k++;
Page No
JAVA NOTES
Date
if (k>5)
{
k=1;
}
}
[Link]();
}
}
}
Output:-
Program:-
class pattern0000011111
{
public static void main(String[] args)
{
[Link]();
}
}
}
Page No
JAVA NOTES
Date
Program:-
class pattern123
{
public static void main(String[] args)
{
Output:-
Program:-
class pattern1s0s1
{
public static void main(String[] args)
{
for (int i = 0; i<5; i++)
Page No
JAVA NOTES
Date
{
for (int a =0; a<5; a++ )
{
if (a%2==1)
{
[Link]("*");
}
else if (a==2)
{
[Link](0);
}
else
{
[Link](1);
}
}
[Link]();
}
}
}
Output:-
Program:-
class patternABCDE
{
public static void main(String[] args)
{
[Link]();
Page No
JAVA NOTES
Date
}
}
}
Output:
Program:-
class patterntrangle
{
public static void main(String[] args)
{
2) Static variable
3) Static initializer
1) STATIC METHOD :-
❶ It is modifier
❷ Static is a keyword
❸ Any memorial of class which is prefix with a static modifier then it is known as static member of class
To execute a java program a portion of memory in ram is allocated for VRE in that portion of memory we
have deferent rang of memory
3. Stack Area
4. Heap Area
1. METHOD AREA:-
All the method blacks will be stored in method area with method name instruction and address
Page No
JAVA NOTES
Date
For average class there is a dedicated block of memory is created in class static area
The static members of a class will be allocated inside a memory created for class
3. STACK AREA:-
as a fream
Once the execution of a method dis completed the fream will get remove
4. HIPE AREA:-
In a heap area a block of memory is created for the instance of a class (object)
Avery block of memory created with the help of reference
All the non-static members of a class will be allocated inside the block of memory
There for we can access the non-static members with the help of reference
class treasing
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
Trashing:
Page No
JAVA NOTES
Date
Program:-
class treasingSubmethod
{
public static void main(String[] args)
{
[Link]("main start");
sub ();
[Link]("main end");
}
public static void sub()
{
int a = 50;
int b = 20;
int res = a-b;
[Link](res);
}
}
Tracing:-
STATIC METHOD:-
A method prefix with a static modifier is known as static method
Static method block will get stored in method area with name, instruction and address
The address of static method will get stored in class static area
A static method of the class can be used in any other class with the help of class name
Trashing :-
2) STATIC VERIABLE:-
Program:-
class staticVeriable
{
static int a;
public static void main(String[] args)
{
[Link]("main start");
[Link](a);
[Link]("main end");
}
}
Trashing:-
Page No
JAVA NOTES
Date
Variable declared in a class block and prefix with a static modifier is known as static variable
It is global in nature it can be used within the class as well as in different class
We can use a class name to print the value of static variable
We can access the static variable in different class using class name
If the local variable name and static variable name is same then priority will be given to the local variable
To differentiate a static variable and local variable can use a class name
Program:-
class add
{
static boolean b;
static int d;
public static void main(String[] args)
{
[Link]("main start");
int g = [Link]();
[Link](demo1.a);
test();
[Link](g);
[Link](b);
sub();
[Link]("main end");
}
public static void sub()
{
[Link]("sub start");
int a = 20;
int b = 10;
int sub = a-b-d;
[Link](sub);
[Link](b);
[Link]("sub end");
Page No
JAVA NOTES
Date
}
public static void test()
{
[Link]("test start");
[Link](demo1.a);
int c=34;
[Link](add.d);
[Link](c);
[Link]("test end");
}
}
Program:-
class demo1
{
static int a;
public static void main(String[] args)
{
add();
[Link]("Hello from main method");
}
public static int add()
{
[Link](a);
int res = 40+20;
[Link](res);
return res;
}
}
Trashing :-
Page No
JAVA NOTES
Date
3) STATIC INITIALIZATION :-
Program:-
class staticinitialization
{
static int f = 34;
public static void main(String[] args)
{
[Link]("main start");
add();
[Link]("main start");
}
static
{
[Link]("Hello from multi line static initializer");
}
public static void add()
{
[Link](20+30);
}
}
Trashing:-
Static initializer is use to the startup instruction of program as static initializer gets execution before the
actual execution
Syntax:-
Syntax:-
Static
A block is created for a class in the static pull it can be access with the help of class name
All the method definition will get loaded in method area and the method is static the reference will get
stored in class static area
It class has any static variable they will get loaded in class static area with default value
If class has any static initializer they will get executed in top to bottom order
The loading process of class is completed now JVM call the main method of initial loaded class
Note:-
JVM will only call the main method of initial loaded class
OBJECT:-
Any substance which has real world existence is known as real world object
Avery object will have attributes and behavior
OBJECT IN JAVA:-
Page No
JAVA NOTES
Date
According to object oriented programing object is a block of memory created in heap area during run time
CLASS:-
According to real world situation before costarring an object blue print of an object must be design it
It provides the specification of real world object
Similarly in object oriented programing before creating an object the blue print of an object must be design
which provides the specification of real world object
Step 2 Instunliantion
Syntax:-
New class name()
constructer
NEW KEYWORD:-
CONSTRUCTER:-
Constructer is a special member of a class whose name is same as the class name
Constructer
Page No
JAVA NOTES
Date
Non-primitive data type is use to create is non-primitive variable to store the reference of an object
Program:-
class bag
{
String colour;
double price;
int compartment;
String company;
public void tocarry()
{
[Link]("tocarry a bag");
}
public static void main(String[] java)
{
bag b1=new bag();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]("---------");
[Link]="black";
[Link] =500;
[Link]=4;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]="puma";
[Link]([Link]);
}
}
Trashing:-
Page No
JAVA NOTES
Date
STATIC CONTACT:-
The block which belongs to static method and multiline static initializer is known as static contact
Program:-
class subprogrambag
{
public static void main(String[] args)
{
bag b1=new bag();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
}
}
Trashing :-
Page No
JAVA NOTES
Date
DYNAMIC READ:-
The process of reading the data from the user during execution of a program is known as dynamic read
Step 2:- create an abject of scanner class scanner s1 = new scanner ([Link]);
Step 3:- call the method of a scanner class to read the data from user int a1 = [Link]();
Type of Data
Byte Nextbyte()
Short Nextsort()
Int Nextint()
Long Nextlong()
Floot nextfloot
Double Nextdouble()
Boolean Nextboolean()
Char Nextchar()
String (string word) Next()charft()
class shoes
{
String colour;
int size;
String company;
public static void forrunning()
{
[Link]("use for running");
}
public static void main(String[] args)
{
shoes s1 = new shoes();
Page No
JAVA NOTES
Date
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link] = "black";
[Link] = 7;
[Link] = "woodland";
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
shoes s2 = new shoes();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
class Books
{
String name;
int noofpages;
int price;
public static void main(String[] java)
{
Books b1 = new Books();
Page No
JAVA NOTES
Date
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]("_________________________");
[Link] = 300;
[Link] = "SQL";
[Link]();
[Link]([Link]);
[Link]([Link]);
[Link]("________________________");
Books b2 = new Books();
[Link] = 500;
[Link] = "java";
[Link] = 500;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]("________________________");
Books b3 = new Books();
[Link] = 650;
[Link] = "python";
[Link] = 450;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
}
public void toread()
{
[Link](name+ "is a book of" +noofpages+ "pages");
}
}
Trashing:-
Page No
JAVA NOTES
Date
Any member declared in a class and not prefix with a static modifier is known as non-static member of class
Non-static member belongs to an instance of class hence it is also known as instance member or object
member
The member for non-static member is allocated inside the heap area
We can create any no off instance for a class
NON-STATIC MEMBER:-
1) Non-Static Variable
2) Non-Static Method
3) Non-Static Initialization
1) NON-STATIC VERIABLE:-
A variable declared inside a class block and prefix with a static modifier is known as non-static variable
2) NON-STATIC METHOD:-
Any member declared in a class block and not prefix with a static modifier is known as non-static method
❶A method will gets stored inside a method area and reference of method will get stored in side instance
❷We can’t call the non-static method of a class without creating instance of class (object of class)
❸We can’t access the non-static method directly with the help of class name
❹Non-static method can’t be access directly with their name inside static context.
Page No
JAVA NOTES
Date
3) NON-STATIC INITIALIZER:-
Non-static initializer will execute once for every instance of class (for every object)
Syntax:-
Instruction
}
Note:-
All non-static initializer will get execution in top to bottom order by constructer for
every instance of a class
class nonstaticinitializer
{
static int b = 34;
int a = 25;
static
{
[Link]("Hello World MLSI");
}
public static void main(String[] args)
{
[Link]("Main start");
nonstaticinitializer n1 = new nonstaticinitializer();
[Link]("Main End");
}
{
[Link]("Hello World MLNSI");
}
}
Page No
JAVA NOTES
Date
Trashing:-
ARRAY:-
CHARACTERISTIC OF AN ARRAY :-
❶The size of array must be define at the time of declaration
❷Once declare the size of array can’t be modified hence array is known as fixed size
❸In an array we can access the element’s with the help of index
❹Index is a integer number which start’s from zero and end’s with the size of array minus one
❺In an array we can store only homogeneous type of value. It is also known as homogeneous collection of
object
Note:-
DECLARING AN ARRAY:-
Syntax:-
Data type name [] = new data type [size]
Page No
JAVA NOTES
Date
INSTANTIATING AN ARRAY :-
Ar[0]=10 0 0 10
Ar[1]=20 1 0 20
Ar[2]=30 2 0 30
Ar[3]=40 3 0 40
[Link](ar[0]+ar[1])
Page No
JAVA NOTES
Date
[Link](ar[2])
[Link](ar[3])
Q.1 Create all array initializer the value in array and print all the value an array using loop
Q.2 Create an array and print the addition of all the number’s from array
Q.4 Write a java program to copy all the elements from one array to another
Page No
JAVA NOTES
Date
COMSTRUCTER:-
Program:-
class constructerMarker
{
String color = "Read";
double price;
constructerMarker()
{
[Link]("Hello from no args constructer");
}
public static void main(String[] args)
{
constructerMarker m1 = new constructerMarker();
}
{
[Link]("Hello from MLNSI");
}
}
Output :-
Constructer is a special type of non-static method whose name is the same as a class name but it does not
have written type
Syntax :-
{
Instruction
PURPOSE OF A CONSTRUCTOR :-
❶Non-static members of a class will be loaded of an object if there is non-static initializer in the class
CLASSIFICATION OF CONSTRUCTER:-
1. No-argument constructer
2. Parameterize constructer
1. NO-ARGUMENT CONSTRUSTER:-
A constructor which does not have a formal argument is known as no argument constructer
2. PARAMETERISE CONSTRUCTER:-
If a class as having more than one constructer with a same name but different formal argument is known
as constructer over loading
Parameterize constructer is use to initialize non-static variable buy a accepting data from constructer in the
Program:-
class pen
{
String color;
double price;
pen()
{
[Link]("Hello no argument construction");
}
pen(String h)
{
Page No
JAVA NOTES
Date
color=h;
}
pen(String a, double b)
{
color = a;
price = b;
}
public static void main(String[] args)
{
pen p1 = new pen ();
[Link]([Link]);
[Link]([Link]);
pen p2 = new pen ("black",100);
[Link]([Link]);
[Link]([Link]);
pen p3 = new pen ("blue");
[Link]([Link]);
[Link]([Link]);
}
}
Output:-
Program:-
import [Link];
class calculater
{
public void add()
{
Scanner sc =new Scanner ([Link]);
[Link]("Enter the 1st num");
int a = [Link]();
Page No
JAVA NOTES
Date
import [Link];
class calculaterDriver
{
public static void main(String[] args)
{
Scanner sc =new Scanner ([Link]);
calculater c1 = new calculater();
boolean exit = true;
while(exit)
Page No
JAVA NOTES
Date
{
[Link]("Enter the choice \[Link]\[Link]\[Link]\[Link]\[Link]");
int choice = [Link]();
switch (choice)
{
case 1:
{
[Link]();
}
break;
case 2:
{
[Link]();
}
break;
case 3:
{
[Link]();
}
break;
case 4:
{
[Link]();
}
break;
case 5:
{
exit = false;
[Link]("Application Closed______");
}
break;
}
}
}
}
Page No
JAVA NOTES
Date
Page No
JAVA NOTES
Date
SECTION-NO:-2
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
1. ENCAPSULATION:-
❶The process of binding seats behavior of an object together is in known as encapsulation
1) DATA HIDING :-
It is process of restricting the direct access of data member of an object and provides indirect secured
access of data member throw the method of the same object is known as data hiding
PRIVET MODIFIER:-
❶Private is access modifier
GETTER METHOD:-
❶The getter method is used to fetch the data (print, display, read)
SETTER METHOD:
Note:-
❶ If you won’t to make your data member only readable get create only getter
❷If you won’t to make your hidden data member only modifiable then create only setter method
❸If you won’t to make your hidden data member both readable and modifiable then create both getter and
setter method
❹If we won’t to make your hidden data member neither readable non modifiable then don’t create getter
Program:-
class Mobile
{
private String color;
private double price;
private String company;
import [Link];
class MobileDriver
{
public static void main(String[] args)
{
Scanner sc = new Scanner ([Link]);
Mobile m1 = new Mobile();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]("---------------------------");
[Link]("Enter the mobile company");
String comp = [Link]();
[Link](comp);
[Link]("mobile company updated successfully-----");
[Link]("---------------------------");
[Link]("Enter the mobile price");
double price = [Link]();
[Link](price);
[Link]("mobile price updated successfully-----");
[Link]("---------------------------");
[Link]("Enter the mobile color");
String color = [Link]();
[Link](color);
[Link]("mobile color updated successfully-----");
[Link]("--------------------------");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Out Put:-
Page No
JAVA NOTES
Date
RELATIONSHIP:-
Type of relationship
1. Has a relationship
2. Is a relationship
1. HAS A RELATIONSHIP:-
Based on the level of dependent on the has a relationship is classified in to two type
1) Composition
2) Aggregation
1) COMPOSITION:-
The dependency between two object such that one object can’t exist without another object is known
as composition
2) AGGREGATION:-
The dependency between two object such that one object can exist without the another object is know
as aggregation
Ex:- train and online train booking
Car Engine
{ {
} }
Note:-
❶We can achieve a has a relationship is java by placing the reference variable of dependent class in side
another class
❷The instance of dependent object can be created in two ways
Page No
JAVA NOTES
Date
1) Early instantiations
2) Lazy instantiations
1) EARLY INSTANTIATIONS:-
Step3:-Create constructer of a class which also accept the dependent type object
Step4:-Create the object of a class so the object of dependent class gets created
Program:-
package relationship;
package relationship;
package relationship;
Out Put:-
Program:-
package bagStudentBagDrive;
package bagStudentBagDrive;
import [Link];
Out Put:-
Program:-
package StudentSchool;
public class Student {
private String sname;
private int id;
private int std;
public String getSname() {
return sname;
}
public void setSname(String sname) {
[Link] = sname;
}
Page No
JAVA NOTES
Date
package StudentSchool;
import [Link];
public class School {
String name;
Student s;
public School(String name) {
[Link] = name;
}
public void addstudent() {
if (this.s == null)
{
this.s = s;
[Link]("admision successfully");
[Link]("----------------------------------------");
}
else
{
[Link]("admision is already taken yet");
[Link]("-----------------------------------------");
}
}
public void canceleadmision() {
if (this.s == null)
{
[Link]("admision is not taken yet");
[Link]("-----------------------------------------");
}
else
{
this.s = null;
[Link]("admision cancele successfully");
[Link]("-----------------------------------------");
}
}
public void updatestd() {
if (this.s == null)
{
Page No
JAVA NOTES
Date
package StudentSchool;
import [Link];
public class SchoolDriver {
public static void main(String[] args) {
Scanner sc = new Scanner ([Link]);
School s1 = new School("Hal School");
boolean exit = true;
while (exit)
{
[Link]("Enter the Choice\n1 Taken Admision\n2 Cancele Admision\n3
Update STD \n4 Display Details\n5 Exite");
int choice = [Link]();
switch (choice)
{
case 1:
{
[Link]("ENTER THE STUDENT NMAE");
String name = [Link]();
[Link]("ENTER THE STUDENT ID");
int id = [Link]();
[Link]("ENTER THE STD");
int std = [Link]();
[Link]();
}
break;
Page No
JAVA NOTES
Date
case 2:
{
[Link]();
}
break;
case 3:
{
[Link]();
}
break;
case 4:
{
[Link]();
}
break;
case 5:
{
exit = false;
[Link]("APLICATION CLOSED..........");
[Link]("---------------------------------------");
}
break;
default:
{
[Link]("Invalid choice______");
}
}
}
}
}
IS A RELATIONSHIP:-
The relationship between two object which is similar to parent and child relation is known as is a relationship
In an is a relationship the child object will acquire all the property of the parent object and child object will
In is a relationship we can achieve generalization and specialization parent is called as generalization and
Note:-
With the help of child class deference type we can use members of parent as child class with the help
Of parent class reference we can use only the member of parent class but not the child class
Note:-
INHERITANCE:-
The process of one class is acquiring all the property and behavior of another class is called as
Inheritance
In java we can achieve inheritance with the help of
1. Extend keyword
2. Implement keyword
1. EXTENND KEYWORD:-
{
child c1 = new child ();
[Link] (); //hello from child
[Link] (); //hello from parent
[Link]("------------------------");
parent p1 = new parent ();
[Link](); // hello from parent
[Link](); // error
}
Program:-
public class user {
private String name;
private long cno;
private int pswd;
private String status;
public user(String name, long cno, int pswd, String status) {
[Link] = name;
[Link] = cno;
[Link] = pswd;
[Link] = status;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public long getCno() {
return cno;
}
public void setCno(long cno) {
[Link] = cno;
}
public int getPswd() {
return pswd;
}
public void setPswd(int pswd) {
[Link] = pswd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
[Link] = status;
}
}
package relationship;
import [Link];
public class Instagram
Page No
JAVA NOTES
Date
user u;
public void loginuser(user u) {
if (this.u==null) {
this.u=u;
[Link]("Login Successfully......");
[Link]("-------------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the passward");
int pswd = [Link]();
if (pswd == [Link]()) {
[Link]("Already Logged in");
[Link]("-------------------------");
}
else {
[Link]("Incorrect Passward");
[Link]("-------------------------");
}
}
}
public void logout () {
if (this.u==null) {
[Link](" loged in First");
[Link]("-------------------------");
}
else {
this.u=null;
[Link]("Logout Successfully.....");
[Link]("-------------------------");
}
}
public void updateStatus () {
if (this.u==null) {
[Link]("Login First....you havent log in");
[Link]("-------------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the passward");
int pswd = [Link]();
if (pswd == [Link]()) {
//Scanner sm = new Scanner([Link]);
[Link]("Update the status");
String status = [Link]();
[Link](status);
[Link]("Status updated succesfully.......");
[Link]("-------------------------");
}
else {
[Link]("Incorrect Passward");
}
Page No
JAVA NOTES
Date
}
}
public void displayDetails () {
if (this.u==null) {
[Link]("login first...");
[Link]("-------------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the passward");
int pswd = [Link]();
if (pswd == [Link]()) {
[Link]("user name : "+ [Link]());
[Link]("user contact number : "+ [Link]());
[Link]("user satus : "+ [Link]());
[Link]("-------------------------");
}
else {
[Link]("Incorrect Passward");
}
}
}
public void changePassward () {
if (this.u==null) {
[Link]("Login first");
[Link]("------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the Old passward");
int opswd = [Link]();
if (opswd == [Link]()) {
Scanner sm =new Scanner ([Link]);
[Link]("Enter new Passward");
int npswd = [Link]();
[Link](npswd);
[Link]("New Passward Updated Succesully.....");
}
else {
[Link]("Incorrect Old Passward");
}
}
}
}
package relationship;
import [Link];
public class DriverInstagram {
public static void main(String[] args) {
Scanner sc = new Scanner ([Link]);
Instagram ref = new Instagram ();
boolean condition = true;
while (condition) {
Page No
JAVA NOTES
Date
Program:-
package relationship;
public class Account {
private String name;
private long acno;
private String branch;
private long cno;
private double balance;
private int pswd;
public Account(String name, long acno, String branch, long cno, double balance, int
pswd) {
Page No
JAVA NOTES
Date
[Link] = name;
[Link] = acno;
[Link] = branch;
[Link] = cno;
[Link] = balance;
[Link] = pswd;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public long getAcno() {
return acno;
}
public void setAcno(long acno) {
[Link] = acno;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
[Link] = branch;
}
public long getCno() {
return cno;
}
public void setCno(long cno) {
[Link] = cno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
[Link] = balance;
}
public int getPswd() {
return pswd;
}
public void setPswd(int pswd) {
[Link] = pswd;
}
}
package relationship;
import [Link];
public class Bank {
Account a;
String bankName;
public Bank(String bankName) {
[Link] = bankName;
}
public void createAccount(Account a) {
Page No
JAVA NOTES
Date
if (this.a==null) {
this.a=a;
[Link]("Account Created Successully....");
[Link]("-------------------------------");
}
else {
[Link]("Account Already created.......");
[Link]("------------------------------");
}
}
public void cancelAccount() {
if (this.a==null) {
[Link]("Account not created Yet.......");
[Link]("------------------------------");
}
else {
Scanner sc =new Scanner ([Link]);
[Link]("Enter the Pin");
int pin = [Link]();
if (pin==[Link]()) {
this.a=null;
[Link]("Account Canceled Successfully..");
[Link]("------------------------------");
}
else {
[Link]("Incorrect Pin....");
}
}
}
public void updateDetails() {
if (this.a==null) {
[Link]("Account not created Yet.......");
[Link]("------------------------------");
}
else {
Scanner sc =new Scanner ([Link]);
[Link]("Enter the Pin");
int pin = [Link]();
if (pin==[Link]()) {
[Link]("Enter the new Contact Number");
long ncno = [Link]();
[Link]("Enter New Branch Name");
String branch = [Link]();
[Link](ncno);
[Link](branch);
[Link]("The updation for Branch And Contact Number is
Successfull.....");
[Link]("------------------------------");
}
else {
[Link]("Incorrect Pin....");
}
}
}
public void displayDetails () {
Page No
JAVA NOTES
Date
if (this.a==null) {
[Link]("Account not created Yet.......");
[Link]("------------------------------");
}
else {
Scanner sc =new Scanner ([Link]);
[Link]("Enter the Pin");
int pin = [Link]();
if (pin==[Link]()) {
[Link](">>>>>>>>>>>>>>> "+bankName);
[Link]("Name : "+ [Link]());
[Link]("Branch Name :"+ [Link]());
[Link]("Contact Number : "+ [Link]());
[Link]("Account Number : "+ [Link]());
[Link]("------------------------------");
}
else {
[Link]("Incorrect Pin....");
}
}
}
public void changePassward () {
if (this.a==null) {
[Link]("Login first");
[Link]("------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the Old passward");
int opswd = [Link]();
if (opswd == [Link]()) {
Scanner sm =new Scanner ([Link]);
[Link]("Enter new Passward");
int npswd = [Link]();
[Link](npswd);
[Link]("New Passward Updated Succesully.....");
}
else {
[Link]("Incorrect Old Passward");
}
}
}
public void withdrawAmount () {
if (this.a==null) {
[Link]("Account not created Yet.......");
[Link]("------------------------------");
}
else {
Scanner sc = new Scanner([Link]);
[Link]("Enter the pin");
int pswd = [Link]();
if (pswd == [Link]()) {
[Link]("Enter Withdraw Amount");
int amt = [Link]();
if (amt <= [Link]()) {
Page No
JAVA NOTES
Date
package relationship;
import [Link];
public class DriverBank {
public static void main(String[] args) {
Bank ref = new Bank("IndianBank");
Scanner sc = new Scanner ([Link]);
boolean condition = true;
while (condition) {
[Link]("Enter the choice\n1. Creat Account \n2.
Cancel Account\n3. Update Details\n4. Display Detalis\n5.
Change Passward\n6. Withdraw Amount\n7. Deposite Amount\n8.
Display Balance\n9. Exit ");
int choice = [Link]();
switch(choice) {
case 1 : {
[Link]("Enter The Name");
String name = [Link]();
[Link]("Enter The Account Number");
long acno = [Link]();
[Link]("Enter The Branch");
String branch = [Link]();
[Link]("Enter The Contact Number");
long cno = [Link]();
[Link]("Enter The Balence");
double balence = [Link]();
[Link]("Enter The Passward/Pin");
int pswd = [Link]();
[Link](new Account
(name,acno,branch,cno,balence,pswd));
}
break;
case 2 : [Link]();
break;
case 3 : [Link]();
break;
case 4 : [Link]();
break;
case 5 : [Link]();
break;
case 6 : [Link]();
break;
case 7 : [Link]();
break;
case 8 : [Link]();
break;
case 9 : {
condition = false;
Page No
JAVA NOTES
Date
[Link]("Application Closed.....");
}
break;
default : [Link]("Something Went
Wrong....Try Again");
}
}
}
}
TYPES OF INHERITANCE :-
1. Single Level Inheritance:-
2. Multi-Level Inheritance:-
3. Hieratical Inheritance:-
If a parent (super class) has more than one child (sub class) at the same level then it is known as
Page No
JAVA NOTES
Date
hieratical inheritance
4. Multiple Inheritance:-
If a child class (sub class ) inheritance more than one parent class (supper class ) then it is known as
multiple inheritance
Note:-
❶Multiple inheritance has a problem known as demand problem
❷Because of demand problem we can’t achieve multiple inheritance with the help of class
❸In java we can achieve multiple inheritance with the help of interspace
DEMAND PROBLEM:-
C c1 = new (c)
c1.m1();
Page No
JAVA NOTES
Date
Assume that there are two classes class A and class B both are having a method with same
signature
If class C inheritance class A and class B then this two methods are inheritance to C
Now an ambiguity a arise when we try to call to super class method with the help of sub class reference
5. Hybrid Inheritance:-
When the object is created the super call statement help to load the non-static member of parent class
In to child object
We can also use super call statement to pass the data from child class to parent class
If a programmer doesn’t use a super call statement then compiler will add no argument super class
package relationship;
public class Vehical {
int noofseats;
int noofwheels;
public Vehical(int = noofseats, int = noofwheels) {
[Link];
[Link];
}
}
package relationship;
public class Bike extends Vehical {
Bike (_int a, int b)
{
super(a,b)
}
public static void main(String[] args) {
Bike b1 = new Bike (2,2);
[Link]([Link]);
[Link]([Link]);
}
}
[Link] = name;
}
}
package relationship;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student(34, "ram");
Student s2 = s1;
Student s3 = s2;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
Note:-
We can access the member of student object by using all three variable (s1,s2,s3)
The state of an object can also be modify by any of this three reference veriable
We can copy the reference of one veriable in to another veriable only if both the reference veriable
are of the same type
If both the reference veriable are of different type then the conversion of one reference to another
Fruit can be converted to apple and apple can be converted to fruit vegetable can converted to current
But fruit and apple can’t be converted vegetable and carrot as well as
Fruit can be converted in to an apple as well as mango and apple cannot convert in to fruit
But mango can’t converted to apple as well as apple can’t converted to mango
Example 3:-
1. Up casting
2. Down casting
1. Up casting:-
The process of converting the child class reference in to the parent class reference type
Note:-
Once the reference is up casted we can’t access the members of child class
Up casting can also be don explicitly with the help of type cast operator
Program:-
package relationship;
public class Apple extends Frute {
String color;
public static void main(String[] args) {
Frute f1 = new Apple();//up casting
[Link]([Link] );
//[Link]([Link]);//CTE
[Link]("----------------------------");
}
}
Page No
JAVA NOTES
Date
C = new min();
C = new micro();
C = new prime ();
DISADVANTAGE OF UPASTING:-
There is only one disadvantage of up casting that is once the reference is up casting the child member
Can’t be use
2. DOWN CASTING :-
The process of converting super class reference to child class reference is known as down casting
Note:-
Down casting is not implicitly don by the compiler
It should be don explicitly by the programmer with the help of type cast operator
Which we try to convert a reference to the specific type and the object does not exit then we will get
INSTANCE OF OPERATOR:-
It is a binary operator it is use to chaek the reference variable which object is present and which object
Is not present the return type of the instance of operator is boolean
If the specific object is present it will return true else it will return faults
Program:-
package relationship;
public class Frute {
}
package relationship;
public class Apple {
}
package relationship;
public class Mango {
}
package relationship;
public class FruteDriver {
public static void main(String[] args) {
Frute f1 = new Apple();
[Link]([Link] of Mango);
[Link]([Link] of Apple);
}
}
Program:-
package relationship;
public class Ball {
private double radius;
public Ball(double radius) {
[Link] = radius;
}
public void setRadius(int radius) {
Page No
JAVA NOTES
Date
[Link] = radius;
}
}
package relationship;
public class Bag {
Ball b;
public void addBall (int choice, double radius) {
if (this.b==null) {
if(choice==1) {
b=new TennisBall(radius);
[Link]("Tennis Ball is successfully addes in Bag");
[Link]("----------------------------");
}
else if (choice==2) {
b=new BasketBall(radius);
[Link]("Basket Ball is successfully addes in bag");
}
else {
[Link]("Invalid Choice");
[Link]("----------------------------");
}
}
else {
if (choice == 1) {
[Link]("Tennis The Ball is Already Addes");
[Link]("----------------------------");
}
else if (choice ==2) {
[Link]("Basket The Ball is Already Addes");
[Link]("----------------------------");
}
else {
[Link]("Invalid Input");
[Link]("--------------------------------");
}
}
}
public void removeBall() {
if (this.b==null) {
[Link]("Bag is not added in the Bag");
[Link]("---------------------------");
}
else {
this.b=null;
[Link]("Ball is successfully removed");
[Link]("----------------------------");
}
}
public void checkBag() {
if (this.b==null) {
[Link]("Bag is Empty");
[Link]("----------------------------");
}
else {
[Link]("Bag is Not Empty");
[Link]("----------------------------");
Page No
JAVA NOTES
Date
}
}
public void showGame() {
if (this.b==null) {
[Link]("Ball is not added in the Bag");
[Link]("----------------------------");
}
else {
if (this.b instanceof TennisBall) {
TennisBall t1 = (TennisBall)b;
[Link]("You can play " + [Link]());
[Link]("----------------------------");
}
else if (this.b instanceof BasketBall)
{
BasketBall b1 = (BasketBall)b;
[Link]("You can Play "+[Link]());
[Link]("----------------------------");
}
else {
[Link]("Ball Not Found");
}
}
}
}
package relationship;
public class BasketBall extends Ball {
private String gname = "BasketBall";
public BasketBall(double radius) {
super(radius);
}
public String getGname() {
return gname;
}
}
package relationship;
public class TennisBall extends Ball {
private String gname = "Tennis Ball";
TennisBall(double radius) {
super(radius);
}
public String getGname() {
return gname;
}
}
package relationship;
import [Link];
public class DriverBag {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Bag ref = new Bag ();
boolean condition = true;
while (condition) {
Page No
JAVA NOTES
Date
Program:-
package Book;
public class Book {
private int quantity;
Book (int quantity) {
[Link]=quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
[Link] = quantity;
}
}
package Book;
public class HarryPotter extends Book {
Page No
JAVA NOTES
Date
package Book;
public class RomeoJuliet extends Book {
private String bname = "Romeo Juliet";
private String author = "William Shakespear";
RomeoJuliet (int quantity ) {
super (quantity);
}
public String getBname() {
return bname;
}
public String getAuthor() {
return author;
}
}
package Book;
public class TwoStates extends Book {
private String bname ="2 States ";
private String author ="Chetan Bhagat";
TwoStates (int quantity ) {
super (quantity);
}
public String getBname() {
return bname;
}
public String getAuthor() {
return author;
}
}
package Book;
public class Cart {
Book b;
public void addBook (int choice, int quanity) {
if (this.b==null) {
if (choice== 1) {
b=new RomeoJuliet(quanity);
[Link]("The RomeoJuliet Book Add Successfully");
[Link]("-------------------------------------");
}
Page No
JAVA NOTES
Date
else if (choice == 2) {
b=new TwoStates(quanity);
[Link]("The 2 States Book Add Successfully");
[Link]("-------------------------------------");
}
else if (choice == 3) {
b=new HarryPotter(quanity);
[Link]("The Harry Potter Book Add Successfully");
[Link]("-------------------------------------");
}
else {
[Link]("Invalid Choice...");
}
}
else {
[Link]("The Book is Already Added !!");
}
}
public void removeBook () {
if (this.b==null) {
[Link]("Book is Not Added Yet..");
[Link]("-------------------------------------");
}
else {
this.b=null;
[Link]("The Book Remove is succesfull....");
[Link]("-------------------------------------");
}
}
public void checkCart () {
if (this.b==null) {
[Link]("Cart is Empty");
[Link]("-------------------------------------");
}
else {
[Link]("Cart is Not Empty");
[Link]("-------------------------------------");
}
}
public void showBook () {
if (this.b==null) {
[Link]("Add Book first...");
[Link]("-------------------------------------");
}
else {
if (b instanceof RomeoJuliet) {
RomeoJuliet r = (RomeoJuliet)b;
[Link]("Book Name : "+[Link]());
[Link]("Book Author Name : "+[Link]());
[Link]("Book Quantity : "+[Link]());
[Link]("---------------------------------");
}
else if (b instanceof TwoStates) {
TwoStates t = (TwoStates)b;
[Link]("Book Name : "+[Link]());
[Link]("Book Author Name : "+[Link]());
Page No
JAVA NOTES
Date
package Book;
import [Link];
POLIMORPHISM:-
Polymorphism is derived from to different greek word poly means number and morph means form
which means numeric form or different form polymorphism is a ability of an object to exiblit more than one
form in same name
If the binding is achieved at the compile time and the same behavior get executed is known as compile
time polymorphism
It is also called as static polymorphism compile time polymorphism can be achived by
1) Method overloading
2) Constructor overloading
3) Method shadowing
4) Variable shadowing
5) Operator overloading (does not support in java )
1) METHOD OVERLOADING :-
If more than one method is created with the same name but different formal argument in the same
class is known as method overloading
Ex:-
class Test
{
public static void main(String[] args)
{
add();
add(2,5);
add(3,2,1)
}
public void add(int a, int b)
{
int res = a+b;
[Link](res);
Page No
JAVA NOTES
Date
}
public void add (int a, int b, int c)
{
int res = a+b+c;
[Link](res);
}
public void add ()
{
[Link]("use for addition ");
}
}
2) COMSTRUCTOR OVERLOADING :-
If a class content more than one constructor with a same name but different formal argument is known
as constructor overloading
3) METHOD SHADOWING:-
It the sub class and superclass have the static method with same signature is known as method
shadowing
If the method shadowing is done all compile hence it is compile time polymorphism
The execution of method depends on a reference type and does not depends on the type of object
Created
Note:-
Ex:-
package ParentChild;
public class Parent {
public static void m1()
{
[Link]("Hello From Parent m1()");
}
}
package ParentChild;
public class Child extends Parent {
public static void m1()
{
[Link]("Hello Frome Child m1()");
}
public static void main(String[] args) {
Page No
JAVA NOTES
Date
4) VARIABLE SHADOWING:-
If the superclass and subclass have a variable if the same name then it is known as variable shadowing
In variable shadowing binding is done at compile time hence it is compile time polymorphism
The execution of variable is dependent upon the type of reference variable we have use
Note:-
It is applicable for both static and non-static variable
package ParentChild;
public class ParentC {
String s1 ="ParenC";
}
package ParentChild;
public class ChildP extends ParentC {
String s1 = "ParentC";
public static void main(String[] args) {
ParentC p1 = new ParentC();
[Link](p1.s1);
ChildP c1 = new ChildP();
[Link](c1.s1);
ParentC p2 = new ChildP();
[Link](p1.s1);
}
METHOD OVERRIDIGN:-
It the subclass and superclass have the non-static method with same signature is known as method
Overriding
Page No
JAVA NOTES
Date
Note:-
It is applicable only for non-static method
For method overriding is a relationship is mandatory
The type of method will get executed depends upon the type of object created
package ParentChild;
public class Parent {
public static void m1()
{
[Link]("Hello From Parent m1()");
}
}
package ParentChild;
public class Child extends Parent {
public static void m1()
{
[Link]("Hello Frome Child m1()");
}
public static void main(String[] args) {
Parent p1 = new Parent();
p1.m1();
Child c1 = new Child();
c1.m1();
Parent p2 = new Child();
p2.m1();
}
}
OBJECT CLASS:-
Object class is a supper most parent class for all the classes in java
1. To String ():-
To string method of an object class return the reference of an object in string formal
package Student;
public class Student {
String sname;
int id;
public Student (String sname , int id) {
[Link] = sname;
[Link] = id;
Page No
JAVA NOTES
Date
}
}
package Student;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student (Ram,12);
[Link](s1);//object class student @ 3d on address of object
}
}
Note:-
Java does not provide the real address of an object
Whenever program try to print the reference variable the to-string method of object class
get implicitly call
We overriding to-string method become instance of retuning address of an object it will returning the
package Student;
public class Student {
String sname;
int id;
public Student (String sname , int id) {
[Link] = sname;
[Link] = id;
}
public String tostring() {
return sname;
}
}
package Student;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student (Ram,12);
[Link](s1);//object class student @ 3d on address of object
}
}
2. Equals(obj):-
The equals method of object class is use to compare the reference of an object
Page No
JAVA NOTES
Date
package Student;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student (Ram,12);
Student s2 = new Student (Ram,12);
[Link](s1);
[Link](s2);
[Link]([Link](s2));//false
Student s3 = s2;
[Link]([Link](s3));//true
}
}
package Student;
public class Student {
public boolean equals (object o) {
Student s1 = (Student)o;
return this [Link](s1 sname) && [Link] ==[Link];
}
}
package Student;
HASHCODE METHOD:-
The return type of hash code method is int
The object class hash code method is used to given a unic integer value of object according to the refrance
Page No
JAVA NOTES
Date
package Student;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student (Ram,12);
Student s2 = new Student (Ram,12);
[Link]([Link]());
[Link]([Link]() );
}
}
After overriding hash code method it will return the intiger value on the basis of state of an object
}
package Student;
public class StudentDriver {
public static void main(String[] args) {
Student s1 = new Student (Ram,12);
Student s2 = new Student (Ram,12);
[Link]([Link]());
[Link]([Link]() );
}
}
ABSTACTION:-
It is a design process of hiding the replace enation and showing only declaration to the user is known
as abstraction
We can achieve a abstraction with the help of abstract classes and interface
We can provide implementation to the abstract component with the help of inheritance and method
Overriding
1. Abstract Modifier :-
2. Abstract Method:-
Note:-
Only the child class is response for given implementation two abstract method
3. Abstract Class:-
If the class is prefix with a abstract modifier then it is known as abstract class we cannot create
Note:-
If a class has at list one abstract method declare then it is monetary to make that class as an abstract class
An abstract class can have both abstract and concrete method (with body)
Ex:-
package newpackage;
abstract public class vehical {
abstract public void noofwheels();
abstract public void noofseats();
}
package newpackage;
abstract public class Car extends vehical
{
}
package newpackage;
public class Bike extends Car {
public void noofwheels()
{
[Link]("4 wheels");
}
public void noofseats()
{
[Link]("5 seats");
}
Page No
JAVA NOTES
Date
If a class extends abstract class then should be given implementation to all the abstract method of
Supper class
If inheriting class doesn’t like to give implementation to the abstract method of supper class then it is
If subclass is also becoming and abstract class then the next level child class is responsive is given
implementation to the abstract method
STEPS TO IMPLEMENTATION:-
Create a class
Concrete Class:-
The class which is not prefix with a abstract keyword and which does not content any abstract method
is known as concrete class
Note:-
Concrete Method:-
package newpackage;
abstract public class Bank {
abstract public void cAccount();
abstract public void changeMno();
}
Page No
JAVA NOTES
Date
package newpackage;
abstract public class SBI extends Bank
{
package newpackage;
public class Axis extends SBI {
public void cAccount()
{
[Link]("Account is creted");
}
public void changeMno()
{
[Link]("mobil no change succesfully");
}
public static void main(String[] args) {
Axis a = new Axis();
[Link]();
[Link]();
}
}
INTERFACE
It is a component in java which is use to achieve 100% abstraction with multiple implementation
Note:-
When an interface is compile we will get a class with class extension
Interface by default abstraction
Member Class
Static variable Yes Yes but only final static variable
Example:-
package project1;
public interface Demo1 {
int a;//CTE variable is by default public static variable must be initialize
}
package project1;
public interface Demo2 {
public void test()//CTE
{
}
}
package project1;
public interface Demo3 {
public static void main(String[] args) {
[Link]("Hello world");
}
}
PURPUSE OF INTERFACE:-
To achieve 100% abstraction because concrete non-static method are not allowed in interface
Note:-
Only static method of interface cannot be inherited to both the child class and child interface
Inheritance with respect to interface and interface can inherit any number of interface with the help of
extends key word
package project1;
public interface int1 {
}
package project1;
public interface int2 {
}
Note:-
The interface which is inheriting an another interface should not give implementation (0
Ex:-
2-nonstatic (t1(),t2())
1-static (t5())
Page No
JAVA NOTES
Date
Note:-
Rezone:-
Note:-
If a class inherit and interface then it should give implementation to the abstract method of an interface
If the class is not ready to give then it mandatory to make that class as an abstract class
Next level of child class responsible abstract method of an interface
The diamond problem is solved by implementing multiple interfaces by the class at a time
Rezone:-
Non-static method are not implemented in an inherit static method are not inherit
Page No
JAVA NOTES
Date
RULE:-
Rezone:-
PACKAGES:-
ADVANTAGES PACKAGES:-
Packages is use to avoid name conflate
It increases maintainability
TYPES OF PACKAGES:-
We have two types of package
1. User-defined
2. Belding package
1. USER-DEFINED PACKAGE:-
The package which is created by programmer and user is known as user- defined package
2. BELDING PACKAGE:-
Java-package
Util-sub-package
Scanner-class
1) SUB PACKAGE:-
Package inside package is called as sub package
Note:-
We can also create a user defined sub package
Page No
JAVA NOTES
Date
2. Import statement
There is one class name as scanner class is use to take input from user the fully qualified name is java. utill.
scanner
Create object for scanner class by using its fully qualified name
By using fully qualified name compiler will understand scanner class belong to java. Utill package
Readability is low
To overcome this we can use a class by using import statement
Import statement is use to import classes or interfaces present in specific package or sub package
Import java. Utill . scanner ;
By using import statement in state of using fully qualified name of class we can directly use class name
We can directly use the class name instead of fully qualified name
By importing package one we can use class interface as many times as possible
Page No
JAVA NOTES
Date
Note:-
ACCESS MODIFIRES:-
1) Private
2) Default
3) Protected
4) Public
1) PRIVATE:-
If a member of class its prefix with private modifier then it is accessibility only within the class out-side the
class not possible
2) DEFAULT:-
The accessibility of default modifier is only within the package it can’t be access
If use don’t declare any access modifier then it is as consider as default access modifier
3) PROTECTED:-
The access level of protected modifier is within the package and outside the package throw child class
If you do-not make child class it cannot be access outside the package
4) PUBLIC:-
The access level of public modifier is any
It can be access within the class outside class within package outside package
Page No
JAVA NOTES
Date
Access Modifier Within Class Within Package Outside Package Outside Package By Children
Private True False False False
In java . utill . arrays class we have a static method which can access the array
The sort method uses compare to method of comparable interface for sorting
Any one of the above condition are not followed then we will get class cast exception
COMPARABLE INTERFACE:-
Comparable interface is functional interface (only one abstract method )
COMPARE TO MATHOD:-
It is defied in comparable interface
WORK FLOW:-
If type value one object is greater than another object it will return position integer
If the value of one object is lesser than another object it will return negative integer
If value of one object is equal to another object it will return zero
Program:-
STRING (LITTERAL):-
Anything unclosed in a double code in java will be consider as a string literal is used in a java program an
instants of java land string class is created inside string constant pull
For given string literal if the instants of string is already present then new instant is not created instead of
STRING:-
String is a data and group of character which is in-close within a double cote
It is a non-primitive data
In java data we can store a string by creating instance of following closes
In java whenever we create a string compiler implicitly create and instant of java. Lang. string in string
Diagram:-
package StringClass;
public class Test1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
[Link](s1);//Hello
[Link](s2);//Hello
[Link](s1==s2);//true
[Link]([Link](s2));//true
}
}
Diagram:-
Page No
JAVA NOTES
Date
STRING CLASS:-
In string class to string method equals method and hash code method of object class use over return it
implement
package StringClass;
public class Test2 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String ("Hello");
[Link](s1==s2);//false
[Link]([Link](s2));//true
}
}
Diagram:-
package StringClass;
public class Test3 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "hello";
String s3 = new String ("Hello");
String s4 ="hello";
String s5 = new String ("Hello World");
[Link](s1=s3);//Hello
[Link]([Link](s3));//false
[Link]([Link](s4));//true
[Link]([Link](s5));//false
}
}
Page No
JAVA NOTES
Date
Diagram:-
package StringClass;
public class Test4 {
public static void main(String[] args) {
String s1 = "hello";
[Link]([Link]());//Hello
[Link](s1);//hello
}
}
Diagram:-
Page No
JAVA NOTES
Date
CONSTRUCTER:-
Constructer Description
String() Create an empty string object
Type
String ToupperCase() Convert the special string upper case
String tolowerCase() Convert the special string lower case
String Trim() Remove the space precast before and after
String Substring(int,index) Extract char from string object start from special index and end
1-string
Char charAt(int index) Return char of the specified index from string
Int IndexOf(char ch) Return the index of the character specified if not return -1
Int IndexOf(char,ch,int, Return the index of the character specification by searching
Int indexOf(char, sequence start) Return the index of the specified string index if not return -1
Int IndexOf(char,sequence string Return the index of the specified string searching from specified
Int lastIndexOf(char ch) Return the index of the character which is occurred at least in the
original string
Boolean Contains(string str) Return true if specified string is present else it returns false
1) package StringClass;
public class Test5 {
public static void main(String[] args) {
String s1 = "Hello";
[Link]([Link]());//hello
}
}
2) package StringClass;
public class Test6 {
public static void main(String[] args) {
String s1 = "Hello";
[Link]([Link]("world"));//Helloworld
}
}
3)
package StringClass;
public class Test7 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]());//Hello
}
}
4)
package StringClass;
public class Test8 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link](1));//ello
}
}
5)
package StringClass;
public class Test9 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link](1, 4));//ell
}
}
6) package StringClass;
public class Test10 {
public static void main(String[] args) {
Page No
JAVA NOTES
Date
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link](2));//l
}
}
7)
package StringClass;
public class Test11 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]('l'));//2
}
}
8)
package StringClass;
public class Test12 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]('e',1 ));//1
}
}
9)
package StringClass;
public class Test13 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]('o'));//4
}
}
10)
package StringClass;
public class Test14 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]('H'));//0
}
}
11)
package StringClass;
public class Test15 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]('l'));//2
}
}
Page No
JAVA NOTES
Date
12)
package StringClass;
public class Test16 {
public static void main(String[] args) {
String s1 = "Hello";
[Link](s1);//Hello
[Link]([Link]());//5
}
}
13)
package StringClass;
public class Test17 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "hello";
[Link](s2);//hello
[Link]([Link](s2));//true
}
}
CHARACTERISTICS OF STRING:-
The instance of string class is immutable in nature once the object is created then state cannot be modify
If we try to modify it will directly create new object and reference to the new object
COMPARISEN OF STRING:-
1) ==Operator:- compares the reference
2) = Equal Method:- compare the state
3) Equal Ignore Case():- compare the state by ignore its case
Page No
JAVA NOTES
Date
4) Compare To Method:- compares the string and returns the integer value
DISADVANTAGE:-
Because of in mutability for avery modification its create new object to overcome this problem we use string
buffer
STRUNG BUFFER:-
Constructer Description
StringBuffer() Create string with initial capacity 16
package StringBuffer;
public class Test {
public static void main(String[] args) {
StringBuffer s2 = new StringBuffer("Bye");
StringBuffer s1 = new StringBuffer("Bye");
[Link](s2);//Bye
[Link](s1);//Bye
[Link](s1==s2);//false
[Link]([Link](s2));//false
}
}
package StringBuffer;
public class Test1 {
public static void main(String[] args) {
StringBuffer s2 = new StringBuffer("Hello");
[Link]("world");
[Link](s2);//Helloworld
}
}
Type
String Buffer Insert(int, index, string ) Insert a specified string into original string of specified index
String Buffer Delete(int begin, int end) Delete string from specified beginning index to end -1index
String Buffer deleteCharAt(int index) Delete the character present in the specified index
String Buffer Set length(int length ) Only specified length in a string is exist remaining get
remove
String Buffer Substring(int begin) Return the sub string from the specified beginning index
String Buffer Substring (int begine int end) Return the specified string from the beginning index to end
1 index
String Buffer Replace(int begin int end Replace a specified string from the beginner index to end
String s) -1 index
Void TrimtoSize() Remove the unused capacity of set the capacity till length at
The string
Void Set Char At(int index char Replace the new character in a string of specified index
new char)
1) package StringBuffer;
public class Test2 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link]());//21
}
}
2) package StringBuffer;
public class Test3 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link]());//5
}
}
3) package StringBuffer;
public class Test4 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](3));//l
}
}
4) package StringBuffer;
public class Test5 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](2, "ok"));//Heokllo
}
}
Page No
JAVA NOTES
Date
5) package StringBuffer;
public class Test6 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](1, 4));//Ho
}
}
6) package StringBuffer;
public class Test7 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](2));//Helo
}
}
7) package StringBuffer;
public class Test8 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link]());//olleH
}
}
8)
package StringBuffer;
public class Test9 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link](3);
[Link](s1);//Hel
}
}
9) package StringBuffer;
public class Test10 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](2));//llo
}
}
10) package StringBuffer;
public class Test11 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](1, 4));//ell
}
}
11) package StringBuffer;
public class Test12 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
[Link]([Link](1, 4, "ok"));//Hoko
}
}
Page No
JAVA NOTES
Date
STRING BUILDER:-
String Builder in java is a class used to create a mutable or in other words a modifiable succession of characters
like string Buffer the string builder class is fan alternative to the java string class as the string class provides an
Constructor Description
String Builder(int capacity) It create and empty string builder with the specified capacity
String Builder(char sequence seq) It create a string builder with the same character specified as the argument
String builder (string str) It will construct a string builder with the string specified in the argument
Page No
JAVA NOTES
Date
USE OF METHOD:-
Int capacity
charcharAt(int index)
Int length ()
Void trimTosize()
EXCEPTION:-
The exception is a problem that occurs during execution of a program (runtime)
When an exception occurs the execution of a program stop abnormal (suddenly)
Note:-
Every exception in java is a class of throwable tip
Diagram:-
Page No
JAVA NOTES
Date
Note:-
1) ARITHMATIC EXCEPTION :-
package Exception;
public class Test {
public static void main(String[] args) {
[Link]("Mani strart");
int a = 10;
int b = 0;
int res = a/b;//Arithmatic exception
[Link](res);
[Link]("main end" );
}
}
package Exception;
public class Test1 {
public static void main(String[] args) {
[Link]("main start");
int a[] = {10,20,30};
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link](a[3]);//ARRAY INDEX OUT OF BOUNDS EXCEPTION
[Link]("main end");
}
}
package Exception;
public class Test2 {
public static void main(String[] args) {
[Link]("main start");
String a = "Hello";
[Link]([Link](5));//StringIndexOutOfBoundsException
[Link]("main end");
}
}
[Link]([Link]());//NullPointerException
[Link]("Main end");
}
}
TROWABLE CLASS:-
In all the exception classes to string method is already overridden such that it will return the fully callefied
name of the exception class
1) Checked
2) Unchecked exception
1) CHECKED EXCEPTION:-
In checked exception compiler known the statement which is responsible for abnormal situation (exception)
There for compiler forces the programmer to either handle or declare the exception if it is not done we will
2) UNCHECKED EXCEPTION:-
In unchecked exception compiler doesn’t know the statement which is responsible for abnormal situation
(exception) hence compiler does not force the programmer to either handle or declare the exception
Note:-
In throw able hierarchy error class and sub classes runtime exception class and it sub classes are all consider as
a unchecked exception
All the subclasses of exception class except runtime exception is considered as checked exception
Throw able and exception class is partially check and partially unchecked
EXCEPTION HANDLING:-
Exception handling is a mechanism used in java which is used to continue the normal flow of exception occur
during runtime
Syntax:-
Try
{
Responsible statement
{ instruction
}
Page No
JAVA NOTES
Date
Try:-
The statement which are responsible for exception should be return inside tray black
CATH BLOCK:-
The catch block is used to catch the throw able tip reference thrown by the tray block
If it catches we say the exception is handle and the statement inside catch of program will continue
If it doesn’t catch we say the exception is catch block well not get execution and again program will slop
abstractly
package Exception;
import [Link];
public class Test4 {
public static void main(String[] args) {
Scanner sc = new Scanner ([Link]);
String s1 = null;
try {
[Link]([Link]());
}
catch(NullPointofException k ) {
[Link]("somthing went wrong");
}
}
}
Try
{
}
Catch()
{
Catch()
{
Note:-
WORK FLOW:-
Try
{
Page No
JAVA NOTES
Date
Catch(----)
{
}
Catch(----) If the exception is caught by the catch block then try block does not throw the exception
{ Object to the below catch block
Catch(---)
The order of catch block should be maintained such that child type should be an the top and parent type at the
Bottom
Case1 Case 2
Try Try
{ 10/0; {10/0;
} }
Catch(exception e) Catch (arithmetic exception e)
{ {
} }
Catch(Arithmetic exception e ) Catch (exception e)
{ {
} }
CTE:- parent type is declare on the tip and CTE:- parent type declare on try bottom and child type is the top
object program
Page No
JAVA NOTES
Date
THROWS KEYWORD :-
Throw keyword is used to declare and exception to be thrown to the called throws keyword should be used in
Method declaration
Note:-
Then caller of the method must handle or throw the exception if will not get compile time error
Program:-
package Exception;
public class Test5 {
public static void main (String[]args)
{
div ();
}
public static void div() throws RuntimeException
{
int a = 3;
int b =0;
int r =a/b;
[Link](r);
}
}
FINALLY BLOCK:-
Syntax:-
Try
Catch()
{
Page No
JAVA NOTES
Date
Finally
1. Finally is a block which is used along with try and catch block
2. It will execute even the exception is handle and it will execute even the exception is not handle
THROW KEYWORD:-
By using throw we can throw cheeked exception unchecked throw exception it is manly used to customize
Exception
Ex (Program):-
package Exception;
public class AlreadLogedInException extends RuntimeException {
public String getMassage() {
return "cannot login again...." ;
}
}
public void login(user u)
{
if(this.u==null)
{
this.u=u;
[Link]("login successfully");
}
else
{
throw new AlreadyLoggedInException ();
}
}
package Exception;
public class Test6 {
public static void main (String[]args){
[Link]("main Start");
String s1 = null;
if (s1 ==null){
throw new NullPointerException();
}
else{
[Link]([Link]());
}
}
}
Page No
JAVA NOTES
Date
WRAPPER CLASS:-
short Short
int Int
long Long
float Float
double Double
boolean Boolean
char Char
BOXING:-
The process of wrapping primitive value in to corresponding wrapper class is known as boxing
UNBOXING:-
The process of un-wrapping the wrapper clad object in to the primitive value
VALUE METHOD:-
Value method with help us to un-wrapper the wrapper class object in to primitive value
int a2 = [Link]();
[Link](a2);
char ch1 = [Link]();//un-boxing
[Link](ch1);
PARSING:-
It is a process converting given string into primitive
Perform parsing we need to take a help of parse method which is present in all the 7th wrapper classes except
Character
package WrapperClass;
public class Test {
public static void main(String[] args) {
String s1="10";
[Link](s1);
int a1 = [Link](s1);
[Link](a1);
}
}
Page No
JAVA NOTES
Date
Note:-
Note:-
If any data pass other than true we will get output as a false
AUTO BOXING:-
The process of implicitly converting a primitive value in to corresponding wrapper class object is known as auto
boxing
AUTO UNBOXING:-
The process of implicitly converting object in to primitive value is known as auto unboxing
COLLECTION :-
PURPUS OF COLLECTION:-
The size of array is fixed we cannot reduce and increase the size of array dynamically during execution of
program
There for to avoid limitation to array we can store in deferent data structure ex:- list, set, queue, map
COLLECTION FRAMWORK:-
Collection framework is a set of class of collection which provides mechanism to store group of object
(element)
Page No
JAVA NOTES
Date
4. Search element
5. Update element
6. Sort element
1. Collection hierarchy
2. Map hierarchy
COLLECTION INTERFACE:-
Collection interface is defined in java utill package
All the element in collection of stored in from of object (only non-primitive alive )
Which help to programmer to perform following task
Remove All(collection)
Retain All(collection)
Clear()
IsEmpty()
Hash code ()
Equals()
1. LIST:-
CHARACTERSTIC:-
List is collection of object
Indexing called in list hence we list adding, accessing, removing element using index
2. Add All(collection)
=================
4. AddAll(int index,object)
2. ContainsAll(collection)
===================
3. Iindexof(object)
2. RemoveAll(collection)
3. RemoveAll(collection)
4. Clear()
========================
5. Remove(int index)
=====================
2. List iterator()
Misscelle 1. Size()
2. Is Emty()
3.
4. hashCode()
5. equal()
package collectio;
import [Link];
public class Test {
public static void main(String[] args) {
ArrayList a1 = new ArrayList <>();
Page No
JAVA NOTES
Date
[Link](10);
[Link]("ok");
[Link](true);
[Link]('e');
[Link](10);
[Link](null);
[Link](a1);//[10,ok,true,e,10,null]
[Link](2, 8.5);
[Link](a1);//[10,ok,8.5,true,e,10,null]
ArrayList a2 = new ArrayList<>();
[Link](false);
[Link](5.4);
[Link](1, a1);
[Link](a2);//[false, 10, ok, true, e, 5.4]
[Link]([Link]("Ok"));//false
[Link]([Link](a1));//true
[Link]([Link]("true"));//-1
[Link]([Link]("ok"));//true
[Link](a1);
[Link](a2);//[false,ok,5.4]
[Link](a1);
[Link](a2);//[10,ok,true,e]
[Link]();
[Link](a1);//[]
[Link](1);
[Link](a1);//[10,true,e,10,null]
}
}
We can create the instance of array list and use all the method
Array list(collection):-create an array list object and copy all the values from one collection another collection
Note:-
In array list to string method is over ridden instead of string return of array list it will return array list
ITERATOR :-
Iterator method create iterator type object and return the reassurance
Page No
JAVA NOTES
Date
1) hashnext()
This method is use to chaek whether there is element to be access from collection is present or
not
This method is use to access the element and move the cursor to next element
package collectio;
import [Link];
import [Link];
public class Test1 {
public static void main(String[] args) {
ArrayList a1 = new ArrayList <>();
[Link](10);
[Link]("ok");
[Link](true);
[Link]('e');
[Link](a1);
Iterator i = [Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
NO SUCH ELEMENT EXEPTION:-
In the exception itratore when we tag to access the element using next method and it there is no element
DISADVANTAGE:-
We can iterate only one we cannot access the element in-reverse order to overcame this this advantage we go
LIST ETRATOR:-
List iterator is a method which belongs to list interface
Next():-this method gives the element from current position and move thecursal forward
has Privies():-this method is used to cheak wheter the priviuse element to be accessed is present or not
Privies():-gives the priviuse element of the curser and more the curser backword
package collectio;
import [Link];
import [Link];
import [Link];
public class Test2 {
public static void main(String[] args) {
ArrayList a1 = new ArrayList <>();
[Link](10);
[Link]("ok");
[Link](true);
[Link]('e');
[Link](a1);//[10, ok, true, e]
ListIterator l1 = [Link]();
[Link]([Link]());//true
[Link]([Link]());//10
[Link]([Link]());//true
[Link]([Link]());//ok
[Link]([Link]());//true
[Link]([Link]());//ok
[Link]([Link]());//true
[Link]([Link]());//10
[Link]([Link]());//false
[Link]([Link]());//NoSuchElementException
}
}
get(int index):-
package collectio;
import [Link];
public class Test3 {
public static void main(String[] args) {
ArrayList a1 = new ArrayList <>();
[Link](10);
[Link]("ok");
[Link](true);
[Link]('e');
[Link](a1);//[10, ok, true, e]
[Link]([Link](2));//true
}
}
Page No
JAVA NOTES
Date
main(String[] args) {
public static void
}
0);
[Link](
for (object 0:a1){
true, e]
a1);//[10, ok,
[Link](
[Link]('e');
[Link](true);
[Link]("ok");
[Link](10);
ArrayList <>();
ArrayList a1 = new
Size():-
[Link]( [Link]() );
isEmpty():-
[Link]( [Link]() );
has Code():-
[Link]([Link]());
Equals():-
[Link]([Link]( a1 ));
2. non-generic collection
NON-GENERIC COLLECTION:-
Is a hetorogeneus (defferent type )collection of element every element is converted and stored as an inside
Non-generic collection
GENERIC COLLECTION:-
Is a homogeneus collection of element
package collectio;
import [Link];
public class Test4 {
public static void main(String[] args) {
ArrayList <Integer> a1 = new ArrayList <Integer>();
[Link](10);
[Link]("ok");//CTE
Page No
JAVA NOTES
Date
[Link](38);
[Link](89);
[Link](a1);
}
}
LINK LIST:-
help of address
We can add the element or remove the element in between the list very easily
CHARACTERISTIC OF LINK LIST:-
Inside order duplicate values
package collectio;
import [Link];
public class Test5 {
public static void main(String[] args) {
ArrayList a1 = new ArrayList <Integer>();
[Link](10);
[Link]("ok");
[Link](true);
[Link]('e');
[Link](a1);
[Link](2, 7.5);
[Link](a1 );
}
}
0x1
0x2
0x3
0x4
0x3 object
null
0x5
package collectio;
public class student {
int id;
String sName;
int std;
public student (int id,String sName,int std) {
[Link] = id;
[Link] = sName;
[Link] = std;
}
public String toString() {
return "Student id : " + id + "\nStudent Name : " + sName + "\nstd : " + std;
}
}
package collectio;
import [Link];
import [Link];
public class School {
student s;
Scanner sc = new Scanner ([Link]);
ArrayList<student> a = new ArrayList<student>();
String schoolName = "S. N. R. Highschool";
public void takeAdmission () {
[Link]("Enter the id for Admission");
int id = [Link]();
[Link]("Enter Student Name for Admission");
String sName = [Link]();
[Link]("Enter Standard");
int std = [Link]();
s=new student(id, sName, std);
[Link](s);
[Link]("Admission Are Done Successfully...");
}
public void cancelAdmission() {
[Link]("Enter the id For Cancel the Admission");
int id = [Link]();
for (student m : a) {
if (id==[Link]) {
Page No
JAVA NOTES
Date
[Link]([Link](s));
[Link]("Admission Cancelled Successfullyyy...");
return;
}
}
[Link]("its Id Does Not Exist");
}
public void displayDetails () {
[Link]("Enter the id For Access Details Of Student Admission");
int id = [Link]();
for (student m : a) {
if (id==[Link]) {
[Link]("School Name :--->>>"+schoolName);
[Link](m);
return;
}
}
[Link]("its Id Does Not Exist");
}
public void UpdateDetails () {
[Link]("Enter Id For Update Details");
int id = [Link]();
for (student m : a) {
if (id==[Link]) {
[Link]("What you Want To Update..\n1. Id\n2. Name\n3. Std\n4.
All");
int i = [Link]();
switch (i) {
case 1 : {
[Link]("Enter New Id");
int newId = [Link]();
[Link]=newId;
[Link]("Id succefully updated");
}
break;
case 2 : {
[Link]("Enter New Name");
String newName = [Link]();
[Link]=newName;
[Link]("Name succefully updated");
}
break;
case 3 : {
[Link]("Enter New Std");
int newStd = [Link]();
[Link]=newStd;
[Link]("Std succefully updated");
}
break;
case 4 : {
[Link]("Enter New Id");
int newId = [Link]();
[Link]=newId;
[Link]("Enter New Name");
String newName = [Link]();
[Link]=newName;
[Link]("Enter New Std");
Page No
JAVA NOTES
Date
package collectio;
import [Link];
public class SchoolDriver {
public static void main(String[] args) {
Scanner sc = new Scanner ([Link]);
School ref = new School ();
boolean condition = true;
while (condition) {
[Link]("Enter The Choice\n1. Take Admisssion\n2. Cancel Admission\n3.
Display Details\n4. Update Details\n5. Exit");
int choice = [Link]();
switch(choice) {
case 1 : [Link]();
break;
case 2 : [Link]();
break;
case 3 : [Link]();
break;
case 4 : [Link]();
break;
case 5 : {
condition = false;
[Link]("Its Closed Now :)");
}
break;
default : {
[Link]("Enter valid choice :(");
}
}
}
}
}
package collectio;
public class Account {
String name;
long acno;
String branch;
Page No
JAVA NOTES
Date
long cno;
double balance;
int pswd;
public Account(String name, long acno, String branch, long cno, double balance,int
pswd) {
[Link] = name;
[Link] = acno;
[Link] = branch;
[Link] = cno;
[Link] = balance;
[Link] = pswd;
}
public String toString() {
return "Account Holder Name : " + name + "\nAccount Number : " + acno + "\nBranch :
" + branch + "\nContact Number : " + cno;
}
}
package collectio;
import [Link];
import [Link];
public class Bank {
Account a;
Scanner sc = new Scanner ([Link]);
ArrayList<Account> ar = new ArrayList<Account>();
String bankName = "Indian Bank";
public void createAccount() {
[Link]("Enter The Name : ");
String name = [Link]();
[Link]("Enter The Account Number : ");
long acno = [Link]();
[Link]("Enter The Branch : ");
String branch = [Link]();
[Link]("Enter The Contact Number : ");
long cno = [Link]();
[Link]("Enter The Balence : ");
double balence = [Link]();
[Link]("Enter The Passward/Pin : ");
int pswd = [Link]();
a = new Account (name,acno,branch,cno,balence,pswd);
[Link](a);
[Link]("Account Created Successfully...");
}
public void cancelAccount() {
[Link]("Enter the Name And Passward For Cancelling Account");
[Link]("Name : ");
String name = [Link]();
[Link]("Passward : ");
int pswd = [Link]();
for (Account m : ar) {
if ([Link]([Link]) && pswd==[Link]) {
[Link]([Link](a));
[Link]("Admission Cancelled Successfullyyy...");
return;
}
Page No
JAVA NOTES
Date
}
[Link]("its Name/Passward Does Not Exist :(");
}
public void updateDetails() {
[Link]("Enter the Name And Passward For Update Account Details");
[Link]("Name : ");
String name = [Link]();
[Link]("Passward : ");
int pswd = [Link]();
for (Account m : ar) {
if ([Link]([Link]) && pswd==[Link]) {
[Link]("Enter New Branch");
String newBranch = [Link]();
[Link] = newBranch;
[Link]("Enter New Contact Number");
int newCno = [Link]();
[Link] = newCno;
[Link]("Details Updated Successfully :)");
return;
}
}
[Link]("its Name/Passward Does Not Exist :(");
}
public void displayDetails () {
[Link]("Enter the Name And Passward For Display Account Details");
[Link]("Name : ");
String name = [Link]();
[Link]("Passward : ");
int pswd = [Link]();
for (Account m : ar) {
if ([Link]([Link]) && pswd==[Link]) {
[Link]("Bank Name --->>>> "+bankName);
[Link](m);
return;
}
}
[Link]("its Name/Passward Does Not Exist :(");
}
public void changePassward () {
[Link]("Enter the Account Name And Old Passward For Change The
Passward");
[Link]("Name : ");
String name = [Link]();
[Link]("Passward : ");
int pswd = [Link]();
for (Account m : ar) {
if ([Link]([Link]) && pswd==[Link]) {
[Link]("Enter new Passward");
int newPswd = [Link]();
[Link] = newPswd;
[Link]("Passward Changed Successfully :)");
return;
}
}
[Link]("its Name/Passward Does Not Exist :(");
}
public void withdrawAmount () {
Page No
JAVA NOTES
Date
package collectio;
import [Link];
public class BankDriver {
public static void main(String[] args) {
Bank ref = new Bank();
Scanner sc = new Scanner ([Link]);
boolean condition = true;
while (condition) {
[Link]("Enter the choice\n1. Creat Account \n2. Cancel Account\n3.
Update Details\n4. Display Detalis\n5. Change Passward\n6. Withdraw Amount\n7.
Deposite Amount\n8. Display Balance\n9. Exit ");
int choice = [Link]();
switch(choice) {
case 1 : [Link]();
break;
case 2 : [Link]();
break;
case 3 : [Link]();
break;
case 4 : [Link]();
break;
case 5 : [Link]();
break;
case 6 : [Link]();
break;
case 7 : [Link]();
break;
case 8 : [Link]();
break;
case 9 : {
condition = false;
[Link]("Application Closed.....");
}
break;
default : {
[Link]("Something Went Wrong !!....Please Try Again");
[Link]("-------------------------------------------");
}
}
}
}
}
VECTOR:-
Vector class is declear inside java utill package
Since vector is a implementation class of list interface data will be stored in to sequential manner and we can
STACK:-
Puss(object o) This method is use to add the new element at the top of the stack
Pop() This method is use to remove the and element from the top of stack
Search() This method is use to search the element position of an object the position will
package Stack;
import [Link];
public class Test {
public static void main(String[] args) {
Stack s1 = new Stack ();
[Link](false);
[Link](34);
[Link]("ok");
[Link]('f');
[Link](s1);
[Link]();
[Link](s1);
[Link]([Link]("ok"));
[Link]([Link]());
[Link]([Link]() );
}
}
SET:-
Set is interface and it is a sub interface of collection interface therefor all the method of collection are inheret
to set interface
CHARACTER OF SET:-
Set does not allow duplicate element
Page No
JAVA NOTES
Date
It has all the method inherited from collection as well as set interface
CHARACTER:-
HASH SET():-
package Stack;
import [Link];
public class Test1 {
public static void main(String[] args) {
HashSet h1 = new HashSet<>();
[Link](23);
[Link](false);
[Link]('f');
[Link]("Hello");
[Link](false);
[Link](null);
[Link](null);
[Link](h1 );
}
}
Note:-
It has all method inherited from collection Interface as well as set interface
CHATRACTERISTICS OF LINK HASH LIST:-
package Stack;
import [Link];
public class Test2 {
public static void main(String[] args) {
LinkedHashSet l1 = new LinkedHashSet<>();
[Link](45);
[Link](true);
[Link]('r');
[Link]("ok");
[Link](null);
}
}
TREE SET:-
Tree set is a concrite incrementing class of set interface
Tree set will also have all the method of collection interface
CHARACTER:-
The element will be sorted by defolt in tree set the element to be add in the tree set must be comparable type
Duplicate element are not allow in tree sate we cadn not use index in tree
We cannot add null value in tree set or else we will get null pointer exception
CONSTRUCTER:-
TREESET():-
TREEESET(COLLECTION):-
This constructer is use to copy all the value from one collection to tree set
Page No
JAVA NOTES
Date
package Stack;
import [Link];
public class Test3 {
public static void main(String[] args) {
TreeSet l1 = new TreeSet<>();
[Link](45);
[Link](true);
[Link]('r');
[Link]("ok");
[Link](null);
[Link](l1);
}
}
QUEUE:-
Queue injterface is a type of collection interface
i. Link list
Element() This method is used to return the head of queue if queue is empty it will return null
value
Remove() This method is use to remove the head of the queue if the queue is empty it will return
Priority queue can be used to perform operation in such maner which mines smallest element will be remove
first
We cannot add null value if we try to add will get null pointer exception
Page No
JAVA NOTES
Date
package collectio;
import [Link];
public class Test7 {
public static void main(String[] args) {
PriorityQueue q1 = new PriorityQueue<>();
[Link](10);
[Link](78);
[Link](45);
[Link](56);
[Link](q1);
[Link]();
[Link](q1);
[Link]();
[Link](q1 );
}
}
MAP:-
pairs.
Key cannot be duplicate.
put(key,value) It is use to add an entry into the Map. If key is already present the old value will
putAll (Map) This method is used to add entries in the existing Map into the current Map
Get(key) This Method will return the value associated with a particular key.
containsValue() It will return true or false Value is present -> true Value is not Present -> false
entrySet() It will return a set of key = Value pairs
HASHMAP :
CONSTRUCTORS OF HASHMAP :
HashMap It will create empty HashMap object
HashMap() It will create HashMap object and copies all the entries from passed Map into newly created
Map.
Note : We can create generic Map by specifying the type of key end value.
TREEMAP:-
It is a concrete implementing class of Map interface.
TreeMap() It will create TreeMap object and copies all the entries from passed Map into newly
created Map.
HASHTABLE :
CONSTRUCTORS OF HASHTABLE :
HashTable() It will create HashTable object and copies all the entries from passed Map into newly
created Map.
MULTI-TREADING:-
Exicuting multiple sub tasking and sub process simaltaniusly by multiple thread is known as multi treading
MULTI-PROCESSING:-
THREAD CLASS:-
RUNNEBLE INTERFACE:-
Runnable interface is also declared in java lang package it is a functional interface which content only one
abstraction method
Thread class interface runnable interface we can create a thread by using two way
NEW :-
If develop create new thread then respected thread will be presented at new state
RUNEBLE:-
If developer calls start method and thread will enter in to runnable state it means thread is ready for
RUNNIG:-
Thread scheduler select one thread for execution and thread will inter in running state
NON-RUNNABLE:-
The thread execution is suspended by thread scheduler for particular time period
DEAD:-
In other word the thread will successfully execution JVM is automatically terminated into specific thread
THREA SHEDULAR:-
MAIN THREAD :-
Thread create by JVM is known as main thread and it will automatically created
Developer can create only number of executional thread with the help of main thread
Developer can create only number of execution thread with the help of main thread
Run():- perform the task of thread which is return inside run method
Current thread():- this method will return the object current thread