Core Java
Core Java
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
11. Interpretive
1. Simple:
1. Java applications will take less memory and less execution time.
2. Java has removed all most all the confusion oriented features like pointers, multiple-inheritance,.....
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 Neutral:
Java is an Arch Neutral Programming language, because, Java allows its applications to compile On one H/W
Arch and to execute on another H/W Arch.
5. Portable:
Java is a portable programming language, because, JAVA is able to run its applications under all the operating
systems and under all the H/W Systems.
1
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, and it allocates and de-allocates 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 separate middleware service in the form of JAAS [Java Authentication
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 then that
programming language is called as Dynamic Programming Language.
JAVA is a dynamic programming language, because, JAVA allows memory allocation for primitive data types
at RUNTIME.
9. Distributed:
If we design any java application with out using client-Server arch then that java application is
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 separate module that is "J2EE/JAVA EE".
10. Multi-Threaded:
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 independent,
Arch Neutral, Portable, Robust, Dynamic,......
3
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
; --> 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
4
15 chacters are sufficent.
2. 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:
Excerise:
7. sachinTendulker -->VALID
8. sachin_Tendulker -->VALID
5
9. sachin$Tendulker -->VALID
Keywords or Reserved words are the words in a language that are used for some internal process some
predefined actions. These words are therefore not allowed to use a variable names or objects. Doing this will
result into compile time error.
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
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
6
29. new: Creates new objects
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.
7
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.
Ex 01:
int Exception=10;
System.out.println(Exception);
Output: 10
Ex 02:
String String="String";
System.out.println(String);
Output: String
Ex 03:
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.
8
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:
4. String 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.
9
Number Systems in Java:
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.
If we want to prepare numbers in octal number System then we have to use the symbols like
Ex:
10
3. Decimal Number Systems[BASE-10]:
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:
Note: If we provide numbers in all the above number systems in java applications then compiler will
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.
11
Ex 01:
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);
Output: 10
10
12
12
10
10
Ex 02:
class Test
int a=5;
System.out.println(++a-++a);
Output: -1
12
Ex 03:
class Test
int a=5;
System.out.println((--a+--a)*(++a-a--)+(--a+a--)*(++a+a++));
Output: 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
13
To prepare java applications, JAVA has provided the following data types.
following formula.
n-1 n-1s
-2 to 2 - 1
8-1 8-1
-2 to 2 - 1
77
-2 to 2 - 1
-128 to 128 - 1
14
-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 statement 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
16
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 01:
class Sample
int i=10;
byte b=i;
System.out.println(i+" "+b);
Example 02:
class Sample
byte b=65;
char c=b;
System.out.println(b+" "+c);
17
Example 03:
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 04:
class Sample
char c='A';
int i=c;
System.out.println(c+" "+i);
OP: A 65
Example 05:
class Sample
byte b=128;
18
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 06:
class Sample
byte b1=60;
byte b2=70;
byte b3=b1+b2;
System.out.println(b3); }}
Example 07:
class Sample
byte b1=30;
byte b2=30;
byte b3=b1+b2;
System.out.println(b3);
X+Y=Z
byte+byte=int
19
byte+short=int
short+int=int
byte+long=long
long+float=float
float+double=double
Example 08:
class Sample
long l=10;
float f=l;
System.out.println(l+" "+f);
OP: 10 10.0
Example 09:
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.
20
To perform explicit type casting we have to use the following pattern.
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 01:
class Sample
int i=10;
byte b=(byte)i;
System.out.println(i+" "+b);
OP: 10 10
Example 02:
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
21
type is compatible with left side variable data type then compiler will not rise any error and compiler
When we execute the above program, when JVM encounter the above assignment statement then JVM
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:
if
switch
3. Iterative Statements:
for
while
do-while
4. Transfer statements:
break
continue
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
22
1. if:
Syntax 01:
if (condition)
{ instructions--- }
Syntax 02:
if(condition)
{ ---instructions---- }
else
{ ----instructions--- }
Syntax 03:
if(condition)
{ ---instructions---- }
else if(condition)
{ ---instruction---- }
else if(condition)
{ ---instructions---- }
else
{ ----instructions---- }
Example 01:
class Test
int i=10, j;
if(i==10)
j=20;
else
j=30;
System.out.println(j); } }
23
Status: No Compilation Error
OP: 20
Example 02:
class Demo
int i=10, j;
if(i==10)
j=20;
else if(i==20)
j=30;
else
j=40;
System.out.println(j);
OP: 20
Example 03:
class Test
int j;
24
if(i == 10)
j=20;
System.out.println(j); } }
OP: 20
Example 04:
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; }
25
else
{ j=30; }
System.out.println(j); } }
OP: 30
Example 01:
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.
2. switch
'if' is able to provide single condition checking bydefault, but, switch is able to provide multiple
conditions checking’s.
Syntax:
switch(Var)
case 1:
-----instructions-----
break;
case 2:
----instructions------
Break;
26
case n:
----instructions-----
break;
default:
----instructions-----
break;
Example:
class Demo
int i=10;
switch(i)
case 5: System.out.println("Five");
break;
break;
break;
break;
default: System.out.println("Default");
break;
Output:Ten
1. switch is able to allow the data types like byte, short, int and char.
Example 01:
byte b=10;
27
switch(b) { ---- }
Example 02:
long l=10;
switch(l)
{ ---- }
Example 03:
class Demo
char c='B';
switch(c)
break;
break;
break;
break;
default: System.out.println("Default");
break;
1. *Upto JAVA6 version, switch is not allowing "String" data type as parameter, "JAVA7" version
28
Example 04:
class Demo
String str="BBB";
switch(str)
break;
break;
break;
break;
default: System.out.println("Default");
break;
OP: BBB
2. In switch, all cases and default are optional, we can write switch without cases and with default, we
can write switch with cases and without default, we can write switch without both cases and default.
Example 05:
int i=10;
switch(i)
{}
OP: No Output.
29
Example 06:
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 continuously right from matched case until it
Example 07:
class Demo
int i=10;
switch(i)
case 5: System.out.println("Five");
default: System.out.println("Default");
30
}}
Output: 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 08:
class Demo
byte b=126;
switch(b)
break;
break;
break;
break;
default: System.out.println("Default");
break;
31
Iterative Statements:
These statements are able to allow JVM to execute a set of instructions repeatedly on the basis of a
particular condition.
Example 01:
1. for
2. while
3. do-while
1. for
Syntax:
{ ----instructions----- }
Example 01:
class Demo
for(int i=0;i<10;i++)
{ System.out.println(i); }
Output: 0
---
---
Expr1-----> 1 time
Expr2-----> 11 times
Expr3-----> 10 times
32
Example 02:
class Demo
int i=0;
for(;i<10;i++)
{ System.out.println(i); }
OP: 0 ---- 9
Example 03:
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
33
Example 04:
class Demo
{ System.out.println(i+" "+f); }
Example 05:
class Demo
{ System.out.println(i+" "+j); }
Example 06:
class Demo
{ System.out.println(i+" "+j); }
OP: 0 0
11
34
22
Reason:
In for loop, Expr1 is able to allow almost 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 07:
class Demo
{ System.out.println(i); }
Example 08:
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
35
Example 08:
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 immediately 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 completely 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;
{}
36
Example 09:
class Demo
for(int i=0;i<10;)
System.out.println(i);
i=i+1;
Example 10:
class Demo
for(int i=0;i<10;System.out.println("Hello"))
System.out.println(i);
i=i+1;
}}}
Output: 0
Hello
Hello
----
----
37
Hello
Note: In for loop, Expr3 is optional, we can write for loop with out expr3, we can provide any
statements as expr3.
Example 11:
class Demo
for(;;)
Example 12:
class Demo
for(;;);
Example 13:
class Demo
for(;;)
{}
}}
38
Status: No Compilation Error. Output: No Output, but, JVM will be in infinite loop
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 curly braces to the for loop.
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 01:
class Test
int i=0;
while(i<10)
System.out.println(i);
i=i+1;
Example 02:
class Demo
int i=0;
while()
System.out.println(i);
39
i=i+1;
Example 03:
class Demo
System.out.println("Before Loop");
while(true)
System.out.println("Inside Loop");
System.out.println("After Loop");
3. 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 body
will be executed.
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.
40
Syntaxes:
while(Condition)
---instructions-----
do
---instructions---
While(Condition);
Example 01:
class Demo
int i=0;
do
System.out.println(i);
i=i+1;
while (i<10);
OP: 0, 1, 2,.... 9
41
Example 02:
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
2. 2.continue
3. 3.return
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 01:
class Demo
for(int i=0;i<10;i++)
if(i==5)
break;
42
}
System.out.println(i);
OP: 0
1234
Example 02:
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 immediately after break statement then that statement is
43
Example 03:
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 nested loop, it
will not give any effect to outer loop.
In the above context, if we want to give break statement effect to outer loop, not to the nested loop then we have to
use "Labelled break" statement.
Syntax:
break label;
Where the provided label must be marked with the respective outer loop.
Continue…..
44
Example 01:
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 in-order to continue with next iteration.
Continue….
45
Example 01:
class Demo
for(int i=0;i<10;i++)
if(i == 5)
{ continue; }
System.out.println(i);
OP:
012346789
Example 02:
class Demo
System.out.println("before Loop");
for(int i=0;i<10;i++)
if(i == 5)
continue;
46
System.out.println("After loop");
Reason: If we provide any statement immediately after continue statement then that statement is unreachable
statement, where compiler will rise an error.
Example 03:
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);
OP:
If we provide continue statement in netsted loop then continue statement will give effect to nested loop
47
Example 04:
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++)
48
if(j==5)
continue l1;
System.out.println(i+" "+j);
Output:
00
01
02
03
04
10
11
12
13
14
---
---
90
01
92
93
94
OO
49
ARRAYS
Whenever 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.
An array is an indexed collection of fixed number of homogeneous data elements.
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 achieve
readability.
Once the array is created with some size we can not alter that during execution.
We can use concept called as COLLECTIONS to solve 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.
The arrays are created inside the object hence the memory is allocated in heap memory segment.
Note: Whenever 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
50
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 01 : 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
51
Example 02: 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
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]);
}}
52
Output: 10
20
30
40
50
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 05:
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
53
Examples for 1D (Single Dimension) array:
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
54
Enter the marks:
37
59
64
87 92 37 59 64
class Demo1
a[i]= sc.nextInt();
{ System.out.print(a[i]+" "); }
Output:
87 92 37 59 64
55
Example 03: Demo1.java
class Demo1
int i;
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
56
Example 04: 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:
87 92 37 59 64
57
Example 05: Demo1.java
class Demo1
int n = sc.nextInt();
a[i] = sc.nextInt();
Output:
87 92 37 59 64
58
Example 06: Demo1.java
//Write Program 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:
59
Enter the marks of the students: 60
2. 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[];
Creation of 2D array:
60
Create: a = new int[2][3];
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
Write a Program 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();
61
for (int i=0;i<=2;i++)
System.out.println(" ");
Output: 10 20 30 40 50
60 70 80 90 100
NOTE:
a.length -> 5
a.length ->3
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
62
Example for 2D jagged array:
import java.util.*;
class Demo
a[i][j]= sc.nextInt();
System.out.println(" ");
Output: 10 20 31
41 51
61 71 81 91
63
Example:
class Demo1
System.out.println(a.length); --> 3
System.out.println(a[0].length); --> 5
System.out.println(a[1].length); --> 5
Declaration of 3D array:
int [][][] a;
int a[][][];
int[][] a[];
int[] [][]a;
int[] []a[];
Creation of 3D array:
initilize: a[0][0][0]=10;
64
Example for 3D regular array:
import java.util.*;
class Demo
a[i][j][k]= sc.nextInt();
System.out.println(" ");
65
Output: 10 20 30
40 50 60
70 80 90
100 11 12
13 14 15
16 17 18
import java.util.*;
class Demo
a[i][j][k]= sc.nextInt();
}
66
}
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
67
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
68
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});
}}
69
OBJECT ORIENTATION:
ORIENTATION view point.
eat()
{
------
------
}
sleep()
{
-------
-------
}
run()
{
-------
-------
}
CREATION OF OBJECT:
An object can be created in 5 differnt ways:
1. using 'new' keywords
2. using newInstance()
3. using clone()
4. using FactoryMethod
5. using deserialization
example1: LionApp.java
class Lion
{
String name;
String breed;
String gender;
void eat()
{
System.out.println("lion always eats non-veg");
}
void sleep()
{
System.out.println("lion sleeps 10 hr per day...!");
}
void run()
{
System.out.println("lion runs faster than human being");
}
}
class LionApp
{
public static void main(String[] args)
{
Lion l1 = new Lion();
l1.eat();
l1.sleep();
l1.run();
}
}
Output:
-------
lion always eats non-veg
lion sleeps 10 hr per day...!
lion runs faster than human being
NOTE: 1.Always program execution starts from the class where main method is present.
72
2.To access the variables and methods present in differnt class we will make use of reference varibale.
void eat()
{
System.out.println("lion always eats non-veg");
}
void sleep()
{
System.out.println("lion sleeps 10 hr per day...!");
}
void run()
{
System.out.println("lion runs faster than human being");
}
}
class LionApp
{
public static void main(String[] args)
{
Lion l1 = new Lion(); // object creation is done using new keyword
73
}
}
output:
simba
Asiatic
male
lion always eats non-veg
lion sleeps 10 hr per day...!
lion runs faster than human being
VARIABLES:
Variables are classified into two types based on:
1. Data representation
2. Positional declaration
1.1 Primitive variable: If a variable holds primitive data then such variables are called Primitive varaible.
Ex: int a = 46;
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.
Ex: Lion l1 = new Lion();
2. Positional declaration: based on where we declare the varibales it has been classified into 3 types.
2.1 Instance variable
2.2 Static variable
2.3 Local variable
2.1 INSTANCE VARIABLE:
WHAT IS AN INSTANCE VARIABLE?
Value of a variable if it changes from object to object then such variables are called as Instance
Variables.
NOTE:
--> For every object separate copy of instance variables is created.
Example:
Class Demo
{
int x;
float y;
boolean z;
void method1()
74
{
}
}
Instance Variables are declared within the class but outside the methods/blocks.
For instance variable memory will be allocated during object creation and deallocation will occur during
object destruction. Hence scope of instance variable is same as object scope.
HOW WE CAN ACCESS THE INSTANCE VARIBLES?
Instance variables can not be accessed from static area.
Ex:
class Demo
{
int x =25;
public static void main(String[] args)
{
System.out.println(x);
}
}
because: jvm will not allow to access instance variable in static region.
int x =25;
public static void main(String[] args)
{
}
}
We can make our project 100% object oriented by using wrapper classes.
Example
byte b = 10; Byte b = new Byte(10);
int x = 25; Int i = new Int(25);
NOTE: The disadvantage with wrapper class is that it will occupy more memory.
NOTE: For all the objects only one copy of static variable is created and it is shared by every object.
Example: People.java
class People
{
String name;
int addhar_no;
static String nationality="Indian";
}
Output:
-------
Indian
Indian
Indian
NOTE: If the values of static variable is modified then it will be reflected on all the objects
Example: Demo.java
class Demo
{
static int x = 25;
int y = 50;
public static void main(String[] args)
{
d1.x = 143;
d1.y = 420;
System.out.println(d1.x); // 143
System.out.println(d1.y); // 420
}
}
}
5. HOW WE CAN ACCESS THE LOCAL VARIABLES?
Local Variables can be accessed only within the method/block. Outside the method we cannot access.
Example: refer above example
Example: 01 Demo.java
class Demo
{
public static void main(String[] args)
{
79
int x;
System.out.println("java");
//if local variables are not used then we won’t get compilation error
}
Output:
java
Example: 02 Demo.java
class Demo
{
public static void main(String[] args)
{
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: 03
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
{
public static void main(String[] args)
{
int x = 0;
System.out.println("java");
System.out.println(x);
}
}
Output:
java
0
80
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
{
public static void main(String[] args)
{
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;
public static void main(String[] args)
{
Demo d1 = new Demo();
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);
81
System.out.println(d1.name);
System.out.println(d1.roll_no);
}
}
Output: sagar
24
sandesh
25
sandesh
25
82
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 1:
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()
83
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Demo
84
ref = new CargoPlane();
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryCargo();
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryPassenger();
ref.takeOff();
ref.fly();
ref.land();
//ref.CarryArms();
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 cannot access the specialized methods.
EXAMPLE 2:
class Plane
String name;
int wheel;
void takeOff()
{
85
System.out.println("plane is taking off");
void fly()
System.out.println("plane is flying");
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
86
void CarryPassenger()
void fly()
void CarryArms()
class Airport
ref.takeOff();
ref.fly();
ref.land();
class Demo
a.allow(cp);
87
a.allow(pp);
a.allow(fp);
plane is landing
plane is landing
plane is landing
5. POLYMORPHISM
EXAMPLE:
class Plane
String name;
int wheel;
void takeOff()
void fly()
System.out.println("plane is flying"); }
88
void land()
System.out.println("plane is landing");
void takeOff()
void fly()
void CarryCargo()
void fly()
void CarryPassenger()
89
void fly()
void CarryArms()
class Demo
ref.fly();
ref.land();
((CargoPlane)(ref)).CarryCargo();
plane is landing
UPCASTING: upcasting refers to the creation of child object and assigning the ref to it.
DOWNCASTING: it means temporary converting the parent ref to child type to access the specialized method
90
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()
91
void CarryCargo()
void fly()
void CarryPassenger()
void fly()
void CarryArms()
class Airport
ref.takeOff();
ref.fly();
ref.land();
92
}
ref.takeOff();
ref.fly();
ref.land();
ref.takeOff();
ref.fly();
ref.land();
class Demo
a.allow(cp);
a.allow(pp);
a.allow(fp);
class Plane
String name;
int wheel;
93
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()
94
void CarryPassenger()
void fly()
void CarryArms()
class Airport
ref.takeOff();
ref.fly();
ref.land();
class Demo1
95
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.
Example:
---------
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
{
96
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();
97
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());
non-static to static method overriding and static to non-static method overriding is not permited in java.
98
Example:
class A
void fun1()
class B extends A
//a.fun1();
B b = new B();
b.fun1();
99
INHERITANCE
Inheritance is a process of a class acquiring the properties(variables) and behaviour (methods) from the other class.
Inheritance can be achieved using extends keywords.
Parent class is a class which gives the properties and behaviour to another class.
child class is a class which inherit the properties 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 01: In order to relate two classes we can use extends keywords.
Example 02:
// related classes
class visitor
int ph_no;
100
void Doctor_conslut() // child class or sub class
-------------
------------
NOTE 02:
NOTE 03:
Whenever the object of child class is created the memory is not only allocated for the instance variable of a child class
but it also allocates the instance variable of the parent class.
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);
101
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);
System.out.println(b.i);
NOTE 05:
Child class can call the instance method of parent class directly.
EXAMPLE:
// note5
class A
102
class B extends A
class Demo
B b= new B();
b.fun2();
b.fun1();
OUTPUT:
NOTE 06:
The child class can call the inherited static methods directly.
EXAMPLE:
// note4
class A
class B extends A
103
void fun2()
class Demo
B b= new B();
b.fun2();
b.fun1();
NOTE 07:
Unlike the private members constructors are also doesn’t participate in the inheritance.
i.e., parent class constructor 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;
104
class B extends A
B() //UDDC
super();
class Demo
B b= new B();
b.display();
J value is 2222
// note7 example:2
class A
int i;
int j;
A(int x)
super();
i=1111;
j=2222;
105
class B extends A
B()
super();
void display()
class Demo
B b= new B();
b.display();
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 then we will get compilation error
NOTE 08:
Even though the parameterized constructor of a sub-class is called yet, the default constructor in the super class is
executed first then the parameterized constructor of the sub-class is executed.
// note8
class A
A() //UDDC
106
//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();
i value is 10
j value is 20
107
NOTE 09:
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
{
108
public static void main(String[] args)
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
{
109
int i =20;
void display()
System.out.println(i);
class Demo
C c1 = new C();
c1.display();
class A
void fun1()
class B extends A
void fun2()
110
class C extends B
void fun3()
class Demo
C c1 =new C();
c1.fun1();
c1.fun2();
c1.fun3();
class A extends B
void fun1()
class B extends A
void fun2()
111
}
class Demo
B b1 =new B();
b1.fun1();
b1.fun2();
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
112
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();
113
this();
EXAMPLE:
class Parent
//IB
//IB
fun1();
Parent() //UDDC
//IB
114
}
//IB
fun2();
Child() //UDDC
2. execute instance variable fallowed by instance blocks and method and finally execute parent class constructor
4. execute instance variable fallowed by instance blocks and method and finally execute child class constructor
115
EXECUTION OF THE STATIC MEMBERS IN INHERITANCE:
EXAMPLE:
class Parent
static
static
fun1();
Parent()
static
static
fun2();
116
System.out.println("child class second static block");
Child()
117
EXECUTION OF BOTH STATIC AND INSTANCE MEMBERS IN INHERITANCE:
EXAMPLE:
class Parent
static
// instance block
// instance block
test1();
// constructor
Parent()
// static method
System.out.println(x);
// instance method
void test1()
118
System.out.println("parent class first instance method");
System.out.println(y);
int b=40;
static
test2();
Child()
System.out.println(a);
void test2()
System.out.println(b);
119
Child.fun1();
Child.fun2();
10
20
--------------------------------
20
40
2. execute the sv sb and sm of parent class and execute it in the top-bottom order
120
INHERITED, OVERRIDDEN, SPECILIZED METHODS.
INHERITED METHOD : any method which is acquired by the child class from the parent class is called as inherited
method.
SPECIALIZED METHOD : methods 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();
122
cp.land();
cp.CarryCargo();
pp.takeOff();
pp.fly();
pp.land();
pp.CarryPassenger();
plane is landing
plane is landing
METHOD OVERRIDING
class Parent
void marry()
void marry()
123
void job() // SPECILIZED METHODS.
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
EXAMPLE:
class Vehicle
void Move()
void Move()
void Move()
124
void Move()
class Demo1
b.Move(); // 1:1
c.Move(); // 1:1
t.Move(); // 1:1
Parent reference to child object in method overriding is all about proving the parent object reference to the child
object to achieve the POLYMORPHISM.
EXAMPLE:
class Vehicle
void Move()
125
class Bike extends Vehicle
void Move()
void Move()
void Move()
class Demo1
v.Move();
v = new Car();
v.Move();
v = new Truck();
v.Move(); // 1:3 } }
126
OUTPUT: bike is moving medium speed
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 reusability, execution time, ease of
share ability.
1.IS-A relationship
2.HAS-A relationship
IS-A : by using this we can achieve the concept of inheritance by doing so we can perform 'code reusability'.
HAS-A : It defines associations b/w the entities to improve the communication b/w the entities for better data
navigation.
1. COMPOSITION
2. AGGREGATION
aggregation will have less dependency with enclosed object whereas composition will have more dependency with
enclosed object
127
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;
return brand;
128
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
129
130
131