Professional Documents
Culture Documents
Language Fundamentals:
1. Variables/identifiers
2. Reserved keywords
3. Datatypes
4. literals
1.Identifiers
A name in java program is called as Identifier.This may be class name method name.....
int x=10;
int virat=18;
x --> identifier/variable
= --> operator
10 --> data(constant)/literal
; --> terminator
1. a to z
2. A to Z
3. 0-9
4. _
5. $
note: If we are using any other character we will get compile time error
18virat -->(invalid)
3. Java is case sensitive in case of identifiers it will threat the name as new one..!
int virat=18;
int VIRAT=19;
int Virat=20;
4. There is no length limit for java identifers but it just recommeded that in and around
Reserved Keyword:
In java some identifiers are reserved. Hence to associate some data and these words can not be considered as identifiers
in general programs.
Reserved keyword[53]
keywords
-->used keywords[48]
used keywords:
1.byte
2.short
3.int
4.float
5.double
6.char
7.long
8.boolean
1.if
2.else
3.switch
4.case
5.default
6.for
7.do
8.while
9.break
10.continue
11.return
1.public
2.private
3.protected
4.static
5.final
6.abstract
7.synchronized
8.native
9.strictfp
10.transient
11.volatile
1.try
2.catch
3.finally
4.throw
5.throws
6.assert
1.class
2.package
3.import
4.extends
5.implements
6.interface
-----------------------------
1.new
2.instanceOf
3.super
4.this
excerise:
7. sachinTendulker -->VALID
8. sachin_Tendulker -->VALID
9. sachin$Tendulker -->VALID
Java Features:
To show the nature of java programming language, JAVA has provided the following features.
1.Simple
2.Object Oriented
3.Platform independent
4.Arch Nuetral
5.Portable
6.Robust
7.Secure
8.Dynamic
9.Distributed
10.Multi Threadded
11.Interpretive
12.High Performance
1. Simple:
2.Java has removed all most all the confusion oriented features like pointers,multipleinheritance,.....
2. Object Oriented:
Java is an object oriented programming language, because, JAVA is able to store data in the form of Objects only.
3. Platform Independent:
Java is platform independent programming Language, because, Java allows its applications to compile on one
operating system and to execute on another operating system.
4. Arch Nuetral:
Java is an Arch Nuetral Programming language, because, Java allows its applications to compile
5. Portable:
Java is a portable programming language, because, JAVA is able to run its applications under all
6. Robust:
1.Java is having very good memory management system in the form of heap memory Management SYstem, it is a
dynamic memory management system, it allocates and deallocates memory for the objects at runtime.
2.JAVA is having very good Exception Handling mechanisms, because, Java has provided very good predefined
library to represent and handle almost all the frequently generated exceptions in java applications.
7. Secure:
1.JAVA has provided an implicit component inside JVM in the form of "Security Manager" to
2.JAVA has provided a seperate middleware service in the form of JAAS [Java Authetication
3.Java has provided very good predefined implementations for almost all well known network
security alg.
8. Dynamic:
If any programming language allows memory allocation for primitive data types at RUNTIME
JAVA is a dynamic programming language, because, JAVA allows memory allocation for primitive data types at
RUNTIME.
9. Distributed:
a)Standalone Applications
b)Distributed Applications
a)Standalone Applications:
If we design any java application with out using client-Server arch then that java application is
b)Distributed Applications:
If we design any java application on the basis of client-server arch then that java application is called as Distributed
application.
To prepare Distributed applications, JAVA has provided a seperate module that is "J2EE/JAVA EE".
It able to allow only one thread to execute the complete application,it follows sequential execution,
It able to allow more than one thread to execute application, It follows parallel execution, it will
JAVA is following Multi Thread Model, JAVA is able to provide very good environment to create
and execute more than one thread at a time, due to this reason, JAVA is Multi threaded
Programming Language.
11. Interpretive:
1.To check developers mistakes in java applications and to translate java program from High
JAVA is high performance programming language due to its rich set of features like Platform
Keywords or Reserved words are the words in a language that are used for some internal process or represent some
predefined actions. These words are therefore not allowed to use as a variable names or objects. Doing this will result
into a compile time error.
2.assert -Assert describes a predicate (a true–false statement) placed in a Java program to indicate that the developer
thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure
results, which typically causes execution to abort.
3. boolean – A data type that can hold True and False values only
8. char – A data type that can hold unsigned 16-bit Unicode characters
13. double – A data type that can hold 64-bit floating-point numbers
15. enum – A Java keyword used to declare an enumerated type. Enumerations extend the baseclass.
16. extends -Indicates that a class is derived from another class or interface
17. final -Indicates that a variable holds a constant value or that a method will not be overridden
18. finally -Indicates a block of code in a try-catch structure that will always be executed
19. float -A data type that holds a 32-bit floating-point number
24. instanceof -Indicates whether an object is an instance of a specific class or implements an interface
25. int – A data type that can hold a 32-bit signed integer
28. native -Specifies that a method is implemented with native (platform-specific) code
32. private -An access specifier indicating that a method or variable may be accessed only in the class it’s declared in
33. protected – An access specifier indicating that a method or variable may only be accessed in the class it’s declared
in (or a subclass of the class it’s declared in or other classes in the same package)
34. public – An access specifier used for classes, interfaces, methods, and variables indicating that an item is accessible
throughout the application (or where the class that defines it is accessible)
35. return -Sends control and possibly a return value back from a called method
37. static -Indicates that a variable or method is a class method (rather than being limited to one particular object)
38. strictfp – A Java keyword used to restrict the precision and rounding of floating point calculations to ensure
portability.
39. super – Refers to a class’s base class (used in a method or class constructor)
45. transient -Specifies that a variable is not part of an object’s persistent state
46. try -Starts a block of code that will be tested for exceptions
47. void -Specifies that a method does not have a return value
** The keywords const and goto are reserved, even they are not currently in use.
** true, false and null look like keywords, but in actual they are literals. However they still can’t be used as identifiers
in a program.
4. Identifiers should not be duplicated with in the same scope, identifiers may be duplicated in two different
scopes.
example:
class A{
void m1(){
5. In java applications, we can use all predefined class names and interface names as identifiers.
EX1:
int Exception=10;
System.out.println(Exception);
OP: 10
EX2:
String String="String";
System.out.println(String);
EX3:
int System=10;
System.out.println(System);
Reason: Once if we declare "System"[Class Name] as an integer variable then we must use that
"System" name as integer variable only in the remaining program, in the remaining program if we use
In the above context, if we want to use "System" as class name then we have to use its fully qualified .
2. Literals:
EX:
---
int a=10;
= ------> Operator
10 -----> constant[Literal].
To prepare java programs, JAVA has provioded the following set of literals.
3.Boolean Literals:
Note: JAVA7 has given a flexibility like to include '_' symbols in the middle of the literals inorder to
improve readability.
EX:
---
float f=12345678.2345f;
float f=1_23_45_678.2345f;
If we provide '_' symbols in the literals then compiler will remove all '_' symbols which we provided,
compiler will reformate that number as original number and compiler will process that number as original number.
IN general, in any programming language, to represent numbers we have to use a particular system .
In java , all number systems are allowed, but, the default number system in java applications is
If we want to represent numbers in Binary number system then we have to use 0's and 1's, but, the
Note: Binary Number system is not supported by all the java versions upto JAVA6, but , JAVA7 and
above versions are supporting Binary Number Systems, because, it is a new feature introduced in JAVA7 version.
2. Octal Number Systems[BASE-8]:
If we want to prepare numbers in Octal number System then we have to use the symbols like
EX:
---
If we want to represent numbers in Decimal number system then we have to use the symbols like
0,1,2,3,4,5,6,7,8 and 9 and number must not be prefixed with any symbols.
EX:
---
If we want to prepare numbers in Hexa decimal number system then we have to use the symbols like
0,1,2,3,4,5,6,7,8,9, a,b,c,d,e and f, but the number must be prefixed with either '0x' or '0X'.
EX:
---
recognize all the numbers and their number systems on the basis of their prefix values , compiler will
convert these numbers into decimal system and compilers will process that numbers as decimal
numbers.
Operators:
Operator is a symbol, it will perform a particular operation over the provided operands.
To prepare java applications, JAVA has provided the following list of operators.
1. Arithmetic Operators:
+, -, *, /, %, ++, --
2. Assignment Operators:
3. Comparision Operators:
&, |, ^
6. Short-Circuit Operators:
&&, ||
7. Ternary Operator:
Ex1:
-----
class Test
{
int a=10;
System.out.println(a);
System.out.println(a++);
System.out.println(++a);
System.out.println(a--);
System.out.println(--a);
System.out.println(a);
OP: 10
10
12
12
10
10
EX:
----
class Test
int a=5;
System.out.println(++a-++a);
OP: -1
EX:
----
class Test
int a=5;
System.out.println((--a+--a)*(++a-a--)+(--a+a--)*(++a+a++));
OP: 16
5. Data Types:
---------------
Java is strictly a typed programming language, where in java applicatins before representing data
first we have to confirm which type of data we representing. In this context, to represent type of
EX:
In java applications , data types are able to provide the following advatages.
EX: int i=10;--> int will provide 4 bytes of memory to store 10 value.
Reason: 'byte' data type is providing a particular range for its variables like -128 to 127, in
To prepare java applications, JAVA has provided the following data types.
If we want to identify range values for variablers onthe basis of data types then we have to use the
following formula.
n-1 n-1
-2 to 2 - 1
8-1 8-1
-2 to 2 - 1
77
-2 to 2 - 1
-128 to 128 - 1
-128 to 127
Note: This formula is applicable upto Integral data types, not applicable for other data types.
To identify "min value" and "max value" for each and every data type, JAVA has provided the
Note: Classes representation of primitive data types are called as Wrapper Classes
double-------------------> java.lang.Double
char---------------------> java.lang.Character
boolean------------------> java.lang.Boolean
Example:
class Sample{
System.out.println(Byte.MIN_VALUE+"----->"+Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE+"---->"+Short.MAX_VALUE);
System.out.println(Integer.MIN_VALUE+"----->"+Integer.MAX_VALUE);
System.out.println(Long.MIN_VALUE+"----->"+Long.MAX_VALUE);
System.out.println(Float.MIN_VALUE+"----->"+Float.MAX_VALUE);
System.out.println(Double.MIN_VALUE+"----->"+Double.MAX_VALUE);
System.out.println(Character.MIN_VALUE+"----->"+Character.MAX_VALUE);
//System.out.println(Boolean.MIN_VALUE+"----->"+Boolean.MAX_VALUE);---> Error
}}
Type Casting:
The process of converting data from one data type to another data type is called as "Type Casting".
The process of converting data from one primitive data type to another primitive data type is
The process of converting data from lower data type to higher data type is called as Implicit Type
Casting.
To cover all the possibilities of implicit type casting JAVA has provided the following chart.
124848
byte ---> short ---> int ---> long ---> float ---> double
^| char
If we want to perform implicit type casting in java applications then we have to assign lower data type
Example:
---------
byte b=10;
int i = b;
System.out.println(b+" "+i);
OP: 10 10
If we compile the above code, when compiler encounter the above assignment stattement then
compiler will check whether right side variable data type is compatible with left side variable data type
or not, if not, compiler will rise an error like "possible loss of precision". If right side variable data
type is compatible with left side variable data type then compiler will not rise any error and compiler
When we execute the above code, when JVM encounter the above assignment statement then JVM
1.JVM will convert right side variable data type to left side variable data type implicitly
2.JVM will copy the value from right side variable to left side variable.
Note: Type Checking is the responsibility of compiler and Type Casting is the responsibility of JVM.
Example:
--------
class Sample
int i=10;
byte b=i;
System.out.println(i+" "+b);
Example:
class Sample
byte b=65;
char c=b;
System.out.println(b+" "+c);
}
Status: Compilation Error
Example:
--------
class Sample
char c='A';
short s=c;
System.out.println(c+" "+s);
Reason: byte and short internal data representations are not compatible to convert into char.
Example:
--------
class Sample
char c='A';
int i=c;
System.out.println(c+" "+i);
OP: A 65
class Sample
byte b=128;
System.out.println(b);
Reason: When we assign a value to a variable of data type, if the value is greater the max limit of the
left side variable data type then that value is treated as of the next higher data type value.
Note: For both byte and short next higher data type is int only.
Example:
class Sample
byte b1=60;
byte b2=70;
byte b3=b1+b2;
System.out.println(b3);
Example:
---------
class Sample
byte b1=30;
byte b2=30;
byte b3=b1+b2;
System.out.println(b3);
X+Y=Z
2.If either X or Y or both X and Y belongs to {long, float, double} then Z should be higher(X,Y).
byte+byte=int
byte+short=int
short+int=int
byte+long=long
long+float=float
float+double=double
Example:
class Sample
long l=10;
float f=l;
System.out.println(l+" "+f);
OP: 10 10.0
Example:
---------
class Sample
float f=22.22f;
long l=f;
System.out.println(f+" "+l);
The process of converting data from higher data type to lower data type is called as Explicit Type
Casting.
P a = (Q) b;
Where P and Q are two primitive data types, where Q must be either same as P or lower than P as
Example:
--------
class Sample
int i=10;
byte b=(byte)i;
System.out.println(i+" "+b);
OP: 10 10
example:
class Demo
int i=130;
byte b=(byte)i;
System.out.println(i+" "+b);
When we compile the above code, when compiler encounter the above assignment statement, compiler will check
whether cast operator provided data type is compatible with left side variable data type or not, if not, compiler will rise
an error like "Possible loss of precision". If cast operator provided data type is compatible with left side variable data
type then compiler will not rise any error and compiler will not perform type casting.
When we execute the above program, when JVM encounter the above assignment statement then JVM will perform
two actions.
1.JVM will convert right side variable data type to cast operator provided data type.
2.JVM will copy value from right side variable to left side variable
-----------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------
Java Statements:
2. Conditional Statements:
-->1. if
-->2. switch
3. Iterative Statements:
-->1. for
-->2. while
-->3. do-while
4. Transfer statements:
-->1. break
-->2. continue
-->3. return
-->throw, try-catch-finally
6. Synchronized statements:
1.synchronized methods
2.synchronized blocks
Conditional Statements:
These statements are able to allow to execute a block of instructions under a particular condition.
Example:
--------
1. if
2. switch
1. if:
------
syntax-1:
---------
if(condition)
---instructions----
Syntax-2:
---------
if(condition)
---instuctions----
else
{
----instructions----
Syntax-3:
---------
if(condition)
---instructions----
else if(condition)
---instruction----
else if(condition)
---instructions----
----
----
else
----instructions----
Example:
--------
class Test
int i=10;
int j;
if(i==10)
j=20;
else
j=30;
System.out.println(j);
OP: 20
Example:
---------
class Demo
int i=10;
int j;
if(i==10)
j=20;
else if(i==20)
j=30;
else
j=40;
System.out.println(j);
}
OP: 20
Example:
--------
class Test
int j;
if(i == 10)
j=20;
System.out.println(j);
}}
OP: 20
EX6:
class Demo
int j;
if(true)
j=20;
System.out.println(j);
}
}
Reasons:
1.In java applications, only class level variables are having default values, local variables are not
having default values. If we declare local variables in java applications then we must provide
initializations for that local variables explicitlty, if we access any local variable with out having
initialization explicitly then compiler will rise an error like "Variable x might not have been
initialized".
class Demo
int j;
if(false)
j=20;
else
j=30;
System.out.println(j);
op : 30
EX:
class A{
void m1(){
System.out.println(i);// OP: 0
//System.out.println(j);--> Error
j=20;
System.out.println(j);---> No Error
Note: Local variables must be declared in side methods, blocks, if conditions,... and these variables are
having scope upto that method only, not having scope to outside of that method. Class level variables
are declare at class level that is in out side of the methods, blocks,.... these variables are having scope
through out the clsas that is in all methods, in all blocks which we provided in the respective class.
switch
'if' is able to provide single condition checking bydefault, but, switch is able to provide multiple
conditions checkings.
Syntax:
--------
switch(Var)
case 1:
-----instructions-----
break;
case 2:
----instructions------
break;
----
----
case n:
----instructions-----
break;
default:
----instructions-----
break;
Example:
---------
class Demo
int i=10;
switch(i)
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
break;
case 15:
System.out.println("Fifteen");
break;
case 20:
System.out.println("Twenty");
break;
default:
System.out.println("Default");
break;
Op:Ten
1.switch is able to allow the data types like byte, short, int and char.
Example:
---------
byte b=10;
switch(b)
----
Example:
---------
long l=10;
switch(l)
----
Example:
---------
class Demo
char c='B';
switch(c)
case 'A':
System.out.println("Five");
break;
case 'B':
System.out.println("Ten");
break;
case 'C':
System.out.println("Fifteen");
break;
case 'D':
System.out.println("Twenty");
break;
default:
System.out.println("Default");
break;
*Upto JAVA6 version, switch is not allowing "String" data type as parameter, "JAVA7" version
Example:
---------
class Demo
String str="BBB";
switch(str)
case "AAA":
System.out.println("AAA");
break;
case "BBB":
System.out.println("BBB");
break;
case "CCC":
System.out.println("CCC");
break;
case "DDD":
System.out.println("DDD");
break;
default:
System.out.println("Default");
break;
OP: BBB
2. In switch, all cases and default are optional, we can write switch with out cases and with default, we
can write switch with cases and with out default, we can write switch with out both cases and default.
Example:
---------
int i=10;
switch(i)
{}
OP: No Output.
Example:
--------
class Demo
int i=10;
switch(i)
default:
System.out.println("Default");
break;
}
OP: Default
3. In switch, "break" statement is optional, we can write switch with out break statement, in this
context, JVM will execute all the instructions continously right from matched case untill it
Example:
---------
class Demo
int i=10;
switch(i)
case 5:
System.out.println("Five");
case 10:
System.out.println("Ten");
case 15:
System.out.println("Fifteen");
case 20:
System.out.println("Twenty");
default:
System.out.println("Default");
OP: Ten
Fifteen
Twenty
Default
4. In switch, all case values must be provided with in the range of the data type which we provided as
parameter to switch.
Example:
---------
class Demo
byte b=126;
switch(b)
case 125:
System.out.println("125");
break;
case 126:
System.out.println("126");
break;
case 127:
System.out.println("127");
break;
case 128:
System.out.println("128");
break;
default:
System.out.println("Default");
break;
------------------------------------------------------------------------------------------------------------------------
Iterative Statements:
----------------------
These statements are able to allow JVM to execute a set of instructions repeatedly on the basis of a
particular condition.
Example:
---------
1.for
Syntax:
----instructions-----
Example:
--------
class Demo
for(int i=0;i<10;i++)
System.out.println(i);
OP: 0
---
---
9
Expr1-----> 1 time
Expr2-----> 11 times
Expr3-----> 10 times
Example:
---------
class Demo
int i=0;
for(;i<10;i++)
System.out.println(i);
OP: 0 ---- 9
Example:
--------
class Demo
int i=0;
for(System.out.println("Hello");i<10;i++)
System.out.println(i);
Reason:
In for loop, Expr1 is optional, we can write for loop even with out Expr1 , we can write any statement
like System.out.println(--) as Expr1, but, always, it is suggestible to provide loop variable declaration
Example:
---------
class Demo
System.out.println(i+" "+f);
Example:
--------
class Demo
System.out.println(i+" "+j);
Example:
--------
class Demo
{
public static void main(String[] args)
System.out.println(i+" "+j);
OP: 0 0
11
22
Reason:
-------
In for loop, Expr1 is able to allow atmost one declarative statement, it will not allow more than one
declarative statement, we can declare more than one variable with in a single declarative statement.
Example:
--------
class Demo
System.out.println(i);
Example:
--------
class Demo
System.out.println(i);
Reason --> In for loop, Expr2 is optional, we can write for loop even with out Expr2, if we write for loop
with out Expr2 then for loop will take "true" value as Expr2 and it will make for loop as an infinite
loop. If we want to write any statement as Expr2 then that statement must be boolean statement, it
Example:
--------
class Demo
System.out.println("Before Loop");
for(int i=0;;i++)
System.out.println("Inside Loop");
System.out.println("After Loop");
Reasons:
--------
In java applications, if we provide any statement immediatly after infinite loop then that statement is
called as "Unreachable Statement". If compiler identifies the provided loop as an infinite loop and if
compiler identifies any followed statement for that infinite loop then compiler will rise an error like
"Unreachable Statement". If compiler does not aware the provided loop as an infinite loop then there is
Note: Deciding whether a loop as an infinite loop or not is completly depending on the conditional
expression, if the conditional expression is constant expression and it returns true value always then
compiler will recognize the provided loop as an infinite loop. If the conditional expression is variable
expression then compiler will not recognize the provided loop as an infinite loop even the loop is
int i=0;
{}
Example:
--------
class Demo
for(int i=0;i<10;)
System.out.println(i);
i=i+1;
OP: 0 ,1 ..... 9
Example:
---------
class Demo
for(int i=0;i<10;System.out.println("Hello"))
System.out.println(i);
i=i+1;
}
}
OP: 0
Hello
Hello
Hello
Note: In for loop, Expr3 is optional, we can write for loop with out expr3, we can provide any
statements as expr3.
Example:
---------
class Demo
for(;;)
Example:
---------
class Demo
for(;;);
---------
class Demo
for(;;)
{}
Reason-->In for loop, if we want to write single statement in body then curly braces
[{ }] are optional , if we dont want to write any statement as body then we must provide either ; or
In general, we will utilize for loop when we aware no of iterations in advance before writing loop.
2. While loop:
In java applications, when we are not aware the no of iterations in advance before writing loop there
Syntax:
while(Condition)
---instructions-----
Example:
---------
class Test
int i=0;
while(i<10)
{
System.out.println(i);
i=i+1;
Example:
--------
class Demo
int i=0;
while()
System.out.println(i);
i=i+1;
Example:
---------
class Demo
System.out.println("Before Loop");
while(true)
{
System.out.println("Inside Loop");
System.out.println("After Loop");
do-while:
Q) What are the differences between while loop and do-while loop?
Ans:
1.While loop is not giving any guarantee to execute loop body minimum one time.
do-while loop will give guarantee to execute loop body minimum one time.
2.In case of while, first, conditional expression will be executes, if it returns true then only loop
In case of do-while loop, first loop body will be executed then condition will be executed.
3.In case of while loop, condition will be executed for the present iteration.
In case of do-while loop, condition will be executed for the next iteration.
Syntaxes:
while(Condition)
---instructions-----
do
---instructions---
While(Condition):
-------------------
Example:
---------
class Demo
{
int i=0;
do
System.out.println(i);
i=i+1;
while (i<10);
OP: 0, 1, 2,.... 9
Example:
--------
class Demo
System.out.println("Before Loop");
do
System.out.println("Inside Loop");
while (true);
System.out.println("After Loop");
Transfer Statements:
---------------------
These statements are able to bypass flow of execution from one instruction to another instruction.
Example:
--------
1.break:
---------
break statement will bypass flow of execution to outside of the loops or outside of the blocks by
skipping the remaining instructions in the current iteration and by skipping all the remaining iterations.
Example:
---------
class Demo
for(int i=0;i<10;i++)
if(i==5)
break;
System.out.println(i);
OP: 0
1234
Example:
--------
class Demo
System.out.println("Before loop");
for(int i=0;i<10;i++)
if(i==5)
break;
System.out.println("After Loop");
Reason: If we provide any statement immediatly after break statement then that statement is
Example:
---------
class Demo
if(j==5)
{
break;
System.out.println(i+" "+j);
OP: 0 0
01
02
Note: If we provide "break" statement in nested loop then that break statement is applicable for only
In the above context, if we want to give break statement effect to outer loop , not to the nested loop
Syntax:
break label;
Where the provided label must be marked with the respective outer loop.
Continue…..
Example:
---------
class Demo
if(j==5)
break l1;
}
System.out.println(i+" "+j);
OP: 0 0
01
02
03
04
2.Continue:
This transfer statement will bypass flow of execution to starting point of the loop by skipping all the
remaining instructions in the current iteration inorder to continue with next iteration.
Continue….
Example:
---------
class Demo
for(int i=0;i<10;i++)
if(i == 5)
continue;
System.out.println(i);
}
}
OP:
012346789
Example:
---------
class Demo
System.out.println("before Loop");
for(int i=0;i<10;i++)
if(i == 5)
continue;
System.out.println("After loop");
Reason: If we provide any statement immediatly after continue statement then that statement is
Example:
--------
class Demo
{
public static void main(String[] args)
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
if(j==5)
continue;
System.out.println(i+" "+j);
OP:
---
If we provide continue statement in netsted loop then continue statement will give effect to nested loop
Example:
--------
class Demo
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
if(j==5)
continue;
}
System.out.println(i+" "+j);
In the above context, if we want to give continue statement effect to outer loop, not to the nested loop
Syntax:
-------
continue label;
Where the provided label must be marked with the respective outer loop
Example:
---------
class Demo
l1:for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
if(j==5)
continue l1;
System.out.println(i+" "+j);
00
01
02
03
04
10
11
12
13
14
---
---
---
90
01
92
93
94
OO
ARRAYS
-------
*Whenver we try to store large amount of data in a variable we will face readability issue.
In order to store small amount data we can use variables but if we want to store large amount of data then we must use
ARRAYS.
--> The main disadvantage of array is we can present only homogeneous type of data.
--> The main advantage of array is we can represent multiple values under the same variable.Hence we can achive
readability.
--> Once the array is created with some size we can not alter that during execution.
--> We can use concept called as COLLECTIONS to slove the above mentioned problem.
TYPES OF ARRAYS :
-------------------------------
SYNTAX:
-------
a[1] = 20;
NOTE: Array is an obejct since it is created using new keyword. The Super class of array is Object.
WHERE DOES THE MEMORY ALLOCATED FOR ARRAYS?
--> The arrays are created inside the object hence the memeory is allcated in heap memeory segment.
Note: When ever array is created the default values will be added based on the datatype.
example:
--------
float a[] = new float[5] --> 0.0 0.0 0.0 0.0 0.0
ARRAY DECLARATION:
-----------------
The declaration of the array can be done in nay one of the way:
1. int a[];
2. int []a;
3. int[] a; -->{recommended}
example:1
---------
Demo1.java
----------
class Demo1
int a[];
a = new int[5];
a[0] = 10;
a[1] = 20;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
output:
-------
10 20 0 0 0
example 2:
----------
Demo1.java
----------
class Demo1
a[0] = 10;
a[1] = 20;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
//System.out.println(a[5]);
output:
-------
10 20 0 0 0
example 3:
----------
Demo1.java
class Demo1
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
//System.out.println(a[5]);
output:
-------
10
20
30
40
50
---------------------------------------------------------------------------
---------- -----------
--------
Demo1.java
-----------
class Demo1
System.out.println(s.getClass());
NOTE: At the array declaration Size should not be specified. Size should be mentioned only during creation of aaray.
example:
--------
An array size can not be mentioned as negative value. If we do so during compilation we will not get any problem but
during execution we will get error
-----------------------
example 1:
----------
Demo.java
----------
class Demo
a[0]= sc.nextInt();
a[1]= sc.nextInt();
a[2]= sc.nextInt();
a[3]= sc.nextInt();
a[4]= sc.nextInt();
output:
-------
87
92
37
59
64
87 92 37 59 64
example 2:
----------
Demo1.java
----------
class Demo1
a[i]= sc.nextInt();
}
for (int i=0;i<=4 ;i++)
System.out.print(a[i]+" ");
output:
-------
87
92
37
59
64
87 92 37 59 64
example 3:
----------
Demo1.java
----------
class Demo1
i=0;
while(i<=4)
a[i]= sc.nextInt();
i++;
i=0;
while(i<=4)
System.out.print(a[i]+" ");
i++;
output:
-------
87
92
37
59
64
87 92 37 59 64
example 4:
----------
Demo1.java
----------
class Demo1
int i;
i=0;
do
a[i]= sc.nextInt();
i++;
while(i<=4);
i=0;
do
System.out.print(a[i]+" ");
i++;
while(i<=4);
output:
-------
Enter the marks:
87
92
37
59
64
87 92 37 59 64
example 5:
----------
Demo1.java
----------
class Demo1
int n = sc.nextInt();
a[i] = sc.nextInt();
output:
-------
87
92
37
59
64
87 92 37 59 64
example 6:
----------
Demo1.java
----------
//WAP to store and sum the values and print sum value.
class Demo1
int n = sc.nextInt();
a[i] = sc.nextInt();
int sum = 0;
sum = sum+a[i];
output:
-------
10
10
20
30
40
50
60
70
Enter the marks of the students
80
90
100
-----------------------------------------------------------------------------------------------------------------------------------------------
---
MULTI-DIMENSIONAL ARRAY
-----------------------
Multi_dimensional arrays are such arrays whose data can be stored in multiple row/columns.
int a[][];
int [][]a;
int[][] a;
int[] []a;
int[] a[];
---------------------
a[0][1]=20;
--------------------------------------
----------------------------------------
1. 2D regular array
2. 2D jagged array
1. 2D regular array:
--------------------
In this regular array all the rows will have same number of columns.
example:1
---------
WAP to store and print the marks of students from 3 class rooms where in each class 5 students are presents.
import java.util.*;
class Demo
a[i][j]= sc.nextInt();
System.out.println(" ");
output:
-------
10 20 30 40 50
60 70 80 90 100
NOTE:
------
a.length -> 5
a[i].length ->5
a.length -> 3
a[i].length -> 4
a[i][j].length ->5
2. 2D jagged array:
-------------------
If the number of columns is not same in each rows then it is called as Jagged array.
--------------------- -----------------
co -> s0 s1 s2 s3 s4 c0 -> s0 s1 s2
c1 -> s0 s1 s2 s3 s4 c1 -> s0 s1
c2 -> s0 s1 s2 s3 s4 c2 -> s0 s1 s2 s3
---------------------------
import java.util.*;
class Demo
a[i][j]= sc.nextInt();
System.out.println(" ");
output:
-------
10 20 31
41 51
61 71 81 91
example:
--------
class Demo1
System.out.println(a.length); --> 3
System.out.println(a[0].length); --> 5
System.out.println(a[1].length); --> 5
System.out.println(a[0][0].length); --> error
-----------------------------------------------------------------------------------------------------------------------------------------------
Declaration of 3D array:
------------------------
int [][][] a;
int a[][][];
int[][] a[];
int[] [][]a;
int[] []a[];
Creation of 3D array:
---------------------
initilize : a[0][0][0]=10;
-------------------------------------------
-----------------------------
import java.util.*;
class Demo
System.out.println("Enter the marks of student " + k +"of the classroom "+j+" from
the school " +i);
a[i][j][k]= sc.nextInt();
System.out.println(" ");
}
}
output:
------
10 20 30
40 50 60
70 80 90
100 11 12
13 14 15
16 17 18
-------------------------------
import java.util.*;
class Demo
System.out.println("Enter the marks of student " + k +"of the classroom "+j+" from
the school " +i);
a[i][j][k]= sc.nextInt();
System.out.println(" ");
output:
-------
10 20
30 40 50
60 70
80 90 100
-----------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------
---------------------------
example:
--------
Demo.java
class Demo
System.out.println(x[i]);
output: 10 20 30 40 50
-------
example:
--------
Demo.java
class Demo
{
for (int i : x)
System.out.println(i);
output: 10 20 30 40 50
-------
with the above program we can see that same task can be achvied using for each loop aswell.
------------------------
statements
Continue statement:
-------------------
Continue is a control statement which is used to skip the current iteration and move to the next iteration .Continue can
be used only with the loops.
example:
--------
Demo.java
// Continue Statement
class Demo
{
for (int i : x)
if(i==70)
continue;
System.out.println(i);
-------
ANONYMOUS ARRAY
Anonumous array are such array which doesnt have name . It can be declared and initilized in single line.
example:
---------
Demo1.java
// ANONYMOUS ARRAY
class Addition
int sum;
sum=sum+x[i];
System.out.println(sum);
class Demo1
a.add(new int[]{10,20});
OUTPUT:
-------
10
30
OBJECT ORIENTATION
------------------
--------------------------------------
5. Every object will have two parts one is 'has' part also called as 'properties' and second one is 'does' part also calles
as 'behaviour'.
6. Has part of a object is handled using 'datatype and variables' whereas does part is handled by 'methods'.
offline online
------- ------
1.customer 1.customer
2.counter 2.counter
3.money 3.money
4.ticket 4.e-tickets
5.theater 5.theater
6.seat 6.seat
7.movie 7.movie
8.snacks 8.snacks
------------------------------
1. CLASS
2. OBJECT
3. POLYMORPHISM
4. ENCAPSULATION
5. ABSTRACTION
6. INHERITANCE
1.CLASS
--------
--------------------
variable
methods
blocks
constructors
interface
nested class
abstraction
SYNTAX OF A METHOD:
-------------------
---------------
---------------
----------------------------
Class Lion
String name;
String breed;
String gender;
eat()
------
------
sleep()
-------
-------
run()
-------
-------
CREATION OF OBJECT:
-------------------
2. using newInstance()
3. using clone()
4. using FactoryMethod
5. using deserialization
2. Instantiation : allocate the memory (new) memory is pointed by reference variable eg: new Lion();
---------
LionApp.java
------------
class Lion
String name;
String breed;
String gender;
void eat()
void sleep()
void run()
class LionApp
l1.eat();
l1.sleep();
l1.run();
}
output:
-------
NOTE: 1.Always program execution starts from the class where main method is present.
2.To access the variables and methods present in differnt class we will make use of reference varibale.
---------------------------------------------
2. using methods
--------------------------------------------------------
example
--------
LionApp.java
------------
class Lion
String name;
String breed;
String gender;
void eat()
void sleep()
void run()
class LionApp
l1.breed = "Asiatic";
l1.gender = "male";
System.out.println(l1.name);
System.out.println(l1.breed);
System.out.println(l1.gender);
l1.sleep();
l1.run();
}
output:
-------
simba
Asiatic
male
VARIABLES:
----------
1. Data representation
2. Positional declaration
1.1 Primitive variable : If a variable holds primitive data then such variables are called Primitive varaible.
1.2 Reference variable : If a variable holds address of the memory location of an object then such type of variables
are called as ref variable.
2.Positional declaration: based on where we declare the varibales it has been classified into 3 types.
------------------
--> Value of a variable if it changes from object to object then such variables are called as Instance Variables.
NOTE:
-----
--> Example:
Class Demo
int x;
float y;
boolean z;
void method1()
Instance Variables are declared within the class but outside the methods/blocks.
--> Instance variables present within the object inside the 'heap' memory.Hence it is also called object varible or
attribute.
WHAT IS THE SCOPE OF THE INSTANCE VARIABLE ?
For instance variable memory will be allocated during object creation and deallocation will occur during
object destruction.
ex:
---
class Demo
int x =25;
System.out.println(x);
because: jvm will not allow to access instance variable in static region.
example:
--------
class Demo
int x =25;
-------------------------------------------------------------
ex:
---
class Demo2
byte b;
short s;
int i;
long l;
float f;
double d;
boolean bo;
char ch;
String st;
System.out.println(d1.b); --> 0
System.out.println(d1.s); --> 0
System.out.println(d1.i); --> 0
System.out.println(d1.l); --> 0
}
IS JAVA IS PURELY (100%) OBJECT ORIENTED PROGRAMMING LANGUAGE ?
---------------------------------------------------------------
NO, considering only java it doesnot support few features operator overloading, multiple inheritence hence it is not
100% object oriented.
also, if a programming language is 100% object oriented then everything in the program must be considered as object.
we can make our project 100% object oriented by using wrapper classes.
example
-------
NOTE:
-----
The disadvantage with wrapper class is that it will occupy more memory.
STATIC VARIABLE:
----------------
--> The value of a variable does not change from object to object such variables are called as STATIC VARIBALES.
--> Static variables are declared within the class but outside the methods or block.
example:
--------
class People
{
String name; IV
NOTE: For all the objects only one copy of static variable is created and it is shared by every object.
--> Static variables always present in method area [static memory segment] inside the memory.
For the static variable memory will be allocated during loading of class file and deallocated while unloading the class
file.
example:
--------
People.java
-----------
class People
String name;
int addhar_no;
//System.out.println(nationality);
output:
-------
Indian
Indian
Indian
-----------------------------------------------------------
example:
--------
Demo2.java
----------
class Demo2
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
{
Demo2 d1 = new Demo2();
System.out.println(d1.b); --> 0
System.out.println(d1.s);` --> 0
System.out.println(d1.i); --> 0
System.out.println(d1.l); --> 0
NOTE: If the values of static variable is modified then it will be reflected on all the objects
example:
--------
Demo.java
---------
class Demo
int y = 50;
System.out.println(d1.x); // 25
System.out.println(d1.y); // 50
d1.x = 143;
d1.y = 420;
System.out.println(d1.x); // 143
System.out.println(d1.y); // 420
Demo d2 = new Demo();
System.out.println(d2.x); // 143
System.out.println(d2.y); // 50
LOCAL VARIABLE:
--------------
--> Local Variables are temporory variables which are used by programmers to meet temporory requierments.
--> Local Variables are always declared within the method or block.
example:
--------
Class Demo
p s v m(String []args)
for(int i=0;i<10;i++)
s.o.p(i);
--> Local Variables are always present in stack memory hence it is also called as stack variable.
example:
class Demo
int x = 10;
System.out.println(x); // valid
System.out.println(i); // valid
System.out.println(x); // valid
//System.out.println(i); // error[invalid]
--> Local Variables can be accessed only within the method/block.Outside the method we can not access.
example:1
--------
Demo.java
---------
class Demo
{
public static void main(String[] args)
int x;
System.out.println("java"); --> if local variables are not used then we wont get
compilation error
output:
-------
java
example:2
---------
Demo.java
---------
class Demo
int x;
System.out.println("java");
System.out.println(x); --> if we try to use local variables with out initilization then we will
get compilation
error
output:
-------
error
example:3
---------
NOTE: jvm will not provide default values to the local variables hence it is recommended to the programmer to give
default values
Demo.java
---------
class Demo
int x = 0;
System.out.println("java");
System.out.println(x);
ouput:
------
java
1. VALUE TYPE ASSIGNMENT: Whenever value of one variable is assigned to another variable is called as value
type assignment.
example:
--------
Demo.java
---------
class Demo
int x = 10;
int y;
y = x;
System.out.println(x);
System.out.println(y);
output:
-------
10
10
2. REFERENCE TYPE ASSIGNMENT : Whenever the address of the one variable is assigned to another variable
then it is called as reference type assignment.
After the assignment all the ref variable would be pointing to the same object.
Modification done by any one of the reference variable would affect the same object.
example:
--------
Demo.java
---------
class Demo
String name;
int roll_no;
d1.name = "sagar";
d1.roll_no = 24;
System.out.println(d1.name);
System.out.println(d1.roll_no);
Demo d2;
d2 = d1;
d1.name = "sandesh";
d1.roll_no = 25;
System.out.println(d2.name);
System.out.println(d2.roll_no);
System.out.println(d1.name);
System.out.println(d1.roll_no);
output:
-------
sagar
24
sandesh
25
sandesh
25
METHODS:
--------
The does part or behaviuor of an object is handled in the programming using methods.
Syntax of method:
-----------------
method body
}
example:
--------
int z;
z=x+y;
s.o.p(z);
-----------------------------------------------------
example:1
-----------
Demo.java
---------
class Demo
class Addition
void add()
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
output --> 30
example:2
-----------
Demo.java
---------
class Demo
int x=12;
int y=8;
a1.add(x,y);
class Addition
int c;
c=a+b;
System.out.println(c);
output --> 20
example:3
-----------
Demo.java
---------
class Demo
int x=12;
int y=12;
System.out.println(res);
}
}
class Addition
int c;
c=a+b;
return c;
output: --> 24
example:4
-----------
Demo.java
---------
class Demo
System.out.println(res);
System.out.println(res);
}
class Addition
int add()
int a,b,c;
a=14;
b=14;
c=a+b;
return c;
OUTPUT --> 28
example
--------
class Demo
int[] x = ar.fun();
System.out.println(x[i]);
}
}
class ArrayRetrun
int[] fun()
int[] a ={10,20,30,40};
return a;
output: --> 10 20 30 40
CONSTRUCTORS
------------------------------
Constructor is a special block or method where name of the constructor is same as the class name.
Constructor doesnot have any return type.The access modifier allowed for the Constructor method is
public,private,protected,default.
----------------------------------------
-----------------------------
EXAMPLE:
--------
class Student
{
String name;
int roll_no;
class Demo2
s1.name ="raju";
s1.roll_no = 84;
System.out.println(s1.name);
System.out.println(s1.roll_no);
OUTPUT:
--------
raju
84
---------------------
EXAMPLE:
--------
class Student
String name;
int roll_no;
name=sname;
roll_no=sroll_no;
}
public String getName()
return name;
return roll_no;
class Demo2
s1.SetData("somu",89);
System.out.println(s1.getName());
System.out.println(s1.getRoll_no());
OUTPUT:
-------
somu
89
-----------------------
EXAMPLE:
--------
class Student
name=sname;
roll_no=sroll_no;
System.out.println(name);
System.out.println(roll_no);
class Demo
OUTPUT:
-------
bheem
28
somu
89
EXAMPLE:2
---------
// SHADOWING PROBLEM
----------------------
class Student
name=name;
age=age;
return name;
return age;
class StudentApp
System.out.println(s1.getName());
System.out.println(s1.getAge());
OUTPUT:
--------
null
Whenever local variable name is same as the instance variable then the priority is given to local variable. Because of
this problem object initilization
1. use the 'this' keyword to differeniate b/w instance and local variable.
EXAMPLE:
--------
class Student
this.name=name;
this.age=age;
return name;
return age;
class StudentApp
System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s2.getName());
System.out.println(s2.getAge());
}
}
OUTPUT:
-------
ramu
21
somu
22
this keyword always points the currently executing object and also brings the difference b/w local and instance
variable.
TYPES OF CONSTRUCTOR
--------------------
1. default constructor
3. parameterized constructor
DEFAULT CONSTRUCTOR:
--------------------
In a class if constructor is not present during the compilation compiler will add default constructor.
The only one line of code present within the default constructor is super() method.
Whenever compiler adds the default constructor the access modifier of the constructor will be same as that of class.
If user has provided the constructor within a class then during compilation compiler will add a super() method to the
body of the Constructor.
USER DIFIEND DEFAULT CONSTRUCTOR:
----------------------------------
In a class if a programmer adds a constructor then compiler will not add the default constructor.
In a class there would be either UDC or DC. Both of them will never occur simultaneoulsy in the class.
EXAMPLE:
--------
class Student
String name;
int age;
Student()
age=21;
return name;
return age;
class Demo
System.out.println(s1.getName());
System.out.println(s1.getAge());
OUTPUT:
-------
ramu
21
--------------------------------------------
EXAMPLE:
--------
class A
A()
void A()
class Demo1
a1.A();
a1.A();
OUTPUT:
-------
Inside the constructor
CONSTRUCTOR METHOD
------------------------ --------------------------
4. Constructor will be called only one during the object creation 4. method can be called n number times
5. access modifier permitted are : public,private,protected,default 5. we can also use static,final ...etc
PARAMETERIZED CONSTRUCTOR:
--------------------------
Constructors with the parameter is called as parameterized constructor. It is a user difiend constructor.
EXAMPLE:
--------
class Student
String name;
int age;
Student(String name)
return name;
}
}
class Demo
System.out.println(s1.getName());
OUTPUT:
--------
RAMU
EXAMPLE:2
---------
class Student
String name;
int age;
Student(String name)
return name;
class Demo
OUTPUT:
-------
COMPILATION ERROR
NOTE: In the above program we are trying to call the paramterized constructor with out passing the argument hence
we will get compilation error.
CONSTRUCTOR OVERLOADING:
------------------------
1. number of parameter
2. type of parameter
3. order of parameter
EXAMPLE:
--------
class Employee
this.name = name;
this.name = name;
this.id = id;
}
this.name = name;
this.id = id;
this.salary = salary;
return name;
return id;
return salary;
class Demo
System.out.println(e1.getName());
System.out.println(e2.getName());
System.out.println(e2.getId());
System.out.println(e3.getName());
System.out.println(e3.getId());
System.out.println(e3.getSalary());
}
OUTPUT:
--------
ramu
ramu
124
ramu
124
50.45
NOTE: Constructor overloading is used to extend the funcyionality of the constructor .It exhibits virtual
polymorphism.
------------------------
this --> this keyword is used which will internally points to the currently executing object.
this() --> this() method is a constructor call within the same class.
Calling the constructor within another constructor of a same class can be achived using this()
EXAMPLE:
--------
class A
A()
A(int x)
{
this();
class Demo
A a = new A(18);
OUTPUT:
-------
EXAMPLE:2
----------
class A
A()
this("ramu");
A(int x)
this();
A(String s)
{
System.out.println("inside String parametrized constructor");
class Demo1
A a = new A(18);
OUTPUT:
-------
-------------------------------------------
Based on the object state modification methods can be classified into two types:
1.MUTATORS/SETTER : These are used to set or modify the value in the object.
2.ACCESSOR/GETTERS : These are used to get the value from the object.
class Credentials
un=username;
{
pwd=password;
String getUn()
return un;
String getPwd()
return pwd;
class Demo
c.setUn(" ");
c.setPwd("3443");
System.out.println(c.getUn());
System.out.println(c.getPwd());
output : -->
34343
class Student
name=sname;
age=sage;
height=sheight;
String getName()
return name;
int getAge()
return age;
float getHeight()
return height;
class Demo
s.setName("Subbu");
s.setAge(24);
s.setHeight(6.1f);
System.out.println(s.getName());
System.out.println(s.getAge());
System.out.println(s.getHeight());
24
6.1
PASS BY VALUE
-------------
In java the parameter can be passed only in the value mode. Java doesnot support the any other passing techniques
other than pass by value.
In c programming language it has both pass by value and pass by reference, but java doesnot support concept of
pointer hence pass by refernece is
--------------------------
class Test
int temp;
temp = x;
x = y;
y = temp;
class Demo
System.out.println("before swapping:");
t.swap(a,b);
System.out.println("after swapping:");
output:
-------
before swapping:
after swapping:
--------------------------
In c language we can write any number of functions but the functions name should be unique(no two functions shuold
have the same name).
example of c language:
----------------------
#include<stdio.h>
#include<conio.h>
Void main()
printf(“%f”, add3(p,q));
printf(“%f”, add4(a,x));
printf(“%f”, add10(a,b,c));
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
}
int add7(float x, int y)
return x+y;
return x+y;
return x+y;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
}
return x+y+z;
note:
-----
In the above c program even though we are properly performing addition operation but still we should remember
multiple functions name which is complex
The above problem can be overcome using the METHOD OVERLOADING concept in java.
example:
------------
class Demo
// ORDER OF THE
PARAMETER
System.out.println(t.add(p,q));
System.out.println(t.add(a,x));
System.out.println(t.add(a,b,c));
System.out.println(t.add(a,p));
class Test
{
int add(int x, int y)
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
return x+y;
}
int add(int x, int y, int z)
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
return x+y+z;
output:
-------
30.4653
11.2
60
20.222
Multiple methods with the same name is called as method overloading . Whenever call is made for overloaded method
the compiler will resolve the
2.NUMBER OF PARAMETER
---------------------------
class Demo
int a = 10;
d1.fun();
int c=a+b;
System.out.println(c);
}
{
NOTE: Instance blocks are anonymous(nameless) blocks which are executed during the object creation before the
constructor call
EXAMPLE:
--------
class A
A()
A(int x)
class Demo2
A a =new A();
OUTPUT:
-------
EXAMPLE:
---------
class A
class Demo2
A a =new A();
OUTPUT:
-------
NOTE: The order of the memeory allocation is 1. instance variables 2. instance blocks(non-static blocks) 3. constructor
EXAMPLE:
--------
class A
{
//int a=10;
A()
float f = 12.14f;
void fun()
class Demo2
A a =new A();
OUTPUT:
------
NOTE: Unlike constructors instance blocks are used to initialize the instance variables
EXAMPLE:
---------
class A
{
//IB
age=16;
class Demo2
A a =new A();
OUTPUT:
-------
the age is 16
NOTE: Instance blocks are used to provide the logic which is common for all the objects. If the logic is specific for
different
EXAMPLE:
--------
class Student
//IB
Student() //UDDC
register_number=20;
Student(int x) //UDPC
register_number = x;
class Demo
OUTPUT:
-------
NOTE: The memory for instance variables and methods and blocks are always given in the heap memory segment.
import java.util.*;
class Student
name = sc.next();
age = sc.nextInt();
schoolName = sc.next();
System.out.println("name is :"+name);
System.out.println("age is :"+age);
System.out.println("schoolname is :"+schoolName);
class Demo
s1.setData();
s1.display();
OUTPUT:
--------
sagar
25
jain
NOTE: Whenever the value is same for multiple objects instead of having multiple copies we can have a single copy.
In the above program schoolname is common for all the students hence we can have a single copy and it can be shared
among the objects
such common elements we should make it as static in the program to imporve memory effieceny.
EXAMPLE:2
----------
NOTE: when ever java program stats executing always static members will execute first.
STATIC METHODS:
---------------
Static methods are such methods present in the class where a method is prefixed with static keyword.
static methods are class methods which are shared by multiple objects.they are not associated with objetcs.
--------
class Test
void fun1()
class Demo2
t1.fun1();
t1.fun2();
Test.fun2();
OUTPUT:
-------
EXAMPLE:
---------
class Test
static //SB
a=10;
b=20;
c=30;
System.out.println(a);
System.out.println(b);
System.out.println(c);
{ //IB
x=40;
y=50;
z=60;
a=100;
b=200;
c=300;
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
class Demo
Test.fun1();
t2.fun2();
OUTPUT:
--------
100
200
300
40
50
60
100
200
300
INSATNCE METHOD:
----------------
STATIC METHOD:
---------------
3. Can be accessed using the both object ref and class name
STATIC BLOCKS:
--------------
Static blocks are executed during the class loading.There execution is before the execution of main method.
example:
---------
static{ static
} }
EXAMPLE:
----------
// Static blocks
class A
int x;
static int y;
{
x=10;
System.out.println(x);
static
y=20;
System.out.println(y);
A()
class Demo1
A a =new A();
INSTANCE BLOCK:
---------------
2. It will always executes during object creation and before the constructor call.
STATIC BLOCKS:
--------------
2. It is executed during the class loading and bfore the execution of main method
3. Memory will be allocated only once.
-----------------------------------------------------
--> Till java 1.6 version a java program can be executed without a main method.
INHERITANCE
------------
Inheritance is a process of a class aqcuring the properties(variables) and behaviour (methods) from the other class.
Parent class is a class which gives the proerties and behaviour to another class.
child class is a class which inherit the proerties and behaviour from its parent class.
ADVANTAGE OF INHERITANCE:
--------------------------
1. CODE REUSABLITY.
example:1
----------
// unrelated classes
class visitor
String name;
int ph_no;
class Hospital
void Doctor_conslut()
{
------------
-------------
------------
NOTE:1
-------
example:2
----------
// related classes
class visitor
int ph_no;
------------
-------------
------------
NOTE:2
------
------
Whenever the obejct of child class is created the memory is not only allocated for the instance variable of a child class
but it also allocates
EXAMPLE:
--------
// note3
class A
class B extends A
int j = 20;
class Demo
B b= new B();
System.out.println(b.i);
System.out.println(b.j);
NOTE: 4
--------
Private members will not participate in the inheritance.This rule is made to promote ENCAPSULATION.
EXAMPLE:
--------
// note4
class A
class B extends A
int j = 20;
class Demo
B b= new B();
System.out.println(b.i);
System.out.println(b.j);
OUTPUT:
--------
System.out.println(b.i);
NOTE:5
------
Child class can call the instance method of parent class directly.
EXAMPLE:
--------
// note5
class A
class B extends A
class Demo
B b= new B();
b.fun2();
b.fun1();
OUTPUT:
------
NOTE:6
------
The child class can call the inherited static methods directly.
EXAMPLE:
--------
// note4
class A
class B extends A
void fun2()
class Demo
B b= new B();
b.fun2();
b.fun1();
OUTPUT:
------
------
Unlike the private members constructors are also doesnt partcipate in the inheritance.
ie, parent class consructor would not be inherited to the child class rather the control from the child class will go the
super class(parent class)
EXAMPLE:
---------
// note7
class A
int i; //IV
int j; //IV
A() //UDDC
//super();
i=1111;
j=2222;
class B extends A
B() //UDDC
super();
}
class Demo
B b= new B();
b.display();
OUTPUT:
------
i value is 1111
J value is 2222
// note7 example:2
-------------------
class A
int i;
int j;
A(int x)
super();
i=1111;
j=2222;
class B extends A
B()
super();
}
void display()
class Demo
B b= new B();
b.display();
OUTPUT:
-------
COMPILATION ERROR
In the child class during the execution of super() a call is made to the default constructor (parent class) if the default
constructor is not present
NOTE:8
-------
Even though the parameterized constructor of a sub-class is called yet, the default constructor in the super class is
executed first then the parameterzied
// note8
-----------
class A
//super();
class B extends A
B() //UDDC
super();
super();
this.i=i;
this.j=j;
class Demo
B b= new B(10,20);
b.display();
OUTPUT:
-------
inside the default constructor
i value is 10
j value is 20
NOTE:9
-------
If the parameterized constructor of the super class has to be executed then parameter super should be used in the sub-
class
EXAMPLE:
---------
// note9
class A
int i,j;
this.a=a;
this.b=b;
class B extends A
super(30,60);
this.i=i;
this.j=j;
void display()
class Demo
B b= new B(10,20);
b.display();
OUTPUT:
-------
i value is 10
j value is 20
a value is 30
b value is 60
TYPES OF INHERITANCE:
---------------------
1. SINGLE INHERITANCE
2. MULTI-LEVEL INHERITANCE
3. HIERARCHICAL INHERITANCE
4. MULTIPLE INHERITANCE
5. HYBRID INHERITANCE
6. CYCLIC INHERITANCE
NOTE: In Java single,multi-level and hierarchical inheritance is supported and other types are not supported.
--> In case of multiple inheritance it will result in ambiguity(confusion).This problem is referred as 'DIAMOND
SHAPE' problem.
EXAMPLE:
--------
class A
int i = 10;
class B extends A
int i =20;
void display()
System.out.println(i);
class Demo
C c1 = new C();
c1.display();
OUTPUT:
--------
COMPILATION ERROR
class A
void fun1()
class B extends A
void fun2()
class C extends B
void fun3()
class Demo
C c1 =new C();
c1.fun1();
c1.fun2();
c1.fun3();
}
}
OUTPUT:
-------
-----------------------------------
class A extends B
void fun1()
class B extends A
void fun2()
class Demo
B b1 =new B();
b1.fun1();
b1.fun2();
}
OUTPUT:
--------
class A extends B
super keyword
--------------
During the inheritance if the parent class and class having the variable name and the name clash would occur and
priority is given to child class.
instance variable.
In order to access the instance variable of parent class we will use super keyword.
class A
int x = 10;
class B extends A
int x=20;
void fun2()
System.out.println(x); // 20
System.out.println(this.x); // 20
System.out.println(super.x); // 10
class Demo
B b1 =new B();
b1.fun2();
}
--------------------
NOTE: Inside the constructor the first statement should be either this() or super(). If the user is not using either super()
or this() then compiler
EXAMPLE:
---------
class A
A()
NOTE: super() and this() can not be placed in the same constructor.
EXAMPLE:
---------
class A
A()
{
super();
this();
-------------------------------------------------
EXAMPLE:
--------
class Parent
//IB
//IB
fun1();
Parent()//UDDC
{
System.out.println("parent class first instance method");
//IB
//IB
fun2();
Child() //UDDC
OUTPUT:
--------
-------------------------------------------------------
2. execute instance variable fallowed by instance blocks and method and finally execute parent class constrctor
4. execute instance variable fallowed by instance blocks and method and finally execute child class constrctor
-------------------------------------------------
EXAMPLE:
--------
class Parent
static
static
fun1();
Parent()
static
static
fun2();
Child()
OUTPUT:
-------
-------------------------------------------------------
-------------------------------------------------
EXAMPLE:
--------
class Parent
static
// instance block
// instance block
{
test1();
// constructor
Parent()
// static method
System.out.println(x);
// instance method
void test1()
System.out.println(y);
int b=40;
static
test2();
}
Child()
System.out.println(a);
void test2()
System.out.println(b);
Child.fun1();
Child.fun2();
OUTPUT:
-------
10
--------------------------------
20
40
---------------------------------------------------------------------------
2. execute the sv sb and sm of parent class and execute it in the top-bottom order
--------------------------------------------
INHERITED METHOD : any method which is acquired by the child class from the parent class is called as inherited
method.
SPECIALIZED METHOD : mehods which are unique to child class is called as specialized methods
EXAMPLE:
---------
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Demo
cp.takeOff();
cp.fly();
cp.land();
cp.CarryCargo();
pp.takeOff();
pp.fly();
pp.land();
pp.CarryPassenger();
}
OUTPUT:
---------
plane is landing
plane is landing
METHOD OVERRIDING
--------------------------------
class Parent
void marry()
void marry()
The method which is inherited by the child class from the parent class and if the child class modifies or implements
the inherited methods such
process is called as METHOD OVERRIDING.
EXAMPLE:
--------
class Vehicle
void Move()
void Move()
void Move()
void Move()
class Demo1
{
b.Move(); // 1:1
c.Move(); // 1:1
t.Move(); // 1:1
OUTPUT:
-------
---------------------------------
Parent reference to child object in method overriding is all about proving the parent object refernce to the child object
to achive the POLYMORPHISM.
EXAMPLE:
---------
class Vehicle
void Move()
{
void Move()
void Move()
void Move()
class Demo1
v.Move();
v = new Car();
v.Move();
v = new Truck();
v.Move(); // 1:3
}
OUTPUT:
-------
RELATIONSHIPS IN JAVA
-------------------------------------------
As a part of java application development we have to use entities as per the requirement
relationships are used to provide the optimization over memory utilization,code reusablity,execution time,ease of
shareablity.
-------------------------------
1.IS-A relationship
2.HAS-A relationship
IS-A : by using this we can achive the concpet of inheritance by doing so we can perform 'code reusablity'.
HAS-A : It defines associations b/w the entites to improve the communication b/w the entites for better data
navigation.
1. COMPOSITION
2. AGGREGATION
arggregation will have less dependency with enclosed object where as compostion will have more dependency with
enclosed object
aggregation members can be accessed when with out enclosed object
EXAMPLE:
--------
class os
String name;
int size;
this.name=name;
this.size=size;
return name;
return size;
class charger
String brand;
String color;
this.brand=brand;
this.color=color;
}
public String getBrand()
return brand;
return color;
class mobile
System.out.println(c.getBrand());
System.out.println(c.getColor());
class Demo1
//System.out.println(m.o.getName());
//System.out.println(m.o.getSize());
m.hasA(c1);
m=null;
//System.out.println(o.getName());
//System.out.println(o.getSize());
System.out.println(c1.getBrand());
System.out.println(c1.getColor());
}
OUTPUT:
-------
samsung
white
samsung
white
ABSTRACTION
-------------------------------
It is process of hiding the internal implementation and sharing only the related functionality to the user.
2. Interface
-------------------------------------
class Vehicle
System.out.println("vehicle is moving");
System.out.println("vehicle is started");
void Start()
System.out.println("kick start");
class Demo
V.Move();
V.Start();
C.Move();
C.Start();
B.Move();
B.Start();
void Move()
void Start()
void Start()
System.out.println("kick start");
class Demo
C.Move();
C.Start();
B.Move();
B.Start();
NOTE:1
-------
1. ABSTRACT METHOD : Abstarct methods are overridden methods where it will be not have implemenation.
2. abstract is a non access modifier keyword which used as prefix for abstarct methods and classes.
3. If any method is abstract in a class then that class is also considered as abstratc class and prefixed with abstract
keyword.
4. For abstract classes we can not create the object(not required to create).
6. the inherited method from the parent class is also called as 'concrete method'.
EXAMPLE:
--------
void roi()
}
}
void roi()
void roi()
class Demo1
Bank b;
b.roi();
b.roi();
b.roi();
NOTE:2
-------
1. For abstrat class we can not create object but we can have refence
2. by parent reference we can perform upcasting and polymorphism can be achived
3. abstract class which consist of only abstract methods is considered as 100% abstraction.
-----------------------------------------------
---------------------------------------------------------------
class Calc
int a;
int b;
a=10;
b=20;
int c=a+b;
System.out.println(c);
a=20;
b=10;
int c=a-b;
System.out.println(c);
class Demo2
c.add();
c.sub();
-------------------------------
// normal class
int a;
int b;
class Demo2
//c.add();
//c.sub();
------------------------------------
void On()
System.out.println("the TV is on");
void Off()
System.out.println("the TV is off");
class Demo3
remote r;
r = new Tv();
r.On();
r.Off();
------------------------
RULE:1
-------
If a method is made as abstract then compulsory the child class should override the method.
If the child class doesnot override the abstract method then error is displaced during compilation
EXAMPLE:
--------
CASE:1
-------
void fun1()
System.out.println("inside fun1");
CASE:2
-------
1. class
2. methods
3. Interface (methods)
4. Inner class (classes)
1. static
2. final
3. private
1. Strictfp
2. Synchronized
3. native
refer fig:2
Interface is collection of abstract methods using interface 100% abstraction can be achived becuase inside the interface
methods declaration are allowed
SYNTAX:
-------
interface interface_Name
ADVANTAGE OF INTERFACE:
-----------------------
eg: pi value
2. It promotes polymorphism
Also by default all the methods present in the interface is 'public abstract' in nature.
EXAMPLE:1
---------
interface Test
float pi = 3.14f;
void fun();
compile:
interface Test
RULES OF INTERFACE:
--------------------
RULE:1
--> When a class is implementing the inteface the methods access modifiers should be made as public beacause by
default all the abstract method in
EXAMPLE
-------
refer diagram:
---------------
interface Calculate
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
class Demo
c.add();
/*
public
default
private
*/
OUTPUT:
--------
30
RULE:2
-------
-->If a class implements the interface then it should provide the body for all the methods present in the interface class.
If the class is not in a position to provide the body for all the method then class should be made as anstract.
EXAMPLE:1
----------
interface Calculate
void add();
void mul();
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
class Demo
c.add();
}
OUTPUT:
------
Calculator is not abstract and does not override abstract method mul() in Calculate
note:
-----
The above probelm can be overcome by making class as bastract and method where class is not in a position to provide
the body then it should be made
as abstract.
EXAMPLE:2
----------
interface Calculate
void add();
void mul();
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
class Demo
RULE:3
-------
EXAMPLE:
-------
interface Calculate
void add();
void mul();
class Demo
p s v m (---)
OUTPUT:
-------
ERROR
RULE:4
------
Though we cannot create the object for interface its refernce can be created.
EXAMPLE:
--------
interface Calculate
void add();
void mul();
class Demo
p s v m (---)
RULE:5
------
EXAMPLE:
--------
interface Calculate
void add();
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
}
}
class Demo
c.add();
OUTPUT:
-------
ERROR
RULE:6
------
Using the inteface ref (parent ref) the implemented methods of a class can be accessed and using interface ref
polymorphism can be achived
EXAMPLE:
--------
interface Bank
void ROI();
{
System.out.println("AXIS --> 9.5%");
class Calculate
ref.ROI();
class Demo1
c1.allow(s);
c1.allow(a);
c1.allow(c);
OUTPUT:
-------
---------------------------------------------
EXAMPLE:
-------
interface calculate1
interface calculate2
System.out.println(min);
class Ambiguity
t.disp();
OUTPUT:
--------
NOTE: The above problem can be overcome by accessing the inteface variable with the interface name.
EXAMPLE:
--------
interface calculate1
interface calculate2
System.out.println(calculate1.min);
System.out.println(calculate2.min);
class Ambiguity
t.disp();
}
OUTPUT:
-------
10
20
RULE:14
-------
refer dia: 7
EXAMPLE:
--------
interface calculate1
void add();
interface calculate2
void sub();
void mul();
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println(c);
}
public void sub()
int a,b,c;
a=20;
b=05;
c=a-b;
System.out.println(c);
int a,b,c;
a=20;
b=05;
c=a*b;
System.out.println(c);
class Rule14
t.add();
t.sub();
t.mul();
OUTPUT:
-------
30
15
100
EXAMPLE:
--------
interface A
int i =10;
interface B
int i = 20;
class Test
System.out.println(A.i);
System.out.println(B.i);
class Demo
t.disp();
OUTPUT:
------
10
20
ADAPTER CLASS:
--------------
Adapter class is a normal class in java which as empty body for all the abstract methods of an interface.
EXAPLE:
---------
interface compute
void fun1();
void fun2();
void fun3();
void fun4();
void fun5();
void fun6();
{
}
class Demo3
t1.fun1();
t4.fun4();
OUTPUT:
--------
-----------------
Marker interface is a empty interface which doesnot contain any abstract methods or fields.
example: if a class implements clonable interface then a duplicate object with the same behaviour can be created.
1. Cloneable
2. Serialization
3. Runnable
OBJECT CLONING:
---------------
-->The process of creating duplicate object for an existed object is called as Object Cloning.
-->If we want to perform Object Cloning in Java application then we have to use the following steps.
2.Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.
4.In Main class,in main() method,access clone() method over the respective object
EXAMPLE:
--------
int a = 10;
System.out.println(d.a);
Demo5 d1=(Demo5)d.clone();
System.out.println(d1.a);
}
OUTPUT:
--------
10
10
-------------------------------------
extends:
--------
1. A class can inherit other class using the extends keyword.An interface can inherit another interface using the
extends keyword.
2. A subclass which extends super class may or may not override all the methods of superclass
implements:
----------
2. class implementing interface should provide body for all methods of interface
--------------------------------------------
interface:
---------
6. following modifiers are not allowed for abstract methods static, private,strictfp,protected,final
abstract class
--------------
4.every method present in abstract class need not to be public and abstract
5.every variables present in abstract class need not to be public static final
POLYMORPHISM
-------------
POLY means many MORPHS means forms. An object with many forms is called as POLYMORPHISM.
NOTE: In the above program v.Move() is polymorphic statement because it is providing 3 differnt outputs ---> 1:3
POLYMORPHISM is used to achive the 'code reduction' and flexibilty of the program.
EXAMPLE:
--------
class Plane
{
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
{
System.out.println("Passengerplane is flying with the medium speed");
void CarryPassenger()
void fly()
void CarryArms()
class Demo
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryCargo();
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryPassenger();
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryArms();
OUTPUT:
--------
plane is landing
plane is landing
plane is landing
NOTE: In the above program we have achived polymorphism by using the concept of 'parent ref to child object' but by
this technique we can not access
EXAMPLE:
--------
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
{
void fly()
void CarryArms()
class Airport
ref.takeOff();
ref.fly();
ref.land();
class Demo
a.allow(cp);
a.allow(pp);
a.allow(fp);
OUTPUT:
--------
plane is landing
plane is landing
plane is landing
---------------------------------
5. POLYMORPHISM
--------
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Demo
ref.fly();
ref.land();
((CargoPlane)(ref)).CarryCargo();
//ref = new PassengerPlane();
OUTPUT:
-------
plane is landing
---------------------------
UPCASTING : upcasting refers to the creation of child object and assigning the ref to it.
DOWNCASTING: it means tempory converting the parent ref to child type to access the specialized method
WHAT IS RUNTIME POLYMORPHISM AND VIRTUAL POLYMORPHISM ?
--> METHOD OVERLOADING --> VIRTUAL POLYMORPHISM --> STATIC POLYMORPHISM --> EARLY
BINDING.
--> METHOD OVERRIDING --> RUNTIME POLYMORPHISM --> DYNAMIC POLYMORPHISM --> LATE
BINDING.
-----------------------------------------------------
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
{
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Airport
{
ref.takeOff();
ref.fly();
ref.land();
ref.takeOff();
ref.fly();
ref.land();
ref.takeOff();
ref.fly();
ref.land();
class Demo
a.allow(cp);
a.allow(pp);
a.allow(fp);
}
// RUNTIME POLYMORPHISM USING THE METHOD OVERRIDING.
-----------------------------------------------------
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Airport
ref.takeOff();
ref.fly();
ref.land();
class Demo1
a.allow(cp);
a.allow(pp);
a.allow(fp);
-------------------------------------------
RULE 1:
-------
In method overriding the method signature should be same. IE The method name and argument type should be same in
both parent and child class.
eg:
---
---------
-----------
-----
FINAL KEYWORD:
--------------
1. on class
2. on method
3. on variable
------------------------
If a class is made as final then that class will not participate in inheritance.
example:
----------
final class A
void fun1()
class B extends A
void fun1()
A a = new A();
a.fun1();
B b = new B();
b.fun1();
------------------------
The methods which are made as final can be inherited to the child class but can not be overridden.
example:
----------
class A
class B extends A
void fun1()
//a.fun1();
B b = new B();
b.fun1();
//b.fun1();
------------------------
If the variable is made as final then the value of the variable can not be alterd in other words it will become static in
nature.
example:
----------
class A
int fun1()
speed = 250;
//System.out.println(spped);
return speed;
class B
A a = new A();
System.out.println(a.fun1());
RULE 4:
-------
non-static to static method overriding and static to non-static method overriding is not permited in java.
example:
-------
class A
void fun1()
class B extends A
//a.fun1();
B b = new B();
b.fun1();
EXCEPTION HANDLING
------------------------------------
Exception is unwanted or unexpected event which occurs in the excution of program, which distrubs the normal flow
of the program.
compile time error : The mistake done by the programmer in the code which is caught by the compiler during
compilation phase.
run-time error : The faulty inputs given by the user during the execution time leads to runtime error and it is also called
as 'EXCEPTION'.
The main objective of exception handling is to achive 'graceful termination of the program'.
"Exception handling is the way writing alternative way of code to continue the normal flow of the program. "
EXAMPLE:NORMAL TERMINATION
---------------------------
import java.util.*;
class Demo
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("A/B is ="+(a/b));
OUTPUT:
-------
10
A/B is =5
NOTE: In the above example user as given valid input hence normal termination of the program can be seen.
-----------------------------
import java.util.*;
class Demo
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("A/B is ="+(a/b));
OUTPUT:
-------
10
at Demo.main(Demo.java:11)
NOTE: In the above program user as not given right input at the time of execution hence it resulted in runtime error or
exception.
In this case JVM acts as DEFAULT EXCEPTION HANDLER and provides the exception details.
NOTE: Exception can be handled with the help of try and catch block.
syntax:
-------
try
risky code
catch (** e)
}
EXAMPLE: GRACEFUL TERMINATION by using user difiend exception handler
---------------------------------------------------------------------
import java.util.*;
class Demo
int a = sc.nextInt();
int b = sc.nextInt();
try
System.out.println("A/B is ="+(a/b));
catch (Exception e)
// ANY RISKY CODE SHOULD PUT INSIDE THE try and catch block.
OUTPUT:
------
10
-----------------------------------------------
EXAMPLE:
---------
class Demo1
sleep();
wakeup();
OUTPUT:
-------
in sleep method
in wakeup method
in main method
REFER FIG:
EXAMPLE:
--------
class Demo1
System.out.println(10/0);
sleep();
wakeup();
OUTPUT:
-------
at Demo1.wakeup(Demo1.java:5)
at Demo1.main(Demo1.java:16)
REFER FIG:
1. use user difiend exception handler in the specific method where the exception as araised or:
2. use the UDEH in main method because anyways at the end the control will come to main method.
EXAMPLE :1
----------
class Demo1
try
System.out.println(10/0);
sleep();
catch (Exception e)
wakeup();
EXAMPLE:2
-----------
class Demo1
{
System.out.println(10/0);
sleep();
try
wakeup();
catch (Exception e)
--> continuous try block is no permitted in java where as continous catch block is permitted.
NOTE: for a single try block we can have multiple catch block in java.
---------------------
EXAMPLE:
--------
import java.util.*;
class Demo
try
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a/b);
catch(ArithmeticException e)
System.out.println("learn maths..!");
catch(InputMismatchException e)
catch (Exception e)
System.out.println("invalid");
OUTPUT:
-------
learn maths..!
10
JBSJVBSJ
-------------------------------------------------
1. final keyword:
-----------------
finally block:
--------------
finally block always associated with try and catch blocks to maintain the 'clean up code'.
EXAMPLE:
--------
import java.util.*;
class Demo
{
Scanner sc = new Scanner(System.in);
try
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a/b);
catch (Exception e)
System.out.println("invalid");
finally
System.out.println("finally executed..!");
OUTPUT:
--------
10
finally executed..!
10
invalid
finally executed..!
--> finally block is used to excute some set of statements which has to be executed if exception occur or it it does not
occur .
finally block is used w.r.t the codes like closing the connection with database,file,network etc..
finalize() method :
--------------------
finalize method is invoked by 'garbage collector' just before destroying an object to perform cleap up activities.
Once finalize work is completed the G.C will destory the object.
NOTE: finally block is responisble to clean up the things w.r.t try block whereas finalize deal with exception object.
EXCEPTION OBJECT:
-----------------
The main purpose of the catch block is to catch the exception from try block.
REFER DIA
--------------------------------------------------------
1. e.printStackTrace();
2. s.o.p(e);
3. s.o.p(e.getMessage());
EXAMPLE:
--------
import java.util.*;
class Demo1
try
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a/b);
catch (Exception e)
e.printStackTrace();
System.out.println();
System.out.println(e);
System.out.println();
System.out.println(e.getMessage());
OUTPUT:
-------
10
java.lang.ArithmeticException: / by zero
at Demo1.main(Demo1.java:15)
java.lang.ArithmeticException: / by zero
/ by zero
10
SDSCFSVF
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Demo1.main(Demo1.java:13)
java.util.InputMismatchException
null
TYPES OF EXCEPTIONS:
---------------------
1. PRE-DEFINED EXCEPTIONS
-----------------------------
All the exceptions present in the exception hierarchy is considered as pre defiend exceptions
1. Checked Exceptions
2. Unchecked Exceptions
What is the difference b/w checked exception and unchecked exceptions?
-->Chekced exceptions is an exception recognized at compile time,but, not occurred at compilation time.
Unchecked exceptions are not recognize at compile time,these exceptions are recognized at runtime by JVM.
NOTE: In exceptions hierarchy, Runtime exceptions and its sub-class and error and its sub-classes are the example for
unchekced exceptions.
--> Pure checked exceptions is having only chekced exceptions as sub classes in it.
ex: IO exception
partially checked exception where atleast one sub class as unchecked exception present in it.
-----------------------------------
note: all the sub-classes under RUNTIME EXCEPTIONS are unchecked exceptions
1. Arithmetic exception:
-------------------------
EXAMPLE:
--------
// Arithmetic exception
class Demo
{
int i = 10;
int j = 0;
float f = i/j;
System.out.println(f);
OUTPUT:
--------
at Demo.main(Demo.java:8)
2. NullPointer Exception
------------------------
EXAMPLE:
--------
// NullPointer exception
class Demo
String s = null;
System.out.println(s.length());
OUTPUT:
--------
at Demo.main(Demo.java:7)
3. ArrayIndexOutOfBounds exceptions:
------------------------------------
EXAMPLE:
--------
// ArrayIndexOutOfBoundsException
class Demo
System.out.println(a[5]);
OUTPUT:
--------
at Demo.main(Demo.java:7)
4.StringIndexOutOfBoundsException:
EXAMPLE:
--------
// StringIndexOutOfBoundsException:
class Demo
String s = "sagar";
System.out.println(s.charAt(5));
}
}
OUTPUT:
--------
at java.lang.String.charAt(String.java:658)
at Demo.main(Demo.java:7)
5. ClassCastException:
-----------------------
EXAMPLE:
---------
// ClassCastException:
class A
class B extends A
class Demo
A a = new A();
B b = new B();
//B b = (B)a;
A a1 = b;
OUTPUT:
-------
at Demo.main(Demo.java:14)
NOTE: In java programs we are able to keep sub-class(child class) object reference value in the super-class(parent
class) reference variable,but
parent class object reference value can not be kept in child class variable.
6.ClassNotFoundException:
---------------------------
EXAMPLE:
--------
// ClassNotFoundException:
class A
System.out.println("class loading...!");
class Demo
Class c = Class.forName("XYZ");
OUTPUT:
-------
Class c = Class.forName("XYZ");
----------------------------
1. OutOfMemory Error:
---------------------
EXAMPLE:
---------
// OutOfMemoryError:
class Demo
OUTPUT:
--------
at Demo.main(Demo.java:6)
2. stackOverflow Error:
------------------------
refer dia:1
EXAMPLE:
--------
// StackOverflowError:
fun1();
System.out.println("inside fun1");
fun1();
OUTPUT:
--------
------------------------------
EXAMPLE:
--------
import java.io.*;
class Demo
try
catch (FileNotFoundException e)
OUTPUT:
-------
'throw' keyword:
-----------------
-------
class Demo
System.out.println(10/0);
at Demo.main(Demo.java:5)
case-2
-------
class Demo
at Demo.main(Demo.java:5)
As a programmer we can create a exception explicitly and handover to the jvm manually.To perform this activity we
need thorw keyword.
EXAMPLE:
---------
import java.util.*;
class Demo
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(divide(a,b));
if (b<0)
else if(b>a)
return a/b;
OUTPUT:
-------
10
2
5
10
at Demo.divide(Demo.java:23)
at Demo.main(Demo.java:11)
10
20
at Demo.divide(Demo.java:21)
at Demo.main(Demo.java:11)
case-1
-------
class Demo1
throw e;
OUTPUT:
-------
at Demo1.<clinit>(Demo1.java:3)
case-2
-------
class Demo1
static ArithmeticException e ;
throw e;
OUTPUT:
--------
at Demo1.main(Demo1.java:6)
NOTE: First we must create the exception object using new keyword and then we can throw that exception. Without
creating exception object if we
try to throw the exception we will get nullpointerexception because there is no exception object in the memory.
case-3
------
class Demo1
System.out.println(10/0);
System.out.println("hello world");
OUTPUT:
-------
at Demo1.main(Demo1.java:5)
case-4
-------
class Demo1
System.out.println("hello world");
OUTPUT:
-------
System.out.println("hello world");
NOTE: The line below the exception is not excecuted because jvm stops the flow of execution immeaditly after finding
exception object.
In case of throw keyword the lines below throw statements are unreachable statments.
case-5
-------
class Demo1
OUTPUT:
-------
^
case-6
-------
OUTPUT:
-------
at Demo1.main(Demo1.java:5)
NOTE: All the java objects are not throwable.Only throwable objects can be thrown using throw keyword.
IMPORT STATEMENTS
----------------------------------
// EXAMPLE:1
-------------
class Demo
//System.out.println("Hello World!");
class Test
{
OUTPUT:
-------
compilation error
NOTE: In the above program when compile, we will get compilation eror because we have not specify the location of
the Scanner class.
----------------------------------
class Demo
class Test
NOTE: Usage of fully qualified names in the program leads to readablity probelm and also the code length will
increase.
To overcome this problem we will use import statements in the java programs
------------------------------
import java.util.Scanner;
class Demo
{
class Test
NOTE: Import statements are used to import the class into the program or to bring class into visibility inside the
program.
-------------------------------
---------------------------------------
class Demo
}
output:
compilation error
---------------------------------------
EXAMPLE:
---------
import java.sql.*;
class Demo
System.out.println(d.getClass().getName());
OUTPUT:
-------
java.util.Date
EXAMPLE:
--------
import java.util.*;
//import java.sql.*;
class Demo
System.out.println(d.getClass().getName());
OUTPUT:
----------
java.util.Date
STATIC IMPORT:
--------------
From the 1.5 version of java static import statemnts we can use to access the static members [methods and variables]
without using the class name.
--------------------------
class Demo
System.out.println(Math.sqrt(4));
OUTPUT:
-------
2.0
---------------------------
class Demo
System.out.println(sqrt(4));
}
output:
--------
2.0
EXAMPLE:
----------
class Demo
System.out.println("hi ");
System.out.println("welocme to ");
EXAMPLE:
---------
class Demo
out.println("hi ");
out.println("welocme to ");
IMPORT STATEMENTS:
------------------
eg: System.out
Math.sqrt()
STATIC IMPORT:
--------------
2. less readability
PACKAGES
----------------------------
packages is a folder contains .class files representing related classes and interface
1. MODULARITY
2. ABSTRATCION
3. SECURITY
4. SHARABILITY
5. REUSABILITY
1. MODULARITY: Dividing the requirment into number of pieces and providing soloution for every individual parts
and combining all the solution
Module is a folder that contains .class files representing the related classes and interface
3.SECURITY: In java apps packages are able to provide abstraction and encapsulation where both are provide security
to the app.
4.SHARABILITY: I fwe declare packages one time tehn we are able to share that packages content to any no of apps
or module at a time.
5.REUSABILITY: If we declare a packages one time then we are able to reuse any number of time within a single app
or more than one app.
TYPES OF PACKAGES:
--------------------
2. PREDEFIEND PACKAGES
------------------------
-----------------------------
package package_Name;
-----------------------------------
import package_name.*;
----------------
package p1;
class B
{
System.out.println("package creation");
OUTPUT:
-------
package creation
C:\Users\SAHANA RAM\Desktop\Program>
----------------
package p1;
class C
OUTPUT:
--------
package creation
----------------
package p1;
class C
OUTPUT:
-------
D:\sep_batch\javaPrograms\DAY-42>javac -d S: C.java
D:\sep_batch\javaPrograms\DAY-42>S:
S:\>java p1.C
package creation 1
----------------
package p2.p3;
class D
}
}
OUTPUT:
--------
D:\sep_batch\javaPrograms\DAY-42>java p2.p3.D
sub-package creation
----------------
package p1;
class D
OUTPUT:
-------
D:\sep_batch\javaPrograms\DAY-42>javac -d . D.java
D:\sep_batch\javaPrograms\DAY-42>java p1.D
EXAMPLE: CASE:6 --> Multiple package creation within a same class is not
allowed
-----------------
package p1;
package p2;
class D
{
System.out.println("sub-package creation ");
OUTPUT:
-------
package p2;
case:7
--------------------------------------------
EXAMPLE:
--------
package Multiple.pack1;
class A
class B
class Demo
a.fun1();
B b = new B();
b.fun2();
OUTPUT:
-------
D:\sep_batch\javaPrograms\DAY-42>java Multiple.pack1.Demo
inside class A
inside class B
-------------------------------------
There are 3 ways to import the packages into the java program they are:
EXAMPLE:
---------
Student.java
-------------
package pack2;
String name;
int roll_no;
this.name=name;
this.roll_no=roll_no;
}
StudentApp.java
----------------
package pack1;
class StudentApp
s.getData();
OUTPUT:
--------
D:\sep_batch\javaPrograms\DAY-43>javac -d . Student.java
D:\sep_batch\javaPrograms\DAY-43>javac -d . StudentApp.java
D:\sep_batch\javaPrograms\DAY-43>java pack1.StudentApp
PRE-DEFIEND PACKAGES :
------------------------
These packages are provided by JAVA programming language along woth java software.
examples:
----------
1. java.lang
--> This package is default package in java application, and need no to import this package to the present java file,
when we save java file with
This package will provide funadamental classes and interfaces which is required to crearte java programs.
eg: String.class,StringBugffer,StringBuilder,System,class,Int,Float,,,,,,,
2. java.io
--> This package is able to provide predefiend classes and interface inorder to perform the INPUT AND OUTPUT
operations in java.
eg: InputStream,Serializable,FileWriter,FileOutputStream.......................................
3. java.util
--> This package is able to provide all pre-defiend classes and interface to represent the DATA STRUCTURS
eg: Collection,List,Set,Queue,Map,HashMap,LinkedList,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
---------------------------------------------------
java.awt
javax.swing
java.net
java.sql
java.rmi
programming format:
-------------------
1.comment section
2.packages
3.import
-----------------------------
2. multiline comment
3. Documentation comment
--------------------------------
class Demo
int a;
int b;
int c;
a=20;
b=5;
c=a+b;
OUTPUT:
-------
-------------------------------
class Demo
int a;
int b;
int c;
a=20;
b=5;
c=a+b;
c=a-b;
c=a*b;
OUTPUT:
-------
---------------------------------
/**
/**
*/
return a+b;
NOTE: JAVADOC COMMAND WILL CREATE A HTML PAGE IN WHICH THE DOCUMENTATED DETAILS
WILL BE PRESENT.
'throws' keyword
------------------
--> In Java program if there is a possibility of rising checked exception then compulsorly we should handle it.
case-1
-------
EXAMPLE:
---------
import java.io.*;
class Demo
System.out.println("Hello World!");
OUTPUT:
-------
Case-2
-------
EXAMPLE:
--------
import java.io.*;
class Demo
Thread.sleep(10000);
OUTPUT:
--------
Thread.sleep(10000);
NOTE: From the above examples we came to know that whenever checked exception arisied we must either caught is
using try catch block or we must declared
---------------------------------------------------------
case-3
------
EXAMPLE:
--------
import java.io.*;
class Demo
try
Thread.sleep(10000);
catch (InterruptedException e)
System.out.println("exception caught..!");
OUTPUT:
-------
-------------------------------------------------------
case-4
------
EXAMPLE:
--------
import java.io.*;
class Demo
Thread.sleep(10000);
OUTPUT:
-------
--> throws keyword will not handle the exception rather it will duck the exception or propagate the exception to the
caller.
--> throws keyword is used only for checked exception.using throws keyword on unchecked exception will not make
any impact.
--> it will not lead to normal termination of the program it just helps for compiling the code successfully.
case-5
-------
EXAMPLE:
--------
import java.io.*;
class Demo
System.out.println(10/0);
OUTPUT:
-------
NOTE: throws keyword we can use to delegate responsbility of exception handling to the caller[method,main,jvm].
case-6
-------
EXAMPLE:
--------
import java.io.*;
class Demo
{
method1();
method2();
method3();
Thread.sleep(10000);
OUTPUT:
-------
EXAMPLE:
---------
import java.io.*;
class Demo
{
}
OUTPUT:
-------
EXAMPLE:
--------
import java.io.*;
OUTPUT:
-------
NOTE: throws keyword is applicable only for throwable objects[CHECKED EXCEPTION ONLY]
EXAMPLE:
--------
import java.io.*;
class Demo
OUTPUT:
-------
EXAMPLE:
--------
import java.io.*;
OUTPUT:
-------
EXAMPLE:
--------
import java.io.*;
class Demo
OUTPUT:
-------
EXAMPLE:
---------
import java.io.*;
class Demo
OUTPUT:
-------
*throw and throws keywords impacts only on exceptions and not on errors*
conclusion:
-------------
throw : to excplicitly create the exception object and hand over to jvm.
throws : to delegate the responsibility of exception handling to the caller method [where caller method may be a
method or constructor or jvm]
-----------------------------------------------
EXAMPLE:
--------
import java.util.*;
DistinctionException(String exp_msg)
super(exp_msg);
FirstClassException(String exp_msg)
super(exp_msg);
SecondClassException(String exp_msg)
super(exp_msg);
}
}
class CustException
if (percentage>=75)
else if (percentage>=60)
else if (percentage>=35)
else
OUTPUT:
-------
65
Exception in thread "main" FirstClassException: FirstClass ....still you have scope to improve
at CustException.main(CustException.java:39)
RE-THROWING THE EXCEPTION:
--------------------------
--> The process of catching an exception and throwing it to the caller method is called as re-throwing the exception.
EXAMPLE:
--------
import java.io.*;
class Demo1
try
open(path);
catch (FileNotFoundException e)
e.printStackTrace();
try
catch (FileNotFoundException e)
System.out.println(e);
throw e;
}
}
OUTPUT:
-------
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Demo1.open(Demo1.java:22)
at Demo1.main(Demo1.java:10)
---------------------------------------------------
1. invalid
----------
try
2. invalid
----------
try
try
{
catch ()
3. valid
---------
try
try
catch ()
catch ()
4. invalid
----------
catch ()
5.invalid
---------
catch ()
finally
{
6. valid
---------
try
catch ()
finally
7. invalid
-----------
try
finally
finally
8.valid
---------
----------
10. valid
-----------
try
try
catch ()
catch ()
finally
ACCESS_MODIFIERS
---------------------------------
These are the keywords in object oriented language that set the accessibility of classes,methods and other members.
ACCESS_MODIFIERS IN JAVA:
-------------------------
1. public
2. protected
3. default
4. private
5. final
6. abstract
7. static
8. synchronized
9. native
10. strictfp
11. transient
12. volatile
---------------------------------------------------
1. public
2. default
3. final
4. abstract
5. strictfp
---------------------------------------------------
1. public
2. default
3. final
4. abstract
5. strictfp
6. private
7. protected
8. static
PUBLIC/DEFAULT access_modifers w.r.t classes:
----------------------------------------------
--> If a UDC is declared as 'public' then we can access that class from anywhere.
EXAMPLE:
--------
package pack1;
public class A
System.out.println("inside pack1");
package pack2;
import pack1.A;
class B
A a = new A();
a.fun1();
OUTPUT:
-------
inside pack1
NOTE: If we want to use methods of a class in another package then we must make the UDC as 'public'.
if UDC is public in nature then members of that class can be accessed within the same package and also from differnt
packages.
EXAMPLE:
--------
class Demo
class Demo1
d.fun1();
OUTPUT:
-------
NOTE: If we want to use methods of a class in the same package then we must make the UDC as 'default'.
if UDC is default in nature then members of that class can be accessed within the same package and can not be
accessed from differnt packages.
------------------------------------------------
abstract modifier is only applicable for classes and methods and it is not applicable for variables
NOTE: If any method present in the class is abstract in nature then the class should be prefixed with abstract keyword.
NOTE: Illegal combinations with abstarct keyword:
1. final
2. synchronized[multithreading]
3. private
4. native
5. static
6. strictfp
--------------------------------------------------
--> This modifier is applicable for classes and methods and not applicable for variables.
ie, based on 16 bit 32 bit 64bit we will get different floating point.
To strandarize the result and to achive platform independent strictfp is used w.r.t floating point calculations.
------------------------
--> If strictfp is used on methods then all the floating points in the methods should fallow "IEE754" format. To achive
standarization and platform
independence
------------------------
--> If a UDC is declared as strictfp then every floating point within the class is calculated for concrete methods as per
IEE754 format.
EXAMPLE:
--------
abstract strictfp class Demo2
OUTPUT:
-------
illegal combination
--------------------------------------------------
--> public members can be accessed from any where but, its correspondingg class should public.
2. default members:
--> default members can be accessed only within the current package.
3. private members:
--> if a members is private we can use only within the current UDC.
4. protected members:
--> can be accessed within the current package but, only in child classes of outside package.
EXAMPLE:
--------
package p1;
package p2;
import p1.sample;
//s.fun1();
//s.fun1();
s2.fun1();
OUTPUT:
-------
[ACCESS-MODIFIES PART-2]
----------------------------
static access-modifier:
-----------------------
--> static access modfiers is applicable only on methods and variables and not applicable on top level classes.
legal combinations:
-------------------
static variable
static block
static method
native access_modifier:
------------------------
native access_modiers are applicable only to methods.It is not applicable to variables,inner class,top-level class.
-------------------------------
-----------------------------
EXAMPLE:
---------
class Demo
static
class Demo1
d.fun1();
OUTPUT:
-------
at Demo.fun1(Native Method)
at Demo1.main(Demo1.java:15)
-----------------------------------
transient access_modifier:
----------------------------
--> this access_modifier is only applicable for variables.It is used only during the process of 'serialization mechanism'.
serialization : saving the data of an object in a file.
volatile access-modifiers:
--------------------------
but,
DAY-25
-------
STRINGS
Strings is a collection of characters or a array of characters.It is a non-primitive datatype.In java Strings are treated as
object becuase the memory
is allocated in heap segment.
Example: Sagar,StudyOnline,Java,September.......etc
Based on creation of the creation of the strings it is classified into two types:
1.IMMUTABLE STRINGS
2.MUTABLE STRINGS
IMMUTABLE STRING:
Immutable strings are such strings once it is created it can not be altered or changed.
-->Whenever we create a string using new keyword then the strings is created in heap segment[non-constant pool] and
here duplicates are not allowed.
-->Whenever we create a string without using new keyword then the strings is created in heap segment[constant pool]
and here duplicates are allowed.
EXMAPLE:1
// comparing the two strings using the == symbol.
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagar";
if(s1 == s2)
{
System.out.println("reference are equal");
}
else
{
System.out.println("reference are not equal");
}
}
}
OUTPUT:
-------
reference are equal
NOTE: == symbol will always compare the memory address of the object.
EXAMPLE:2
---------
// comparing the two strings using the equals() method .
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagar";
if(s1.equals(s2))
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}
}
}
OUTPUT:
-------
Strings are equal.
NOTE: equals method will compare the data present inside the two string objects
EXAMPLE:3
---------
// comparing the two strings using the == symbol .
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("sagar");
if(s1 == s2)
{
System.out.println("reference are equal");
}
else
{
System.out.println("refrence are not equal");
}
}
}
OUTPUT:
-------
refrence are not equal
EXAMPLE:4
---------
// comparing the two strings using the equals method .
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("sagar");
if(s1.equals(s2))
{
System.out.println("String are equal");
}
else
{
System.out.println("String are not equal");
}
}
}
OUTPUT:
-------
String are equal
EXAMPLE:5
---------
// comparing the two strings using the equalsIgnoreCase() method .
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("SAGAR");
if(s1.equalsIgnoreCase(s2))
{
System.out.println("String are equal");
}
else
{
System.out.println("String are not equal");
}
}
}
OUTPUT:
-------
String are equal
NOTE: equalsIgnoreCase() method will compare the data present in the string object by ignoring its case.This is
method is used because java is
case sensitive.
EXAMPLE:6
---------
class Demo1
{
public static void main(String[] args)
{
String s1 = "sagar";
System.out.println(s1);
}
}
NOTE: java.lang.* package(default). Whenever we try to use the String class in the program it will be by default
imported from the jvm.
Whenever we try to print the reference (memory address) of a string, value is displayed instead of address.
EXAMPLE:7
---------
class Demo1
{
public static void main(String[] args)
{
String s1 =new String("sagar");
String s2 =new String("sagar");
String s3 ="sagar";
String s4 ="sagar";
System.out.println(s1 == s3);
System.out.println(s2 == s4);
}
}
OUTPUT:
-------
false
false
DAY-26
------
CONCATINATION OF TWO STRINGS.
Concatination of two strings can be done in two ways:
1. using the + operator
2. using the concate() method.
EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar" + "ram";
String s2 = "sagar" + "ram";
System.out.println(s1==s2); // true
System.out.println(s1.equals(s2)); // true
}
}
EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
String s3 = s1+"ram";
System.out.println(s2==s3); // false
System.out.println(s2.equals(s3)); // true
}
}
NOTE: Whenever we try to concatinatewith the use of variables of strings type then the memory will be allocated in
non-constant pool.
In the above program string value is getting concatinated with a refrence variable hence string varibale s3 is allocated
in non constant pool.
EXAMPLE:3
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
s1.concat("ram");
System.out.println(s1); --> sagar
}
}
EXAMPLE:4
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
String s3 = "sagar";
s1.concat(s3);
s1= s1+"kumar";
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1==s3);
}
}
output:
sagarkumar
sagarram
sagar
false
EXAMPLE:5
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
System.out.println(s1 == s2); // false
String s3 = new String("sagar");
String s4 = new String("sagarram");
System.out.println(s3 == s4); // false
System.out.println(s2.equals(s4)); // true
String s5 = "sagarram";
String s6 = "sagar"+"ram";
String s7 = s1+"ram";
System.out.println(s6==s7); // false
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
}
}
OUTPUT:
-------
false
false
true
false
sagar
sagarram
sagar
sagarram
sagarram
sagarram
sagarram
NOTE: in java one object can have multiple refrence variables.In the same way any modification done on the object
will result in creation of brand
new object.
In a project if a string object is same for multiple refrences then instead of creating mutiple string object we create a
single string object which
will be shared among multiple refrence variable.
Hence it improves the performance of the program.These strings can be created without using the new keyword and
memory for such strings will be allocated
in constant pool.
The problem in this apporach is since multiple ref are pointing to same object modification made by one of the ref
variable on object will affect the
other reference variables also,
inorder to overcome this problem strings are made it as immutable.ie once the string is created it can not be altered any
modification perdformed will
result in creation of brand new object.
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toUpperCase());
System.out.println(s2.toLowerCase());
System.out.println(s1.length());
System.out.println(s1.startsWith("stu"));
System.out.println(s1.endsWith("ine"));
System.out.println(s1.contains("dyon"));
System.out.println(s1.indexOf("y"));
System.out.println(s1.charAt(4));
}
}
output:
-------
studyonline
STUDYONLINE
STUDYONLINE
studyonline
11
true
true
true
4
y
-----------------------------------------------------------------------------------------------------------------------------------------------
--
DAY-27
------
EXAMPLE:1
----------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
s1.concat("ram");
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
EXAMPLE:2
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
s1.concat("ram");
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
intern() method:
----------------
It is used to create the copy of string object in the constant pool with the help of non-constant pool reference.
EXAMPLE:1
--------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = s1.intern();
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);
}
}
OUTPUT:
-------
sagar
sagar
false
EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = new String("sagar");
String s3 = s2.intern();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s1 == s3);
}
}
OUTPUT:
-------
sagar
sagar
sagar
false
false
true
trim() method.
--------------
It is used to remove the blank spaces in the begging and ending of the string.However it will not remove the spaces in
b/w the strings.
EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = " Study Online ";
System.out.println(s1.trim());
}
}
OUTPUT:
-------
Study Online
charAt() method.
-----------------
The character in the string cannot be accessed directly.It can be accessed only using charAt() method.
EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "Study Online";
System.out.println(s1[2]);
}
}
OUTPUT:
-------
COMPILATION ERROR
EXAMPLE:2
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "Study Online";
System.out.println(s1.charAt(2));
}
}
OUTPUT:
-------
u
compareTo() method.
-------------------
refer diagram:
It is used to compare two strings lexio graphically ie each character in both the strings are converted in to unicode and
compared.
when this method is used result will be in fallowing way:
EXAMPLE:
--------
class Demo
{
public static void main(String[] args)
{
String s1 = "abhilash";
String s2 = "asha";
int res = s1.compareTo(s2);
if(res == 0)
{
System.out.println("Strings are equal");
}
else if (res > 0)
{
System.out.println("String s1 is greater than String s2");
}
else
{
System.out.println("String s1 is lesser than String s2");
}
}
}
OUTPUT:
-------
String s1 is lesser than String s2.
Whenever the content of the string is frequently changing then dont create the string using String class rather create
using StringBuffer or StringBuilder
class.
If we try to create a string when content are frequently changing using the string class for every modification new
string objects will be created.
Hence it is not recommanded to create such Strings using string class.
EXAMPLE:1
--------
class Demo
{
public static void main(String[] args)
{
//String s1 = new String("sagar");
//String s2 = "sagar";
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 =s1.concat("ram");
System.out.println(s1);
System.out.println(s2);
}
}
OUTPUT:
-------
sagar
sagarram
EXAMPLE:3
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
s1.append("ram");
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
sagarram
EXPLAIN THE DIFFERENCE B/W == AND EQUALS() METHOD IN STRING CLASS AND STRINGBUFFER
CLASS.
------------------------------------------------------------------------------------------
String class --> == will compare the memory address of two string objects.
equals() method will compare the data present in the two String objects.
StringBuffer --> == will compare the memory address of two string objects.
equals() method will compare the memory address of the two String objects.
EXAMPLE:4
---------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
StringBuffer s2 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);
}
}
OUTPUT:
-------
sagar
sagar
false
EXAMPLE:5
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
StringBuffer s2 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.equals(s2));
}
}
EXAMPLE:1
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer();
System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());
s1.append("students");
System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());
System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());
System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());
}
}
OUTPUT:
---------
16
0
students
16
8
students prepare for exams
34
26
students prepare for exams and get placed in a good company
70
59
ensureCapacity() method.
------------------------
In order to set the capacity for paticular value we can use ensureCapacity() method.
EXAMPLE:1
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer();
System.out.println(s1.capacity());
s1.ensureCapacity(1500);
System.out.println(s1.capacity());
}
}
OUTPUT:
-------
16
1500
EXAMPLE:2
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer(1500);
System.out.println(s1.capacity());
}
}
OUTPUT:
-------
1500
EXAMPLE:3
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1.capacity()); // 16 + number of characters
// 16 + 5 = 21
}
}
OUTPUT:
-------
21
EXAMPLE:1
----------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s1.charAt(2));
s1.setCharAt(2,'p');
System.out.println(s1);
s1.deleteCharAt(2);
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
g
sapar
saar
EXAMPLE:1
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
s1.insert(5,"is a good boy..!");
System.out.println(s1);
s1.insert(0,6);
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
sagaris a good boy..!
6sagaris a good boy..!
EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.delete(1,5);
System.out.println(s1);
}
}
OUTPUT:
-------
StudyOnline
SOnline
reverse() method:
-----------------
It is used to reverse the given String
EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.reverse();
System.out.println(s1);
}
}
OUTPUT:
-------
StudyOnline
enilnOydutS
setLength() method:
-------------------
It is used to set the length of the string.
EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.setLength(5);
System.out.println(s1);
}
}
OUTPUT:
-------
StudyOnline
Study
DAY-29
-------
METHOD CHAINING WITH RESPECT TO STRINGS.
---------------------------------------
Calling multiple methods in the same line is called as method chaining.
EXAMPLE:
--------
StringBuffer s1 = new StringBuffer("Study");
System.out.println(s1.append("online").reverse().length());
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("study");
System.out.println(s1.append("online").reverse().length());
}
}
OUTPUT:
-------
11 --> always in the method chaining the last method result will be displayed.
EXAMPLE:
--------
class Demo
{
public static void main(String[] args)
{
StringBuilder s1 = new StringBuilder("studyonline");
System.out.println(s1);
s1.append(" java");
System.out.println(s1);
}
}
OUTPUT:
-------
StudyOnline
StudyOnline java
EXAMPLE:1
----------
// example for next() method and nextline() method.
----------------------------------------------------
import java.util.*;
class Demo
{
public static void main(String[] args)
{
System.out.println("enter your name:");
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println("the entered name is :" + s);
}
}
OUTPUT:
-------
enter your name:
SAGAR
the entered name is :SAGAR
EXAMPLE 1.1
-----------
// example for next() method and nextline() method.
import java.util.*;
class Demo
{
public static void main(String[] args)
{
System.out.println("enter your name:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("the entered name is :" + s);
}
}
OUTPUT:
-------
enter your name:
study Online
the entered name is :study Online
class Demo
{
public static void main(String[] args)
{
String s1 = "students";
String rev ="";
int len =s1.length();
for (int i=len-1;i>=0;i--)
{
rev = rev+s1.charAt(i);
}
System.out.println("Reversed string is :" + rev);
}
}
OUTPUT:
-------
students
Reversed string is stneduts
EXAMPLE:
--------
// example for checking whether the given string is palindrome or not.
class Demo
{
public static void main(String[] args)
{
String s1 = "madam";
String rev ="";
int len =s1.length();
for (int i=len-1;i>=0;i--)
{
rev = rev+s1.charAt(i);
}
System.out.println("Reversed string is :" + rev);
if (s1.equals(rev))
{
System.out.println("the given string is a palindrome");
}
else
{
System.out.println("the given string is not a palindrome");
}
}
}
OUTPUT:
-------
Reversed string is :madam
the given string is a palindrome
class Demo
{
public static void main(String[] args)
{
char c[] = new char[]{'s','t','u','d','y'};
// option 1
String s1 = String.valueOf(c);
System.out.println(s1);
//option 2
String s2 = new String(c);
System.out.println(s2);
}
}
OUTPUT:
-------
study
study
class Demo
{
public static void main(String[] args)
{
String s1 = "StudyOnline";
System.out.println(s1);
char a[] = s1.toCharArray();
for (char ch :a )
{
System.out.println(ch);
}
}
}
OUTPUT:
-------
StudyOnline
S
t
u
d
y
O
n
l
i
n
e
class Demo
{
public static void main(String[] args)
{
ASSIGNMENTS:
------------
1. count the number of vowels and consonents from the given string string --> hello
2. reverse the words present in given string. sentence --> welcome to
studyonline
DAY-31
------
1. number of words in a given string
--------------------------------------
EXAMPLE:
--------
import java.util.*;
class Demo
{
public static void main(String[] args)
{
String str = " join studyonline to learn programming languages";
StringTokenizer s = new StringTokenizer(str);
int count = s.countTokens();
System.out.println("The number of words in the given string is: "+count);
}
}
OUTPUT:
-------
The number of words in the given string is 6
class Demo
{
public static void main(String[] args)
{
String str = " join studyonline to learn programming languages ";
System.out.println(str);
str = str.replaceAll("\\s","");
System.out.println(str);
}
}
OUTPUT:
------
join studyonline to learn programming languages
joinstudyonlinetolearnprogramminglanguages
b = b+g;
g = b.substring(0,b.length()-g.length());
b=b.substring(g.length());
s1 = "from";
s2 = "form";
s1 = "silent";
s2 = "listen";
import java.util.*;
class Demo
{
public static void main(String[] args)
{
String s1 = "listen";
String s2 = "silent";
if (s1.length()!=s2.length())
{
System.out.println("Strings are not anagram");
System.exit(0);
}
char a[]=s1.toCharArray();
char b[]=s2.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
if(Arrays.equals(a,b))
{
System.out.println("Strings are anagram");
}
else
{
System.out.println("Strings are not anagram");
}
}
}
OUTPUT:
-------
Strings are anagram
-----------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------
EXAMPLE:
--------
class Student
{
private String name;
private int age;
private int roll_no;
}
class StudentApp
{
public static void main(String[] args)
{
Student s1=new Student();
s1.SetName("raju");
System.out.println(s1.getName());
s1.SetAge(21);
System.out.println(s1.getAge());
s1.SetRoll_no(84);
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
raju
21
84
EXAMPLE:2
---------
class Student
{
private String name;
private int age;
private int roll_no;
}
class StudentApp
{
public static void main(String[] args)
{
Student s1=new Student();
s1.SetData("raju",21,84);
System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
raju
21
84
NOTES:
------
1. DATA HIDING:
Data Hiding is hiding the data so that outside person cannot access the data directly. This can be achicved by using
the data members (variable)
as private.
ADAVANTAGES OF ENCAPSULATION:
------------------------------
1. SECURITY TO THE DATA.
2. ENHANCEMENT IS EASY.
-----------------------------------------------------------------------------------------------------------------------------------------------
-------
CONSTRUCTORS
------------------------------
}
}
OUTPUT:
--------
raju
84
class Demo2
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.SetData("somu",89);
System.out.println(s1.getName());
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
somu
89
class Demo2
{
public static void main(String[] args)
{
Student s1 = new Student("bheem",28);
Student s2 = new Student("somu",89);
}
}
OUTPUT:
-------
bheem
28
somu
89
Constructor is a special block or method where name of the constructor is same as the class name.
It is a Specialized setter to initilize the object.
Constructor doesnot have any return type.The access modifier allowed for the Constructor method is
public,private,protected,default.
Constructor are always called during the object creation.