Java Notes
Java Notes
JAVA
History
➢ James gosling is the father of java, and introduced in the year 1991.
➢ The software was named as green talk and the team which developed is
called green team. Later the software was renamed as Oak. Oak is a symbol
of strength and it is a national tree for Germany.
➢ There was already existing company called Oak technology which had
become a legal issues due to this legal issues they changed the software
name Oak to java.
➢ James gosling and his team went for a coffee to an island and the coffee
shop named was java hence they kept the software name as java , since they
went for a coffee they kept the coffee bug as a logo for the java software. ➢
Java is a high-level programming language originally developed by Sun
Microsystems and released in 1995. Java runs on a variety of platforms, such
as Windows, Mac OS, and the various versions of UNIX
Tokens
Token is the smallest unit of program.
In token we have,
1. Identifier 2. Keywords 3. Literals
4. Operators 5. Separators 6. Comments
1. Identifier
Identifier is a name given for the java program.
2. Keywords
Keywords are the pre – defined word which has its own meaning.
In java , we have 50 keywords as follows,
Abstract continue for new switch
Page 1
JAVA
3. Literals
Literals are the value which is used in java programming languages.
In literals we have,
1. Number literals: Integer literals → (9,8,7,6,5)
Decimal literals → (0.55, 0.75)
4. Operators
Operator is a symbol which is used to perform some operations on the
operands.
Ex: 5 + 3 → operands
Operator
Page 2
JAVA
5. Separators
Separators is used to separate the given code.
In java we have,
{ } → braces, [ ] → brackets, ( ) → parenthesis, ; → semicolon , ( , ) → comma
6. Comments
Comments are used to provide the additional information for the java
program.
In comments we have,
1. Single line comments
//……………..//
2. block line comments
/*………….*/
Page 3
JAVA
Java architecture
➢ We will write the program in edit plus / notepad. It is also called as source
code which is in human readable format.
➢ To convert this human readable format into machine readable format, we
have to go to command prompt and perform 2 operations
1. Javac ( java compiler)
2. Java ( java interpreter)
➢ Once after writing the program we have to save the file with the extension of
.java in below path
c:/pgmfiles/java/ Jdk 1.8 / bin
➢ Once after saving we have to give this .java file as an input to the compiler
where it will check for 1). Syntax 2). Rules 3). Translate from .java
to .class file
➢ If there is any syntax or rules violation we get compile time error.
➢ If there is no violation then the .class file will be generated.
➢ .class is an intermediate code which is in byte code format which cannot
understood neither by human nor by machine.
➢ .class file will be given as input for the interpreter which 1). Reads line by
line 2). Execute ( JVM ) 3). Translate .class file to binary language.
➢ If we find any abnormal statements like 1/0 which is infinite , which is not
defined in java hence we get run time error called Arithmetic exception.
Page 4
JAVA
Page 5
JAVA
1. Class
Class is a blueprint or template to create an object.
Ex: : program to print Hello java keyword
identifier class Sample // class
Declaration {
Public static void main ( String [ ] args ) // method Declaration
{
System.out.println (“Hello java”);
}
}
Page 6
JAVA
Page 7
JAVA
VARIABLES
Variable is a named memory location which is used to store some values or
data and it can change N no of times during execution. Variables are of two types
Variable declaration
Syntax: datatype variable _ name;
Ex: int a;
Variable initialization
Syntax: variable _ name = values;
Ex: a = 10;
Variable utilization
System.out.println(a);
o/p : a=10;
Page 8
JAVA
Page 9
JAVA
System.out.println (x);
Page 10
JAVA
} }
2. Global variables
➢ Any variables which is declared outside method and inside the class is
called as Global variables.
➢ The scope of the Global variables is from the beginning of the class till the
end of the class.
➢ It can be classified into static and non – static.
➢ It will have default values.
➢ Once the global variables is declared immediately in the next line we cannot
initialized or re – initialized , if so we will get compile time error .
Ex: class Sample {
Static int a=20;
Public static void main ( String [ ] args ) {
System.out.println (a);
} }
Primitive data Default values Size ( in Range
types bits)
byte 0 8 -128 to 127
short 0 16 -32,768 to 32,767
Int 0 32 -2^31 to 2^31-1
long 0 64 -2^63 to 2^63-1
Double 0.0d 64 1.4e-0.45 to 3.4e +
0.38
float 0.0f 32 4.9e -324 to 1.8e +
308
Char ‘\v0000’(unique) 16 0 to 65,535
Boolean False 1 True or false
String Null - -
Page 11
JAVA
METHODS
Method is a block of statements which will get executed whenever it is
called or invoked.
Syntax:
Access specifier modifier return type method name (arguments)
Public Static void identifier [ optional ]
Private Non – static int
Protected double
Package / default char , String
Float, Boolean, class type
Page 12
JAVA
Final variable :
Any variable which is declared with a keyword final is called as final variable.
System.out.println(1/2); → 0 ( if both are integer)
System.out.println(1/2.0); → 0.5 ( if one of them is decimal)
Ex: class Circle { static void area() {
final double pi=3.142; int r=4;
double result=pi*r*r;
System.out.println(result);
}
public static void main(String[] args) {
area();
} }
Page 13
JAVA
Conditional statements
To check for logical conditions, we should go for conditional statements.
1. If – conditions
Syntax : if ( condition )
{
---------
---------
} Ex:
class Demo {
public static void main(String[] args) {
If (5>3)
Page 14
JAVA
{
System.out.println(“hi”);
}}
2. If – else conditions
Syntax : if ( condition )
{
---------
} else {
-----
}
Ex: class Demo {
public static void main(String[] args) {
If (5>30)
{
System.out.println(“hi”);
} else {
System.out.println(“hello”);
}}}
3. Else - if conditions
Syntax : if ( condition )
{
---------
} else if ( condition ){
Page 15
JAVA
-----
} else {
------
}
Ex: class Demo {
public static void main(String[] args) {
If (5>30)
{
System.out.println(“hi”);
} else if ( 5>2) {
System.out.println(“hello”);
} else {
System.out.println(“cool”);
}}}
Page 16
JAVA
Loops
Whenever the starting and ending range is given then we want to go for FOR
loop.
Syntax: For ( initialization ; condition ; increment (++) / decrement (--))
{
}
Ex 1: For ( int i=1 ; i<=4 ; i++)
{
System.out.println(“cool”) ; → cool , cool , cool , cool
}
Ex 2: For ( int i=1 ; i<=10 ; i++)
{
System.out.println(i) ; → 1,2,3,4,5,6,7,8,9,
10 }
Ex 3: For ( int i=10 ; i<=1 ; i--)
{
System.out.println(i) ; → 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 ,
1 }
Ex 4: without using semicolon :
For ( int i=1 ; i<=n ; System.out.println(i) ))
i++;
Switch case :
Page 17
JAVA
Switch case is used for pattern matching. The particular case will be executed
based on the input.
Syntax:
Switch ( character)
{
Case charseq : statement ;
Break;
Case charseq : statement ;
Break;
Default : statement ;
Break;
}
Ex: class Demo {
public static void main(String[] args) {
Int input=3;
Switch ( input )
{
Case 1 : System.out.println(“FCD”);
Break;
Case 2 : System.out.println(“FC”);
Break;
Default : System.out.println(“Invalid input”) ;
Break;
}}}
Page 18
JAVA
Page 19
JAVA
STATIC
➢ Any member of the class declared with a keyword static is called as static
member of the class.
➢ Static is always associated with class.
➢ Static is one copy.
➢ All the static members will be stored in static pool area.
➢ Whenever we want to access static members from one class to another class
then we should use
Class _ name . variable _ name ( ); or Class _ name . method _
name ( );
Note : We can develop multiple classes in a single file.
➢ Whichever class is having main method that class file should be filename.
➢ For each and every class present in the file will have corresponding . class
file .
Page 20
JAVA
Ex: B / W the classes with a method as static with return type class
Circle {
static double area( ) {
int r=5;
final double pi=3.142;
double result=pi*r*r;
return result;
}}
class Tester {
public static void main(String[] args) {
double x= Circle. area();
System.out.println("area is "+x);
Page 21
JAVA
}}
NON – STATIC
➢ Any member of the class declared without a keyword static is called as
Non - static member of the class.
➢ Non - Static is always associated with object.
➢ Non - Static is multiple copy.
➢ All the Non - static members will be stored in Heap memory.
➢ Whenever we want to access from Non – static to static then we should use
Object . variable _ name or object . method _ name
Reference variable . variable _ name or
Reference variable . method _ name Syntax:
New class _ name ( ) ;
Ex: New Sample ( ) ; → object
Operator constructor
JVM MEMORY
➢ Whenever class loader loads the class all the static members will get
initialized in the static pool area.
➢ JVM starts executing from main method in the program the first statement is
the object creation , equal operator will work from right to left.
➢ New operator will create a random memory space in the heap memory.
Constructor will initialize all the non - static members into the heap memory
while creating the object itself we pass the arguments which will get
initialized the constructor and from constructor it will get initialized to the
object variable.
➢ Now in the main method the object address will be stored in the references
variable e1 and through that references variables we point the values.
Page 22
JAVA
Stack Heap
memory
Page 23
JAVA
Page 24
JAVA
REFERENCE VARIABLE
Reference variable is a special type of variable which is used to store object
address.
Reference variable can hold either null or object address.
Page 25
JAVA
Void disp ( ) {
System.out.println("Hii");
}
public static void main(String[ ] args) {
Tester t1 = new Tester ( );
t1.disp ( ) ;
} }
Note : multiple objects can be stored in multiple references variable and if any
changes made to an objects it will not affect other objects.
Ref1 address object
Ref2 address object
Class Demo
{ Int a=10;
public static void main(String[] args) {
Page 26
JAVA
Note : Whenever we print the reference variable it print address i.e. fully qualified
path.
Fully qualified path means package name.class_name @ hexadecimal no
Ex : non - static . Demo @ 1bcfc76
Ref1 address object
Ref2
Class Demo {
Int a=10;
public static void main(String[] args) {
Demo1 d1 = new Demo1( );
Demo1 d2 = d1;
System.out.println(d1);
System.out.println(d2);
}}
Output → Demo1 @ 15db9742 ,, Demo2 @ 15db9742
Page 27
JAVA
COMPOSITION / AGGREGATIONS
A class having an object of another class is called as composition.
It is also called as has a relationship.
Class diagram :
It is a pictorial representation to represent the member of the class.
Class Tester {
Void add ( ) {
System.out.println(“hii”);
}}
Class Sample {
Public static void main ( String[] args)
{ Tester t1= new Tester ( ); t1. Add ( ) ;
Page 28
JAVA
}}
Tester Sample
Has a relationship
Void : add ( ) Tester : t1
BLOCKS
There are two blocks
Page 29
JAVA
Output : 10
Page 30
JAVA
System.out.println(a) ;
}
Public static void main ( String [ ] args)
{ Int x=10; add ( x); } }
Page 31
JAVA
}}
Class FedEx {
Public static void main ( String [ ] args){
Amazon a1 = new Amazon ( );
Cust1.needproduct (a1);
}}
CONSTRUCTOR
It is a special type of method or special type (member) of the class which is used
to initialize data members.
Rules :
1. The constructor name should be same as class name.
2. Constructor will not have return type.
3. Constructor will not have return any value.
4. Constructor is always non static.
5. Whenever an object is created , constructor will get invoked.
Syntax :
Class class_name {
Class_name ( ) {
----
Return;
}}
Page 32
JAVA
---- → constructor }
}
Constructor
Page 33
JAVA
Page 35
JAVA
System.out.println (this.
a); } }
Ex: write a program to initialize Student id , student name , student fees using
this keyword
Class Student
{
Int std _ id ;
String std _ name ;
Page 36
JAVA
Page 37
JAVA
Array declaration
Syntax: Datatype [ ] array _ name ; Ex:
int [ ] arr ;
Array Initialization
System.out.println(arr [0]);
System.out.println(arr [1]);
System.out.println(arr [2]);
System.out.println(arr [3]);
System.out.println(arr [4]); → Array Index Out of Bound Exception
Note : If the value is not stored in a particular index and if we try to print , we will
get default values.
Page 38
JAVA
Page 39
JAVA
{10,20,30,40};
System.out.println("index\t values");
for ( int i=0; i<= arr . length ; i++ )
{
System.out.println(i+"\t"+ arr[i]);
}}}
Class Sample {
Public static void main ( String [ ] args )
{ Char [ ] arr = new char [ 3 ] ; arr [ 0 ]
=‘A‘;
arr [ 1 ] = ‘ B ‘ ;
arr [ 2 ] = ‘ C ‘ ;
System.out.println(“ index \t values “ );
For ( int i=0; i<= arr . length ; i++ )
{
System.out.println(“ i+ “ \t” + arr [ i ] “ ); // \t → tab space and \n → new
line } } }
Class Sample {
Public static void main ( String [ ] args ) {
Boolean [ ] arr = { true , false , true , false ) ;
For ( int i=0; i<= arr . length ; i++ )
{
Page 40
JAVA
METHOD OVERLOADING
Developing multiple methods with the same name but variation in argument
list is called as method overloading.
Variation in argument list means :
➢ Variation in the data type.
➢ Variation in the length of the arguments.
➢ Variation in the order of occurrence of the arguments.
Rules :
➢ The method name should be same.
➢ There should be variations in the argument list.
➢ There is no restriction on access specifier, modifier and return type.
Note :
➢ We can overload both static and non - static method. ➢ We can overload
main method.
Ex: class WhatsApp { Void
send ( int no ) {
System.out.println ( “ sending no” +no );
}
Void send ( String msg ) {
System.out.println ( “ sending msg” +msg );
}
Void send ( int no , String msg ) {
System.out.println ( “ sending no and msg ”+no+ “ “ +msg );
Page 41
JAVA
}
Void send (String msg , int no ) {
System.out.println ( “ sending msg and no ”+msg+ “ “ +no );
}}
Class Mainclass {
Public static void main ( String [ ] args ) {
WhatsApp W1 = new WhatsApp ( ) ;
W1.send (123);
W1.send (“hello”);
W1.send (126 ,”hi”);
W1.send (“bye”,127);
}
}
Ex : class Book my show {
Static Void book ( int no_ seat ) {
System.out.println ( “book by no of seats”) ;
}
Static Void book( String movie _ name ) {
System.out.println ( “ movie name” );
}
Void book ( int no _seat , String movie _ name ) {
System.out.println ( “book by no of seats and movie name ”);
}
Void book (String movie , int no _seat ) {
Page 42
JAVA
Page 43
JAVA
INHERITANCE
Inheriting the property from one class to another class is called as
Inheritance.
In Inheritance , we have 5 types :
1. single level Inheritance
2. multi - level Inheritance
3. hierarchical Inheritance
4. multiple Inheritance
5. hybrid Inheritance
Page 44
JAVA
Tester ©
Int : x
Sample ©
Void add ( )
Demo ©
Void : disp ( )
3. HIERARCHICAL INHERITANCE
A multiple sub class inheriting the properties from only one super class or
common super classis called as hierarchical Inheritance.
Tester ©
Int : x
Sample © Demo ©
4. MULTIPLE INHERITANCE
Page 45
JAVA
A sub class inheriting the properties from multiple super class is called as
Multiple Inheritance .
Sample © Demo ©
Tester ©
Int : x
5. HYBRID INHERITANCE
It is combination of single level , multi – level and hierarchical inheritance.
When to go for inheritance ?
➢ We go for inheritance for code reusability .
Page 46
JAVA
Tester 4 ©
Int : x
Demo 4 ©
Sample 6 ©
Void : add ( )
Int : x
Sample 4 ©
Void : disp ( )
Page 47
JAVA
Ex : hierarchical inheritance
Class Tester {
Int y=10;
}
Page 48
JAVA
METHOD OVERRIDING
Developing a method in the sub class with the same name and signature as
in the superclass but with different implementation in the sub class is called as
method overriding.
Rules :
1. The method name and signature should be same in the sub class as in the super
class.
2. There should be IS A RELATIONSHIP ( inheritance ).
3. The method be non – static.
Page 49
JAVA
Page 50
JAVA
}}
Ex:
Class KitKat {
Void camera ( ) {
System.out.println ( “Back camera” ) ;
}}
Class lollipop extends KitKat {
Void camera ( ) {
System.out.println ( “front and back camera” ) ;
}}
Class Mainclass {
Public static void main ( String [ ] args )
{ lollipop l1 = new lollipop ( ) ; l1 .
camera ( ) ;
Page 51
JAVA
}}
SUPER KEYWORD
Super keyword is used in the case of method overriding , along with the sub
class implementation , if we need super class implementation thus we should go
for super . method name Note :
➢ We go for inheritance for code reusability .
➢ We go for method overriding whenever we want to provide new
implementation for the old feature .
➢ We go for method overloading whenever we want to perform common task
and operation .
Ex :
Class phonepe _ v1 {
Void rewards ( ) {
System.out.println (“ rewards by money”);
}}
Class phonepe _ v2 extends phonepe _ v1 { Void
rewards ( ) {
System.out.println (“ rewards by coupon”);
Super . rewards ( ) ;
}}
Class Mainclass { public static void main (
String [ ] args ) { Phonepe _ v2 p2 = new
phonepe _ v2 ( );
P2 . rewards ( );
Page 52
JAVA
}}
What is System.out.println ?
➢ System is a class.
➢ Out is a global static reference variables.
➢ Println is a non – static method of print stream.
Class Demo // print stream
{
Void add ( ) { // println
---
}}
Class Tester {
Static Demo d1 = new Demo ( );
Static Print stream = new print stream ( );
}
Class Mainclass {
Public static void main ( String [] args ) {
Tester.d1.add();
System.out.println
( ); } }
TYPE CASTING
Converting from one type to another type is called Type casting.
1. Primitive type casting
• Narrowing → explicitly
• Widening → → Implicitly , explicitly
Page 53
JAVA
Narrowing → explicitly
Converting from bigger primitive data type to any of its smaller primitive
data type is called Narrowing Type casting.
Explicitly
1. int x = (int) 59.9d; 2. Short y = (short) 36.61;
s.o.p(x); → o/p – 59 s.o.p(y); → o/p – 36 3.
byte z = (byte) 99.9f; 4. Long t = (long) 60.36;
s.o.p(z); → o/p – 99 s.o.p(y); → o/p – 60
Page 54
JAVA
Note :
Sample s1 = new Sample ( ) ; // homogenous type of object creation.
Sample s1 = new Demo ( ) ; // heterogenous type of object creation.
In the case of method overriding even though it is upcasted we will get
overridden implementation.
DEMO ©
Int a Super class object
Super class
type
( up casting) ( Down casting)
Sample ©
Page 55
JAVA
Int a=10;
}
Class Sample extends Demo { Void
disp ( ) {
System.out.println(“hey its disp..”);
}}
Class Mainclass {
Public static void main (String [ ] args) {
Demo D1 = new Sample ( ) ;
System.out.println(D1.a));
Sample S1 = ( Sample ) D1 ;
System.out.println(S1.a));
S1.disp
();}}
POLYMORPHISM
An object showing different behaviour at different stages of its lifecycle is
called polymorphism.
Poly means “ many “ , morphism means “ forms “
In polymorphism , we have 2 types
1. compile time polymorphism
2. run time polymorphism
Page 56
JAVA
The method declaration getting binded to its definition at the compile time
by the compiler based on the arguments passed is called “ compile time
polymorphism / static binding”.
Since the method declaration getting binded to its definition at the time
itself is called as “ early binding “.
Once the method declaration gets binded to its definition it cannot be
rebinded , hence it is called “ static binding” .
➢ Method overloading is an example for “ compile time polymorphism”.
➢ At the compile time it’s going to check for method declaration and its
definition.
Ex: class WhatsApp { Void
send ( int no ) {
System.out.println ( “ sending no” +no );
}
Void send ( String msg ) {
System.out.println ( “ sending msg” +msg );
}
Void send ( int no , String msg ) {
System.out.println ( “ sending no and msg ”+no+ “ “ +msg );
}
Void send (String msg , int no ) {
System.out.println ( “ sending msg and no ”+msg+ “ “ +no );
}}
Class Mainclass {
Public static void main ( String [ ] args ) {
WhatsApp w1 = new WhatsApp ( ) ;
Page 57
JAVA
W1.send (123);
W1.send (“hello”);
W1.send (126 ,”hi”);
W1.send (“bye”,127);
}}
Page 58
JAVA
Animal ©
void : noise ( )
Dog d1
Ex:
Package poly;
Page 59
JAVA
Class Animal {
Void noise ( ) {
System.out.println(“some noise”);
}}
Class Cat extends Animal { Void
noise ( ) {
System.out.println(“meow meow…”);
}}
Class Dog extends Animal { Void
noise ( ) {
System.out.println(“bow bow…”);
}}
Class Snake extends Animal { Void
noise ( ) {
System.out.println(“buss tuss”);
}}
Class Stimulator { Static void
anisum (Animal a1) { a1.noise (
);
}}
Class Mainclass { public static void
main (String []args) {
Cat c1 = new Cat();
Dog d1 =new Dog();
Page 60
JAVA
ABSTRACT CLASS
1. CONCRETE METHOD
Any method which has both declaration and definition is called as “ concrete
method “. Ex:
Void disp ( ) {
----- }
2. CONCRETE ClASS
Any class which has only method is called as “ concrete class “. Ex:
Class Sample {
Void disp ( ) {
----
}
Page 61
JAVA
3. ABSTRACT METHOD
Any method which is declared with a keyword abstract is called as “
Abstract method “. Ex:
Abstract void disp ( ) ;
➢ The class which provides the implementation for the abstract methods, the
subclass is also called as implementation class.
➢ An abstract method cannot be declared as static , final , private.
➢ If any one of the abstract method is not overridden in the subclass, then the
sub class should be declared as abstract.
Ex 1: Abstract class Tester {
Abstract void disp ( );
Abstract void cool ( );
}
Class Demo extends Tester { Void
disp ( ) {
System.out.println(“hi”);
}
Void cool ( ){
System.out.println(“hello”);
}}
Class Mainclass {
Public static void main ( String [ ]args )
{ Demo d2 = new Demo ( );
d2.disp ( ); d2.cool ( ); } }
Page 63
JAVA
Void test ( ) {
System.out.println(“hi”);
}
// Abstract void cool ( );
}
Class Sample extends Tester { Void
cool ( ) {
System.out.println(“hello”);
}
Public static void main ( String [ ]args )
{ Sample s2 = new Sample ( );
s2.test ( );
s2.cool ( );
}}
INTERFACE
➢ An Interface is java type which is a pure abstract body.
➢ In Interface, we have 2 members i.e.
1.variables
2.method
➢ All the variables are by default static and final.
➢ All the methods are by default public and abstract.
➢ Interface does not support constructor.
➢ Java provides the keyword called implements to inherit the properties from
interface to class.
➢ Interface is by default abstract.
➢ We cannot create object class and interface.
Page 64
JAVA
➢ Each and every class extends object class , object class is the super most
class in the class type.
➢ Interface does not extends any class , interface itself is a super most type.
➢ From an interface to interface , to inherit the properties we use the keyword
extends.
➢ The class which provides the implementation for the abstract method , the
subclass is also called as implementation class.
➢ If any one of the abstract method is not overridden in the subclass then the
subclass should be declared as subclass.
➢ Through Interface, we can achieve multiple inheritance and abstraction.
➢ Through abstract class, we can achieve up to 100% abstraction. ➢ Through
interface we can achieve 100 % abstraction.
Syntax:
Interface interface _ name {
Variable / Data members ;
Method / Function members ; }
Ex:
( abstract ) interface Sample
{ Int a=10; // static final
Void disp ( ); // abstract public
}
Page 65
JAVA
System.out.println(“hi”);
}
Public void test ( ) {
System.out.println(“hello”);
}}
Class Mainclass {
Public static void main ( String [ ] args) {
Sample s1 = new Sample ( );
S1.disp();
S1.test();
}}
Page 66
JAVA
}
Public static void main ( String [ ]args )
{ Sample s2 = new Sample ( );
s2.test ( );
s2.cool ( );
} }
a1.wheel
( ); } }
Page 67
JAVA
ABSTRACTION
Hiding the complexity of the system and exposing only the required
functionality to the end user is called as abstraction.
➢ To achieve abstraction , declare all the essential properties in the interface
and provide the implementation in the sub class.
Page 68
JAVA
Animal (I)
void : noise ( )
Dog d1
Ex:
Interface Animal {
Void noise ( )
}
Page 69
JAVA
Page 70
JAVA
{
Cat c1 = new Cat();
Dog d1 =new Dog();
Snake s1 = new Snake();
Stimulator. anisum (c);
Stimulator. anisum (d1);
Stimulator. anisum (s1);
}
}
PACKAGE
It is a folder structure which is used to store similar kind of files. The
packages should be created always in the reverse order.
Ex : www.gmail.com // commercial
Com → gmail → www
In any java file the 1st statement should be package statement , To import the
files from 1 package to another package , java produces a keyword called “ import
“ where the files will be present virtually.
Import statement should be 2 nd statement .we can have n no of import
statement file in a single java file. It can be any java type, i.e. : class, enum,
annotation, interface .
Package movies; →1
Import movies.kan movies action movies .kgf; → 2
Import movies.kan movies action movies .avn;
Class Films
{ → 3
}
Page 71
JAVA
In eclipse when we develop multiple classes which ever class is public that
class that class is eligible to have main method and it should be file
name. Class C
{
-----
}
Public class A
{
Public static void main ( String [ ] args ) A.java
{
-----
}
}
Class B
}}
ACCESS SPECIFIER
Access specifier is used to restrict the access from one class to another class
( or ) from one package to another package.
In java , we have 4 access specifier
1. private
2. default / package level
3. protected
4. public
Page 72
JAVA
1. Private
Any member of the class declared with a keyword private is called as private
access specifier.
It can be accessed only within the class .
3. Protected
Any members of the class declared with the keyword protected is called as “
protected member of the class “.
It can be accessed
1. within the class
2. within the package
3. outside the package with IS A RELATIONSHIP
4. Public
Any members of the class declared with a keyword public is called as “
public access specifier”.
It can be accessed
Page 73
JAVA
public
protected
increase in default / increase in security
visibility private package
Page 74
JAVA
{
System.out.println("bike");
}
public void cycle()
{
System.out.println("cycle");
}
}
package com.family.myfamily;
ENCAPSULATION
Page 75
JAVA
Ex 1 : Class Sample {
Private int a =10;
Public int get A ( )
{
return a ;
}
public void set A ( int a )
{ this. a
=a ;
}
}
Class Mainclass {
Page 76
JAVA
Ex 2 : Class ICICI {
Private int set pin=1234;
Public int atm pin ( )
{
return ;
}
Public void set A ( int atm pin )
{
this. atm pin = atm pin ;
}
}
Class Mainclass {
Public static void main ( String [ ] args) {
ICICI card = new ICICI ( ); System.out.println( card . get atm pin ( ) ) ;
Card . set atm pin (1267);
System.out.println( card . get atm pin ( ) ) ;
Page 77
JAVA
}
}
Ex 3 : class Facebook {
Private int pwd =1234;
Public int get pwd ( )
{
return pwd ;
}
Public void set pwd ( int pwd )
{
this . pwd = pwd ;
}
}
Public Class Mainclass {
Public static void main ( String [ ] args) {
Facebook f1 = new Facebook ( );
System.out.println( f1. get pwd ( ) ) ;
F1 . set pwd (1267);
System.out.println( f1 . get pwd (1 ) ) ;
}
}
OBJECT CLASS
Object class is the super most class in java .
Each and every class extends object class.
Page 78
JAVA
Object class belongs to java. Lang package , which will be imported by default.
In object class we have following methods as follows :
Int hashcode ( )
Boolean equals ( )
Object done ( )
String tostring ( )
Void notify ( )
Void notifyall ( )
Void wait ( )
Void finalize ( )
JAVA LIBRARY
Java library is nothing but inbuilt classes and interfaces , we have following
libraries like
JAVA
Tostring
Tostring method is a non – static , non - final method of object class .
➢ It will be inherited to each and every class.
➢ Whenever we print the reference variable , tostring method will be invoked
implicitly , which will return fully qualified path in the form of string.
➢ Fully qualified path means package name .class name @ hexadecimal
number.
Ex : package poly ;
Page 79
JAVA
Hashcode
Hashcode method is a non - static , non - final method of object class.
➢ Hashcode method will be inherited to each and every class.
➢ Whenever we invoke the hashcode method , it will return the unique integer
no called hash no based on the object address .
➢ The hash code will be generated using hashing algorithm the signature of
hash code method is “ public int hash code “.
➢ Hash code method should be invoked explicitly.
Ex : Public class Demo extends object {
Public static void main ( String [ ] args ) {
Demo d1 = new Demo ( ) ;
System.out.println( d1 . hashcode ( ) ) ;
Demo d2 = new Demo ( ) ;
System.out.println( d2 . hashcode ( ) ) ;
}
} o / p → 12367134
56732193
package poly ;
Public class Tester extends object {
Public int hashcode ( )
Page 80
JAVA
{
return 123 ;
}
Public static void main ( String [ ] args ) {
Tester t1 = new Tester ( ) ;
System.out.println( t1 . hashcode ( ) ) ;
} }
Equal Method
Equal method is a non – static , non – final method of object class.
➢ Equal method will be inherited to each and every class. ➢
Equal method is used to compare object address . ➢ The
signature of equal method is ‘public Boolean equals”. ➢ To
compare the address, we use equal method.
Ex : Public class Demo extends object {
Public static void main ( String [ ] args ) {
Demo d1 = new Demo ( ) ;
Demo d2 = new Demo ( ) ;
System.out.println( d1 .equals
( d2 ) ) ; } }
STRING CLASS
String is a final class which belongs to java. Lang package .
➢ It should be imported to each and every package.
➢ It is immutable. [ means it will not change the state of object ] .
String s1 = “hi”;
String s2 = “hello”;
Page 81
JAVA
Why it is immutable ?
When multiple reference variable are pointing to a single object and if one
of the reference variable de reference with the current object it will not affect other
reference variable. This is why it is immutable.
String s1 = “ cool” ; String s1 = “ cool” ;
String s1 = “ cool” ; String s1 = “ hot ” ;
Page 82
JAVA
String s4 = (“hi”);
System.out.println (s3==s4)
}
}
Difference between comparison operator and equal operator
Comparison Operator Equal Operator
1. it is an operator . 1. It is a non – static method of object.
2. operator cannot be overridden. 2. Object can be overridden.
3. it compares address. 3. Compare object values in string class.
EXCEPTION HANDLING
[ for smoother execution ]
It is an event triggered during the execution of the program which interrupt
the execution and stops the execution abruptly / suddenly handling this event by
using try and catch or throws is called as “Exception handling”.
➢ It is an abnormal statement which stops the program in order to this we have
to go for try , catch or throws.
➢ All the abnormal statement should be developed in try block and address
them in the catch block
➢ We cannot develop any statement between try and catch block.
➢ Once the exception occurs in the try block, further statement of the try block
will not be executed.
➢ For one try block there should be one mandatory catch block.
➢ For one try block we can have more than one catch block but only 1 catch
block will get executed.
➢ Exception class is the super class which can address both checked and
unchecked exception.
➢ All exception classes belongs to java. Lang package.
➢ Once the exception is addressed, we cannot readdress if we try to do that
then we get compile time error.
Page 83
JAVA
➢ Exception class can address all the sub class exception which is either
compile time or run time.
➢ We can develop try , catch , finally or try finally. An Exception can be
address in 2 ways
1. try and catch 2.
using throws
Exception are of 2 types
1. compile time exception or checked exception
2. run time exception or unchecked exception
Page 84
JAVA
}}
Public static void main ( String [ ] args ) {
Try {
Submit ( );
}
Catch ( matrimonyexception e ) {
System.out.println( e.getmessage( ));
}}
Class matrimonyexception extends exception {
String msg ;
Matrimonyexception ( String msg ){
This .msg =msg ;
}
Public String getmessage ( ) {
Return msg ;
}}
Class flipflipexception extends Exception {
String msg ;
Flipflipexception (String msg ) {
This.msg =msg;
}
Public string getmessage ( ) {
Return msg ;
}}
Public class flipkart {
Page 85
JAVA
Syntax :
Page 86
JAVA
1. try { 2. try {
----
---- }
} Catch ( )
Catch ( exception ref variable ) {
{ ----
---- }
}
3. try 4. try {
{ try {
---- ----
} }
} Finally {
Catch ( ) ----
{ }
----
}
Catch ( )
{
----
}
5. try {
----
}
Catch ( )
{
----
}
Finally {
----
}
Throw :
It is used to throw the exception of throwable type.
It will be written internally.
Once exception is addressed if we try to readdress then “COMPILE TIME ERROR
“.
Page 87
JAVA
Throwable
Java . Lang Throwable
Error Exception
Arithmetic exception
Null pointer exception
Index out of bounds exception
Illegal arguments exception
Etc.
Try {
Int I = 1 \ 10 ; \\ throw new arithmetic exception ( “ / zero )
}
Catch ( Arithmetic exception e ) {
System.out.println(“ handled “);
}
} o / p → handled
Note : between try and catch nothing should be written if not compile time error .
➢ Compile time error occurs when we write something between try and catch
block.
Page 90
JAVA
➢ There may be multiple catch for 1 try block but only one catch block will be
executed .
➢ A reference variable can hold either null or object address
Page 91
JAVA
}
Catch ( exception e )
{
System.out.println(“ handled “);
}
Catch ( Arithematic exception e )
{
System.out.println(“ Addressed “);
}
} o / p → compile time error because of 2 exceptional cases
Page 92
JAVA
{
System.out.println(“ Caught “);
}
} o / p → Addressed
Finally Block
Finally block is block in exceptional handling which will get executed mandatory,
even though the exception is addressed or not addressed.
We can develop finally block in 2 ways
1. try catch finally
2. try finally
➢ In amazon 1 rupee sale , too many customer access the server and the
server might not get crashed even through the application crashes , the
database closing application connection statement should get executed ,
hence we have to develop finally block.
Stack Unwinding
If any exception occurs in any 1 f the method and if it is not addressed which
will propagate the exception to the called method which in turn reaches main
method and if main method propagated to JVM. Hence JVM does not have any
handler (throw / try and catch) the stack will get destroyed . hence it is called as
Stack unwinding.
Class Demo {
Static void disp4 ( ) {
Int i =1\10;
}
Static void disp3 ( )
{ disp4 ( );
}
Static void disp2( ) {
Disp3 ( );
}
Static void disp1( ) {
Page 94
JAVA
Disp2 ( );
}
Public static void main ( String [ ] args )
{ Try { disp1 ( );
}
Catch (Arithmetic exception e ) // throw new Arithmetic exception ( )
{
e.printstacktrace ( ); // = new Arithmetic exception ( )
}
}
}
Error
Error is a class which belongs to java. Lang package error is occurred due to
the system configuration.
EXCEPTION
1. Exception is predictable.
2. Exception is occurred due to mistake done by the programmer.
3. exception can be handled.
Page 95
JAVA
THROWS
1. Throws is used to propagate the exception from 1 method to the called method.
2. Throws should be developed in method declaration.
3. Throws is used to propagate the exception.
4. Throws can propagate more than 1 exception
COLLECTIONS
Collections is an unified architecture which consist of interface and class.
➢ All the collections ,class and interface belongs to java.util.package.
➢ In order to overcome the drawback of array we will go for collections. i.e.
1. In collection , the size is dynamic which it grows its size by 50% .
2. The default capacity will be 10.
Capacity = current capacity * 3/2 + 1
= 10 * 3/2 + 1
= 16
3. It can store heterogenous type of data
Page 96
JAVA
Collection
Stack © Linked
hash set ©
Page 97
JAVA
1. List
List is an interface which belongs to java.util.package When you
will go for list type of collection ?
Whenever we want to store upon index and allow duplicates then we will go for
list type of collection.
Features of list
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is indexed type of collection.
➢ It allows duplicates.
➢ It allows null.
➢ It will follow order of insertion.
➢ Since it is indexed type of collection we can do random access.
List interface have 4 sub classes i.e.
1. Array list
2. Vector list
3. Linked list
4. Stack
1. Array list
Array list is a class which implements list interface.
Features of Array list
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is indexed type of collection.
➢ It allows duplicates.
➢ It allows null.
➢ It will follow order of insertion.
Page 98
JAVA
Page 99
JAVA
Package collectiontopic ;
Import java.util. Arraylist;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ;
Ex : Package collectiontopic ;
Import java.util. *;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ; l1. Add ( 20 ) ; l1. Add ( 30 ) ;
Arraylist l2 = new Arraylist ( ); l2. Add
( ‘A’ ) ; l2. Add ( ‘B’) ; l2. Add ( ‘C’ ) ;
System.out.println ( “---- A----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2); l1
. addAll ( l2 );
Page 100
JAVA
Ex : Package collectiontopic ;
Import java.util. *;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ; l1. Add ( 20 ) ; l1. Add ( 30 ) ;
Arraylist l2 = new Arraylist
( ); l2. Add ( ‘A’ ) ; l2. Add
( ‘B’) ; l2. Add ( ‘C’ ) ;
System.out.println ( “---- A----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2); l1
. addAll ( 1 , l2 );
System.out.println ( “---- B----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2);
Page 101
JAVA
}} o / p → -------A-------
Page 102
JAVA
L1 → [ 10 , 20 , 30 ] l2 → [ A , B , C ]
---------B-------
L1 → [ 10 , A , B , C , 20 , 30 ] l2 → [ A , B , C ]
Remove ( ) :
It will help to remove the elements from the collections object ( it is used for
string object)
Ex : Package collectiontopic ;
Import java.util. Arraylist;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
“ Bangalore “ ) ; l1. Add ( “
Nelamangala “ ) ; l1. Add ( “
Rajajinagar “ ) ; System.out.println ( “ l1
→ “ +l1); l1 . remove ( “ Rajajinagar “ );
System.out.println ( “ l2 → “ +l2); l1
. remove ( 0 );
System.out.println ( “ l3 → “ +l3);
}
} o / p → L1 → [ Bangalore , Nelamangala , Rajajinagar ] l2
→ [ Bangalore , Nelamangala ] l3 → [ Nelamangala ]
RetainAll ( )
It will retain all the duplicates in l2 w.r.t l2
Page 103
JAVA
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ; l1. Add ( 20 ) ; l1. Add ( 30 ) ; l1.
Add ( 40 ) ;
Arraylist l2 = new Arraylist
( ); l2. Add ( 30 ) ; l2. Add
( 40 ) ; l2. Add ( 50 ) ; l1. Add (
60 ) ;
System.out.println ( “---- A----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2); l1
. retainAll ( l2 );
System.out.println ( “---- B----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2);
}
} o / p → -------A-------
L1 → [ 10 , 20 , 30 , 40 ] l2 → [ 30 , 40 , 50 , 60 ]
---------B-------
L1 → [ 30 , 40 ] l2 → [ 30 , 40 , 50 , 60 ]
Page 104
JAVA
RemoveAll ( )
It removes all the duplicates in l2 w.r.t l1 .
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ; l1. Add ( 20 ) ; l1. Add ( 30 ) ; l1.
Add ( 40 ) ;
Arraylist l2 = new Arraylist
( ); l2. Add ( 30 ) ; l2. Add
( 40 ) ; l2. Add ( 50 ) ; l1. Add (
60 ) ;
System.out.println ( “---- A----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2); l1
. removeAll ( l2 );
System.out.println ( “---- B----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2);
}} o / p → -------A-------
L1 → [ 10 , 20 , 30 , 40 ] l2 → [ 30 , 40 , 50 , 60 ]
---------B-------
L1 → [ 10 , 20 ] l2 → [ 30 , 40 , 50 , 60 ]
Page 105
JAVA
Page 106
JAVA
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Import java.util . collections;
Public Class Sample {
Public static void main ( String [ ] args )
{ Arraylist l1 = new Arraylist ( ); l1. Add (
10 ) ; l1. Add ( 210 ) ; l1. Add ( 30 ) ; l1.
Add ( 410 ) ;
Arraylist l2 = new Arraylist ( l1 );
Page 107
JAVA
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2);
}}
Arrays :
Arrays is a class which belongs to java.util .package and it has inbuilt
methods like sort , stream methods which helps to find maximum values.
arlist ( ) – it is used to convert array to a list .
class Array { static list arlist
( int [ ] acc ) list l1 = new
Arraylist ( ); l1.add ( acc
[0] ) ; l1.add ( acc [1] ) ;
l1.add ( acc [2] ) ; return
l1; } }
Class Sample {
Public static void main ( String [ ] args ) {
Int [ ] abb = { 10, 20 ,
30 ) ; Array.arlist ( abb );
list l2 = arlist ( ); } }
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Import java.util . Arrays;
Import java.util . collections;
Import java.util . list;
Page 108
JAVA
➢ It is synchronized.
➢ Since it is synchronized, the performance is slow.
Ex : Package collectiontopic ;
Import java.util . Vector;
Public Class Sample {
Public static void main ( String [ ] args )
{ Vector l1 = new Vector ( ); l1. Add ( 10 )
; l1. Add ( 20.56 ) ; l1. Add ( null ) ; l1.
Add ( 10 ) ; System.out.println ( l1 );
System.out.println ( “size → “ +l1.size);
System.out.println ( “ capacity → “ +l1.capacity);
} } o /p → [ 10 , 20.56 , null ,10 ] , size → 4 , capacity → 10
Ex : Package collectiontopic ;
Import java.util . Vector;
Public Class Sample {
Public static void main ( String [ ] args )
{ Vector l1 = new Vector ( ); l1. Add ( 10 )
; l1. Add ( 20.56 ) ; l1. Add ( null ) ; l1.
Add ( 10 ) ; l1. Add ( ‘A’ ) ;
System.out.println ( l1 );
System.out.println ( “size → “ +l1.size);
System.out.println ( “ capacity → “ +l1.capacity);
} } o /p → [ 10 , 20.56 , null , 10 , ‘A’ ] , size → 5 , capacity → 38
Page 110
JAVA
Arraylist Vector
1. it increases its size by 50%. 1. it increases its size by 100%.
2. it is not synchronized. 2. it is synchronized.
3. since it is not synchronized the 3. since it is synchronized the
performance is fast. performance is slow.
3. Linked list
When you will go for linked list type of collection ?
Whenever we want proper order of insertion , then we should go for linked
list.
Linked list is a class which have dual property.
Features of Linked list
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is indexed type of collection.
➢ It allows duplicates.
➢ It allows null.
➢ It will follow order of insertion.
➢ Since it is indexed type of collection we can do random access.
➢ It inherits the properties from both lists and queue.
➢ It can use poll ( ) and peek ( ) method or get ( ) method to fetch the data.
Ex:
Package collection topic;
Import java.util.Linkedlist;
Public class Sample
{
Public static void main(String[ ] args)
{
LinkedList L1 = new LinkedList ( );
Page 111
JAVA
L1.add(10);
L1.add(20.26);
L1.add(‘A’);
L1.add(“hello”);
L1.add(10);
System.out.println(L1);
System.out.println(“after get ( )→ “+L1);
System.out.println(L1. peek ( ));
System.out.println(“after peek ( )→ “+L1);
System.out.println(L1. pool ( ));
System.out.println(“after pool ( )→ “+L1);
}
} o/p → { 10 , 20.26 , A , hello , 10 }
after get ( )→ { 10 , 20.26 , A , hello , 10 }
10 after peek ( )→ { 10 , 20.26 , A , hello ,
10 }
10 after pool ( )→ { 10 , 20.26 , A , hello ,
10 }
4. Stack
Stack is class which belongs to java.util.package Stack
extends vector class.
Features of Stack
➢ Size is dynamic.
➢ We can store heterogenous type of data.
Page 112
JAVA
Page 113
JAVA
2. Queue
Queue is an interface which extends collection interface.
In queue interface we have 2 sub classes
1. Linked list
2. priority queue
1. Priority Queue
Priority queue is a class which implements queue interface which is of pure
queue.
Features of Priority queue
Page 114
JAVA
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is not indexed.
➢ It allows duplicates.
➢ It is auto sorted.
➢ Since it is not indexed type of collection, we cannot fetch the elements upon
index.
➢ In priority queue to fetch the element we should use poll ( ) and peek ( ).
Poll ( ) method
Poll ( ) method is non – static member of the queue class , which helps to
fetch the top most element of the queue and remove the element from the queue
and reduce the size of the queue by 1.
Peek ( ) method
Peek ( ) method is non – static method of the priority queue class , which
helps to fetch the top most element of the queue and it will not reduce the size of
the queue by 1.
Package collection topic;
Import java.util. Priorityqueue;
Public class Sample
{
Public static void main(String[ ] args)
{
Priorityqueue L1 = new Priorityqueue ( );
L1.add(100);
L1.add(20);
L1.add(16);
L1.add(10);
L1.add(80);
Page 115
JAVA
Page 116
JAVA
[ 80 , 100 ]
3. Set
Set is an interface which extends collection interface.
When do we go for set type of collection ?
Whenever we want to store the element not upon index and not allowing
duplicates, then we should go for set type of collection.
Inside interface we have 3 sub classes
1. Hash set
2. Linked hash set
3. Tree set
1. Hash set
Hash set is a class which implements set interface.
Features of Hash set
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is not indexed type of data.
➢ It will not allow duplicates.
➢ It allows null.
➢ Since it is not indexed type of collection, we cannot do random access. ➢ It
will not follow order of insertion.
Package collection topic;
Import java.util. Hashset ;
Public class Sample
{
Public static void main(String[ ] args)
{
Page 117
JAVA
Page 118
JAVA
L1.add(20.56);
L1.add(‘A’);
L1.add(10);
L1.add (“hello”);
System.out.println(L1);
} } o /p → [ 10 , 20.56 , A, hello ]
3. Tree set
Tree set is a class which implements set interface.
Features of Tree Hash set
➢ Size is dynamic.
➢ We can store heterogenous type of data.
➢ It is not indexed type of data.
➢ It will not allow duplicates.
➢ It allows null.
➢ Since it is not indexed type of collection, we cannot do random access. ➢ It
is complexity auto sorted.
Public class Sample
{
Public static void main(String[ ] args)
{
TreeHashset L1 = new TreeHashset ( );
L1.add(100);
L1.add(10);
L1.add(16);
L1.add(10);
System.out.println(L1);
Page 119
JAVA
}} o / p → [ 10 , 16 ,100 ]
MAP
Map is an interface , which belongs to java.util package.
Whenever we want to store upon key and value then we should go for MAP.
Features of Map
➢ Size is dynamic.
➢ It can store heterogenous type of data.
➢ It stores the elements upon keys and values.
➢ It cannot have duplicates keys.
➢ We can have duplicates Values.
Map has 3 sub classes
1. Hash map
2. Linked Hash map
3. Tree map
1. Hash map
Hash map is a class which implements map interface.
Features of Hash Map
➢ Size is dynamic.
➢ It can store heterogenous type of data.
➢ It stores the elements upon keys and values.
➢ It cannot have duplicates keys.
➢ We can have duplicates Values.
➢ It will not follow order of insertion.
Ex:
Package intro;
Import java.util.Hashmap;
Page 120
JAVA
Page 121
JAVA
3. Tree map
Tree map is a class which implements map interface.
Features of Linked Hash Map
➢ Size is dynamic.
➢ It can store heterogenous type of data.
➢ It stores the elements upon keys and values.
➢ It cannot have duplicates keys.
➢ We can have duplicates Values.
➢ It is completely auto sorted based on key. ➢ It sorts based on ASCII values.
Ex:
Package intro;
Import java.util.Treemap;
Public class Sample
{
Public static void main(String[] args)
{
Tree Map <String, Integer> L1= new Tree Map <String, Integer> ( );
L1.put(“virat”,123);
Page 122
JAVA
L1.put(“Rakesh”,321);
System.out.println(L1);
}
} o/p → { virat 123 , Rakesh 321 }
Map (i)
Hash Map ©
Generic class
To achieve generic class, we have to use angular braces < > , by using
generics we can store homogenous objects of a specified class type.
Map is of generic type by default.
Primitive Datatype Wrapper Datatype
byte Byte
short Short int
Integer long Long float float double double char
character boolean Boolean
Page 123
JAVA
THREAD
Thread is an extension instance which owns of its own CPU time and memory.
Deamon thread
The thread which are running at backend is called as Deamon thread.
Marker interface ?
An empty interface is called as marker interface
Ex: interface A
{
---
}
Functional thread ?
Any interface which has only abstract method is called as functional
interface. Ex: interface A
{
Void disp ( );
}
Thread is a class which belongs to java. Lang package has many inbuild
methods like sleep methods.
➢ Thread pause the execution in milliseconds.
SLEEP METHOD
Sleep method is a static method of thread class which belongs to java.lang
package , where it pauses the execution for few milliseconds.
Ex: Package threadtopic;
Public class Sample {
Page 124
JAVA
MULTI THREADING
Processing multiple threads simultaneously is called as multi - threading.
MULTI TASKING
It is a Process of executing multiple task simultaneously is called as multi -
tasking.
SYNCHRONIZED
Processing one by one thread is called as Synchronized .
Processing multiple threads simultaneously is called as “non – Synchronized “.
Page 125
JAVA
Page 126
JAVA
Th2.start ( );
}}
o/p → 1 100 2 102 3 4 ……..
}} o/ p → main
Wait
➢ It is non static method of object class.
➢ It is used only in the case of synchronize. ➢ It will wait still it receive
notifications.
Sleep
➢ It is a static method thread class.
➢ It can be used in any code.
➢ It will pause its execution for few milliseconds.
Notify : It is the non - static method of object class which notifies the thread which
is about access the resource.
Notify all : It is the non - static method of object class which will notify all the
thread which is about access the resource.
FILE HANDLING
File is nothing but collection of similar kind of files or data.
In java file is a class which belongs to java.io package which should be
imported explicitly.
In a file we can have non – static methods like
➢ Mkdir ( ) → make directories.
➢ Create new file ( ) → it helps to create the file.
➢ Exits ( ) → it check whether the file is present or not , if it is present it will
return true else it will return false.
➢ Delete ( ) → which will help to delete the file in the given path.
Ex:
Package filehandlingtopic;
Page 128
JAVA
Import java.io.file;
Class Demo {
Public static void main ( String [ ] args ) {
File f1 = new file ( “d://java batch”);
If (f1.mkdir ( ) )
{
System.out.println ( “folder created “);
}
Else
{
System.out.println ( “folder created “);
}
If (f1.exists ( ) )
{
System.out.println ( “folder exits“);
}
Else
{
System.out.println ( “folder does not exits“);
} if (f1.delete
()){
System.out.println ( “folder is deleted “);
}
Else
Page 129
JAVA
{
System.out.println ( “folder is not deleted “);
}}} o / p → folder created exists file deleted
Page 130
JAVA
Import java.io.file;
Import java.io.Ioexception;
Import java.io.filewriter;
Public Class Sample {
Public static void main ( String [ ] args ) throws IO exception
{
File f1 = new file (“D://rcb.txt” );
File writer fw = new file writer (f1);
Fw. Write(“hello I will get job”);
System.out.println ( “Data is written “);
Fw. Flush ( );
}} o / p → Data is written
Page 131
JAVA
System.out.println (s1);
}} o / p → hello I will get job
Package filehandlingtopic;
Import java.io.Bufferdwriter;
Import java.io.file;
Import java.io.Ioexception;
Import java.io.filewriter;
Public Class Sample {
Public static void main ( String [ ] args ) throws IO exception
{
File f1 = new file (“D://rcb.txt” );
FileWriter fw = new FileWriter (f1,true);
BufferdWriter bw = new BufferdWriter (fw);
Bw.write(“hello”); Bw.line(
);
Bw.write(“hello”);
Bw.line( );
System.out.println (“data is written”);
Bw.flush( );
}}
Package filehandlingtopic;
Import java.io.BufferdReader;
Import java.io.file;
Import java.io.Ioexception;
Page 132
JAVA
Import java.io.filewriter;
Public Class Sample {
Public static void main ( String [ ] args ) throws IO exception
{
File f1 = new file (“D://rcb.txt” );
FileReader fw = new FileReader (f1);
BufferdReader br = new BufferdReader (fr);
String s1 = br.readline();
While(s1!=null)
{
System.out.println (s1);
s1 = br.readline();
}}} o / p → hello hello hello hello
Page 133
JAVA
➢ File input stream and file output stream are the input class which belongs to
java.io. package . it helps to read and write the media files.
4. Write a program to read an image from the folder and write it back with
different names. Package qsp ;
Import java .io. file;
Import java.io.*;
Public class Sample
{
Public static void main ( String [ ] args ) throws IO exception
{
File f1 =new file (“D://k.jpg”);
File input stream fin = File input stream ( f1 ) ;
Byte [ ] arr =new byte [(int) f1.length ( )];
Fin.read (arr);
File output stream fout = new File output stream (“D:// rak.jpg”);
Fout.write (arr);
Fout . flush ( );
System.out.println (“rcb is back”);
}
} remove → f1. Write ( “ “ )
Page 135
JAVA
System.out.println (s3.a);
}}
Instance of operator
It checks does the object belong or instance belong to class hierarchy.
If it belongs then it returns true.
Package qsp;
Interface Animal {
Void noise ( );
}
Class Cat implements Animal { Public
Void noise ( ) {
System.out.println (“meow meow..”);
}}
Class Demo {
Public static void main ( String [ ] args ) { Animal
a1 = null ;
System.out.println (“an instance of animal”);
}
}
Page 136
JAVA
Constructor overloading
Developing multiple constructor within the class but variation in argument
list is called constructor overloading.
Variation in argument list means :
1. variation in the datatype .
2. variation in the length of the arguments.
3. variation in the order of occurrence of arguments
Page 138
JAVA
Ex 2 : class Demo {
Demo ( ) {
System.out.println( “cool” ) ;
}}
Class Tester extends Demo {
// default constructor will be created
}}
Class Sample extends Tester { Sample
() {
System.out.println( “hii” ) ;
}}
Class Mainclass {
Public static void main ( String [ ] args ) {
New Sample ( ) ;
}} o/p→ cool hi
Page 139
JAVA
Sample ©
Interface Demo
{
Int x =10;
}
Interface Tester {
Void disp ( ) ;
}
Class Sample implements Demo , Tester {
Public void disp ( )
Page 140
JAVA
{
System.out.println (“hi”);
}
Public static void main (String [ ] args )
{
Sample s1 = new Sample ( );
S1 .disp ( );
System.out.println (s1.x);
}}
Page 141
JAVA
Page 142
JAVA
4) Method can have any access The methods are by default public and
specifier. abstract.
7) Abstract class extends object It is the super most class which does
class. not extends object class.
Constructor chaining :
sub class constructor calling its immediate super class constructor intern
Page 143
JAVA
super class constructor calling its immediate super class constructor is called as
constructor chaining.
Why the main method is declared as Public static void main (String [ ] args ) ?
➢ Public is application level access where JVM should be able to access main
method for execution.
➢ Static is the modifier which helps to load the main method before execution.
➢ The return type is void where main method does not return any value.
➢ Main is the method name.
➢ The parameter are of string [ ] type because main method receives the input
in the form of string [ ] array.
Int x = IntegerparseInt (“123”) ; → convert from string to int
System.out.println ( x ) ;
Wrapper class
Wrapper class are the inbuilt classes which belongs to java. Lang package .
➢ For each and every primitive data type we have the corresponding class and
those classes are called as wrapper class.
➢ We can perform an operation called boxing and unboxing.
Boxing
Converting from primitive data type to wrapper class object is called as
boxing.
Unboxing
Converting from wrapper class object back to its primitive data type is called as
Unboxing.
primitive data type wrapper class
Byte byte
Short short
Int integer
Long long
Double double
Page 144
JAVA
Char Char
Boolean boolean
Page 145
JAVA
Class Mobile
{ Int mob_cost ;
String mob_name ;
String mob_color ;
Mobile (Int mob_cost , String mob_name , String mob_color ) {
This . mob_cost = mob_cost ;
This . mob_name = mob_name ;
This . mob_color = mob_color ;
}
Public static void main (String [] args ) {
Mobile m1 = new Mobile (25000 , “oneplus 6 “ , “black”);
System.out.println( m1 . mob_cost);
System.out.println( m1 . mob_name);
Page 146
JAVA
System.out.println( m1 . mob_color);
}}
REVERSE Order
Package collection topic ;
Import java . util. Arraylist ;
Class Sample {
Public static void main (String [] args ) {
Arraylist l1 = new Arraylist ( );
l1.add(80); l1.add(20.56);
l1.add(‘A’);
l1.add(“hello”);
l1.add(10);
for (int i= l1.size ( ) -1 ; i>=0 ; i--)
{
System.out.println( l1.get[i]);
}}}
o/p → 10 A 80
Page 147
JAVA
Page 148
JAVA
Page 149
JAVA
Any member of the class declared without a keyword static is called as Non
- static member of the class.
20. Define composition?
The class having an object of another class is known as composition. It is
also called HAS a relationship.
21. What is static initialization block?
Any block which is declared with a keyword static is called as static
initialization block . SIB is used to initialize static members. SIB will get
executed before main method.
22. What is Non - static initialization block?
Any block which is declared without a keyword static is called as Instance
initialization block. IIB is used to initialize non - static members. IIB will get
executed whenever an object is created.
23. What are pass by value and pass by reference ?
Calling or invoking a method by passing primitive type of data is called as
call by value or pass by value.
Calling or invoking a method by passing references variables is called as
call by references or pass by references.
24. What is a Constructor ?
It is a special type of method or special type (member) of the class which is
used to initialize data members.
25. How many types of constructors are used in Java?
Page 152
JAVA
Page 153
JAVA
Page 154
JAVA
Any members of the class declared with the keyword protected is called as “
protected member of the class “.
56. What is public access modifier?
Any members of the class declared with a keyword public is called as “ public
access specifier”.
57. Why is String class considered immutable?
When multiple reference variable are pointing to a single object and if one of
the reference variable de reference with the current object it will not affect other
reference variable. This is why it is immutable.
58. Why is String Buffer called mutable?
The String class is considered as immutable, so that once it is created a
String object cannot be changed. If there is a necessity to make a lot of
modifications to Strings of characters then String Buffer should be used. 59.
What is the difference between String Buffer and StringBuilder class?
Use StringBuilder whenever possible because it is faster than String Buffer. But, if
thread safety is necessary then use String Buffer objects.
60. what is Thread ?
Thread is an extension instance which owns of its own CPU time and memory.
61. What do you mean by Multithreaded program?
Processing multiple threads simultaneously is called as multi - threading.
62. What is Sleep method ?
Sleep method is a static method which pause its execution for few
milliseconds.
63. What is multi – tasking ?
It is a Process of executing multiple task simultaneously is called as multi -
tasking.
64. What is Synchronized ?
Processing one by one thread is called as Synchronized .
Page 155
JAVA
Page 156
JAVA
Page 157
JAVA
Page 158
JAVA
It is used to sort collections and arrays of objects using the collections. sort
and java.util. The objects of the class implementing the Comparable interface can
be ordered.
90. Why Vector class is used?
The Vector class provides the capability to implement a growable array of
objects. Vector proves to be very useful if you don't know the size of the array in
advance, or you just need one that can change sizes over the lifetime of a program.
91. What are the advantages of Array List over arrays?
Array List can grow dynamically and provides more powerful insertion and
search mechanisms than arrays.
92. Why deletion in Linked List is fast than Array List?
Deletion in linked list is fast because it involves only updating the next
pointer in the node before the deleted node and updating the previous pointer in the
node after the deleted node.
93. How do you decide when to use Array List and Linked List?
If you need to frequently add and remove elements from the middle of the
list and only access the list elements sequentially, then LinkedList should be used.
If you need to support random access, without inserting or removing elements from
any place other than the end, then Array List should be used.
94. What is a Values Collection View ?
It is a collection returned by the values method of the Map Interface, It
contains all the objects present as values in the map.
95. Which package is used for pattern matching with regular expressions?
java.util.regex package is used for this purpose.
96. java.util.regex consists of which classes?
java.util.regex consists of three classes − Pattern class, Matcher class and
Pattern Syntax Exception class.
97. What is finalize method?
Page 159
JAVA
Page 160
JAVA
Final classes are created so the methods implemented by that class cannot be
overridden. It can’t be inherited.
106. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF8
characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII
character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents
characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit
patterns.
107. Which Java operator is right associative?
The = operator is right associative.
108. What is the difference between a break statement and a continue
statement?
A break statement results in the termination of the statement to which it
applies switch ,for ,do ,or while. A continue statement is used to end the current
loop iteration and return control to the loop statement.
109. What are Class Loaders?
A class loader is an object that is responsible for loading classes. The class Class
Loader is an abstract class.
110. What will happen if static modifier is removed from the signature of the
main method?
Program throws "No Such Method Error" error at runtime.
111. What is the default value of an object reference declared as an instance
variable?
Null, unless it is defined explicitly. 112.
Can constructor be inherited?
No, constructor cannot be inherited
113. What is the difference between the >> and >>> operators?
Page 161
JAVA
The >> operator carries the sign bit when shifting right. The >>> zero-fills
bits that have been shifted out.
114. Does Java allow Default Arguments?
No, Java does not allow Default Arguments.
115. Where import statement is used in a Java program?
Import statement is allowed at the beginning of the program file after
package statement.
116. Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can
extend more than one Interface.
117. Which object oriented Concept is achieved by using overloading and
overriding?
Polymorphism
118. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.
119. Is there any need to import java. Lang package?
No, there is no need to import this package. It is by default loaded internally
by the JVM.
120. What environment variables do I need to set on my machine in order to
be able to run Java programs?
CLASSPATH and PATH are the two variables.
121. What is an enumeration?
An enumeration is an interface containing methods for accessing the
underlying data structure from which the enumeration is obtained. It allows
sequential access to all the elements stored in the collection.
122. What is difference between Path and Class path?
Page 162
JAVA
Path and Class path are operating system level environment variables. Path
is defines where the system can find the executables.exe files and class path is used
to specify the location of .class files.
123. What is an Applet ?
A java applet is program that can be included in a HTML page and be
executed in a java enabled client browser. Applets are used for creating dynamic
and interactive web applications.
124. Explain the life cycle of an Applet.
An applet may undergo the following states:
• Init : An applet is initialized each time is loaded.
• Start : Begin the execution of an applet.
• Stop : Stop the execution of an applet.
• Destroy : Perform a final cleanup, before unloading the applet.
125. What happens when an applet is loaded ?
First of all, an instance of the applet’s controlling class is created. Then, the
applet initializes itself and finally, it starts running.
126. The immediate superclass of the Applet class?
Panel is the immediate superclass. A panel provides space in which an
application can attach any other component, including other panels.
127. Define canvas?
It is a simple drawing surface which are used for painting images or to
perform other graphical operations.
128. Define Network Programming?
It refers to writing programs that execute across multiple devices computers,
in which the devices are all connected to each other using a network.
129. What is a Socket?
Page 163
JAVA
Page 164
JAVA
Page 165
JAVA
Page 166
JAVA
This method is used to method is used to load the driver that will establish a
connection to the database.
152. What is the advantage of Prepared Statement over Statement ?
Prepared Statements are precompiled and thus, their performance is much
better. Also, Prepared Statement objects can be reused with different input values
to their queries.
153. What is the use of Call able Statement ? Name the method, which is used
to prepare a Call able Statement.
A Call able Statement is used to execute stored procedures. Stored
procedures are stored and offered by a database. Stored procedures may take
input values from the user and may return a result. The usage of stored
procedures is highly encouraged, because it offers security and modularity.
The method that prepares a Call able Statement is the following: Call able
Statement. Prepare Call();
154. What does Connection pooling mean ?
The interaction with a database can be costly, regarding the opening and
closing of database connections. Especially, when the number of database clients
increases, this cost is very high and a large number of resources is consumed. A
pool of database connections is obtained at start up by the application server and is
maintained in a pool. A request for a connection is served by a connection residing
in the pool. In the end of the connection, the request is returned to the pool and can
be used to satisfy future requests.
155. What is RMI ?
The Java Remote Method Invocation (Java RMI) is a Java API that performs
the object-oriented equivalent of remote procedure calls(RPC),with support for
direct transfer of serialized Java classes and distributed garbage collection. Remote
Method Invocation(RMI) can also be seen as the process of activating a method on
a remotely running object. RMI offers location transparency because a user feels
that a method is executed on a locally running object. Check some RMI Tips here.
156. What is the basic principle of RMI architecture ?
Page 167
JAVA
Page 168
JAVA
remote object can be associated with a name using the bind or rebind methods of
the Naming class.
161. What is the difference between using bind() and rebind() methods of
Naming Class ?
The bind method bind is responsible for binding the specified name to a
remote object, while the rebind method is responsible for rebinding the specified
name to a new remote object. In case a binding exists for that name, the binding is
replaced.
162. What are the steps involved to make work a RMI program ?
The following steps must be involved in order for a RMI program to work
properly:
• Compilation of all source files.
• Generation of the stubs using rmic.
• Start the rmi registry.
• Start the RMI Server.
• Run the client program.
163. What is the role of stub in RMI ?
A stub for a remote object acts as a client’s local representative or proxy for
the remote object. The caller invokes a method on the local stub, which is
responsible for executing the method on the remote object. When a stub’s method
is invoked ,it undergoes the following steps:
• It initiates a connection to the remote JVM containing the remote object.
• It marshals the parameters to the remote JVM.
• It waits for the result of the method invocation and execution.
• It un marshals the return value or an exception if the method has not been
successfully executed.
• It returns the value to the caller.
Page 169
JAVA
Page 170
JAVA
Page 171
JAVA
Page 172
JAVA
• Status Code: describes the status of the response. It can be used to check if
the request has been successfully completed. In case the request failed, the status
code can be used to find out the reason behind the failure. If your servlet does not
return a status code, the success status code, Http Servlet Response. SC_OK, is
returned by default.
• HTTP Headers: they contain more information about the response. For
example, the headers may specify the date/time after which the response is
considered state, or the form of encoding used to safely transfer the entity to the
user. See how to retrieve headers in Servlet here.
• Body: it contains the content of the response. The body may contain HTML
code, an image, etc. The body consists of the data bytes transmitted in an HTTP
transaction message immediately following the headers.
179. What is a cookie ? What is the difference between session and cookie ?
A cookie is a bit of information that the Web server sends to the browser.
The browser stores the cookies for each Web server in a local file. In a future
request, the browser, along with the request, sends all stored cookies for that
specific Web server. The differences between session and a cookie are the
following:
• The session should work, regardless of the settings on the client browser.
The client may have chosen to disable cookies. However, the sessions still work, as
the client has no ability to disable them in the server side.
• The session and cookies also differ in the amount of information the can
store. The HTTP session is capable of storing any Java object, while a cookie can
only store String objects.
180. Which protocol will be used by browser and servlet to communicate ?
The browser communicates with a servlet by using the HTTP protocol.
181. What is HTTP Tunneling ?
HTTP Tunneling is a technique by which, communications performed using
various network protocols are encapsulated using the HTTP or HTTPS protocols.
The HTTP protocol therefore acts as a wrapper for a channel that the network
Page 173
JAVA
Page 174
JAVA
Page 175
JAVA
Page 176
JAVA
Java programs
1. Check if number is odd or even.
2. Factorial of a number.
3. To find Fibonacci series for 1st ten number or within the range 100 using for loop.
4. To find Fibonacci series for 1st ten number or within the range 100 using while loop.
5. To check given number is prime number or not.
6. To check given number is prime number or not ( range of input ).
7. To find sum of digits of a given number.
8. To check whether given number is a Armstrong no or not.
9. To check given number is strong or not.
10. To check or count how many Binary digit are present in given number.
11. To count the number of digits in a given number
12. Reverse a given number.
13. To check whether the given number is palindrome or not.
14. To print the tables .
15. To find the power of a number.
16. To compute the quotient and remainder.
Page 177
JAVA
Page 178
JAVA
Page 179
JAVA
Page 180
JAVA
}
5. To check given number is prime number or not.
class Primeno1
{
public static void main(String[] args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number: ");
n = sc . nextInt ( ) ; boolean flag=true;
for(int i=2;i<n; i++)
{
if( n % i==0 )
{ flag=fals
e; break; }
}
if(flag==true)
{
System.out.println("It is a prime number : " + n);
} else
{
System.out.println("It is not a prime number : " + n);
}
}
}
6. To check given number is prime number or not ( range of input ).
class Primeno2
{
public static void main(String[] args)
{
for(int k=2;k<=100;k++)
{ int n=k; boolean
flag=true; for(int
i=2;i<n ; i++)
{
if(n % i ==0)
{ flag=fals
e; break; }
}
if(flag==true)
Page 181
JAVA
{
System.out.println("It is a prime number : " +n);
}
}
}
}
7. To find sum of digits of a given number.
class Sum {
public static void main(String[] args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ;
int sum=0;
while(n!=0) { int
rem = n % 10 ; sum
= sum + rem ; n =
n / 10;
}
System.out.println("Sum of a number : " +sum);
}
}
8. To check whether given number is a Armstrong no or not
class Armstrongno
{
public static void main(String[] args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int copy=n; int
sum=0; while(n!=0)
{
int rem = n % 10 ; sum = sum + (
rem * rem * rem ) ; n = n / 10; }
if(sum == copy)
{
System.out.println("It is Armstrong number : "+copy);
} else
Page 182
JAVA
{
System.out.println("It is not Armstrong number : "+copy);
}
}
}
9. To check given number is strong or not.
class Strongno
{
public static void main(String[]args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int sum=0; int
fact=1; int copy=n; while(n!=0) { int
rem=n%10;
for(int i=rem ; i>=1;i--)
{
fact=fact*i;
} sum=sum +
rem; n=n/10; }
if(copy==sum) {
System.out.println("It is Strong no : " +copy);
} else
{
System.out.println("It is not Strong no : " +copy);
}
}
}
10. To check or count how many Binary digit are present in given number.
class Binarycount
{
public static void main(String[]args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int count=0;
while(n!=0)
Page 183
JAVA
{ int rem=n%10;
if(rem==0 || rem==1)
{ count+
+; }
n=n/10;
}
System.out.println(count);
}
}
11. To count the number of digits in a given number.
class Digitcount
{
public static void main(String[] args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int count=0;
while(n!=0) { n=n/10; count++;
}
System.out.println("count of a number : " +count);
}
}
12. Reverse a given number.
class Reverseno
{
public static void main(String[]args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int rev=0; while(n!
=0) { int rem=n%10;
rev=rev*10+rem; n=n/10;
}
System.out.println("reverse of the number is : " + rev);
}
}
13. To check whether the given number is palindrome or not.
Page 184
JAVA
class Palindromeno
{
public static void main(String[]args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
n = sc . nextInt ( ) ; int rev=0; int
copy=n; while(n!=0) { int rem=n%10;
rev=rev*10+rem; n=n/10; }
if(copy==rev)
{
System.out.println("palindrome number is : " +copy);
} else
{
System.out.println("Not palindrome number is : " +copy);
}
}
}
14. To print the tables .
class Tables
{
public static void main(String []args)
{ int n
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : "); n
= sc . nextInt ( ) ;
for(int i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+(n*i));
}
}
}
15. To find the power of a number.
class Powerno
{
public static void main(String[] args)
{ int n , p
;
Page 185
JAVA
Page 186
JAVA
class Reversestring2
{
public static void main(String[] args)
{
String s1 ;
Scanner sc = new Scanner(System.in); System.out.println("Enter
the String :");
s1=sc.nextLine();
String s2 = " "; int
i=s1.length()-1;
while (i>=0) {
s2 = s2 + s1.charAt(i) ; i--;
}
System.out.println("reverse String is : "+s2 ) ;
}
}
21. To reverse a String without using loop.
class Reversestring3
{
static String s1="java"; static
String s2 = " ";
public static void main(String[] args)
{
int x=s1.length()-1; disp(x);
System.out.println(s2) ;
}
static void disp(int n)
{
if( n >= 0 )
{
s2 = s2 + s1.charAt(n) ;
n--; disp(n);
}
}
}
22. To check whether a String is palindrome or not.
class Palindromestring
{
public static void main(String[] args)
Page 188
JAVA
{
String s1 ;
Scanner sc = new Scanner(System.in); System.out.println("Enter
the String :");
s1=sc.nextLine(); String
s2 = " ";
for(int i=s1.length()-1;i>=0;i--)
{
s2 = s2 + s1.charAt(i);
}
if(s1.equals(s2))
{
System.out.println("It is a palindrome : "+s2) ;
} else
{
System.out.println("It is not a palindrome : "+s2) ;
}
}
}
23. To accept a character , determine whether the character is a lowercase or
uppercase.
class Character
{
public static void main(String[] args)
{ char ch='R';
if(ch>='A' && ch<='Z')
{
System.out.println("It is a uppercase character : " + ch);
}
else if(ch>='a' && ch<='z')
{
System.out.println("It is a lowercase character : " + ch);
}
}
}
24. To find the area and circumference of the circle.
class Circle
{
public static void main(String[] args)
Page 189
JAVA
{ int r
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number : ");
r = sc . nextInt ( ) ; final double
pi=3.142; double area = pi*r*r; double
circum = 2*pi*r;
System.out.println("Area of the Circle : " + area);
System.out.println("Circumference of the Circle : " + circum);
}
}
25. To convert days into years , months and days.
class Days {
public static void main(String[] args)
{ int totaldays
;
int days , months , years;
Scanner sc = new Scanner(System .in ) ;
System.out.println("Enter the totaldays : ");
totaldays = sc . nextInt(); years =
totaldays/365; totaldays = totaldays%365;
months = totaldays/30; days = totaldays%30;
System.out.println("Years : " + years);
System.out.println("Months : " + months);
System.out.println("Days : " + days);
}
}
26. To find grade of the student.
class Grade {
public static void main(String[] args)
{ int marks
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the marks : ");
marks = sc . nextInt ( ) ; if(marks>=85
&& marks<=100)
System.out.println("Distinction : " + marks); else
if (marks>=60)
System.out.println("First class : " + marks); else
if(marks>=50)
Page 190
JAVA
Page 191
JAVA
{
public static void main(String[] args)
{ int year
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the year : "); year
= sc . nextInt ( ) ;
if(year%4 == 0 && year!=100 || year%400 == 0)
System.out.println("It is a Leap year : " + year); else
{
System.out.println("It is not a Leap year :" + year);
}
}
}
30. To find the square and cube of a number .
class sqrcube
{
public static void main(String[] args)
{ int a
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the number :");
a = sc . nextInt ( ) ; int square = a * a;
int cube = a * a * a;
System.out.println("Square of the number : " +square);
System.out.println("Cube of the number : " +cube);
}
}
31. To convert the temperature in Fahrenheit into Celsius
class Temperature
{
public static void main(String[] args)
{
double Fahren ;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the Fahrenheit :");
Fahren = sc . nextDouble(); double
Celsius ;
Celsius =((5.0 / 9.0) * Fahren - 32.0);
Page 192
JAVA
Page 193
JAVA
{ int a ,b
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the value of a and b : ");
a = sc . nextInt () ; b = sc . nextInt () ; int
temp=a; a=b; b=temp;
System.out.println("After swapping the value of a is : "+a);
System.out.println("After swapping the value of b is : "+b);
}
}
35. Swap two numbers without using 3 rd. variable.
class Swap2
{
public static void main(String[] args)
{ int a ,b
;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the value of a and b : ");
a = sc . nextInt () ; b = sc . nextInt () ; a = a +
b; b = a - b; a = a - b;
System.out.println("After swapping the value of a is : "+a);
System.out.println("After swapping the value of b is : "+b);
}
}
36. To sort an array in ascending order (Bubble sort).
class Bubblesort
{
public static void main(String[] args)
{
int [ ] arr = { 8 , 7 , 5 , 9 , 2 , 10 };
int n=arr.length-1; for( int i=1;i<n; i+
+)
{
for( int j=1;j<n; j++)
{
if ( arr[ j - 1 ] > arr[ j ] )
{
int temp = arr [ j-1 ] ; arr
[ j-1 ] = arr [ j ] ; arr
[ j ] = temp ;
Page 194
JAVA
}
} }
for( int i=0 ; i<arr.length; i++)
{
System.out.println( arr[ i ]+ " ");
}
}
}
37. write a program to generate capca or OTP.
class OTP {
public static void main(String[] args)
{
String s1="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String s2= s1.toLowerCase();
String s3= "123456789";
String s4 =s1+s2+s3; Random
r = new Random (); char []
pwd = new char[5]; for(int
i=0;i<5;i++)
{
pwd[i] = s4.charAt(r. nextInt(s4.length()));
}
for(int i=0;i<5;i++)
{
System.out.println(pwd[i]);
}
}
}
38. To generate Random numbers.
class GenerateRandom
{
public static void main(String[] args)
{
Random rm = new Random();
System.out.println("Random numbers are : ");
System.out.println("*******************"); for(int
i=1;i<=5;i++)
{
System.out.println(rm.nextInt(10));
}
Page 195
JAVA
}
}
39. To get the IP Address
class GetMyIPAddress
{
public static void main(String[] args) throws
UnknownHostException
{
InetAddress myIP = InetAddress.getLocalHost();
System.out.println("My IP address is : ");
System.out.println(myIP.getHostAddress());
}
}
40. To print the number in pyramid shape.
class Pyramidshape
{
public static void main(String[] args)
{ int n
;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : ");
n=sc.nextInt(); for(int i=1;i<n;i++)
{
for(int j=1;j<=n;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(" "+k+ " ");
}
for(int m=n-1;m>0;m--)
{
System.out.print(" "+m+ " ");
}
System.out.println();
}
}
}
Page 196
JAVA
Page 197
JAVA
}
}
43. To find Natural number.
class Naturalno
{
public static void main(String[] args)
{
int n ,sum = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: "); n
= sc.nextInt();
for(int i=0;i<=n;i++)
{
sum = sum + i ;
}
System.out.println("Sum of natural numbers is : " +sum);
}
}
44. To find the perfect square.
class Perfectsquare
{
static boolean checkPerfectSquare(double x)
{
double sq = Math.sqrt(x); return
((sq-Math.floor(sq))==0);
}
public static void main(String[] args)
{ double num
;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : "); num
= sc.nextDouble(); if(checkPerfectSquare(num))
System.out.println(num+" is a perfect square number"); else
System.out.println(num+" is not a perfect square number");
}
}
45. To find whether the number is positive or negative .
class Posneg
Page 198
JAVA
{
public static void main(String[] args)
{ int num
;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : ");
num = sc.nextInt(); if(num>0)
{
System.out.println(num+ " is a positive number");
} if(num<0)
{
System.out.println(num+ " is a negative number");
}
}
}
46. Addition of 2 matrices.
class Add2matrix
{
public static void main(String[] args)
{
int rows , cols , c ,d ;
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number for rows and columns : ");
rows = sc.nextInt(); cols = sc.nextInt();
int a [][] = new int [rows][cols] ; int
b [][] = new int [rows][cols] ; int sum
[][] = new int [rows][cols] ;
System.out.println("Enter the elements of 1st matrix : ");
for(c=0;c<rows;c++) for(d=0;d<cols;d++) a[c][d] =
sc .nextInt();
System.out.println("Enter the elements of 2nd matrix : ");
for(c=0;c<rows;c++) for(d=0;d<cols;d++) b[c][d] =
sc .nextInt(); for(c=0;c<rows;c++) for(d=0;d<cols;d++)
sum[c][d] = a[c][d] + b[c][d] ;
System.out.println("Sum of the matrices : ");
for(c=0;c<rows;c++)
{
for(d=0;d<cols;d++)
System.out.println(sum[c][d]+ "\t");
}
Page 199
JAVA
}
}
47. multiplication of 2 matrices.
class Multiply2matrix
{
public static void main(String[] args) {
int m , n , p , q , sum = 0 , c ,d , k ;
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number for rows and columns of 1st
matrix : "); m = sc.nextInt(); n = sc.nextInt();
int a [][] = new int [m][n] ;
System.out.println("Enter the numbers of 1st matrix : ");
for(c=0;c<m;c++) for(d=0;d<n;d++) a[c][d] =
sc .nextInt();
System.out.println("Enter the number for rows and columns of 2nd
matrix : "); p = sc .nextInt(); q = sc .nextInt(); if (n!=p)
System.out.println("matrices entered order can't be multiplied
with each other"); else {
int b [][] = new int [p][q]; int
multiply[][] = new int[m][q];
System.out.println("Enter the elements of 2nd matrix : ");
for(c=0;c<p;c++) for(d=0;d<q;d++) b[c][d] = sc.nextInt();
for(c=0;c<m;c++)
{
for(d=0;d<q;d++)
{
for(k=0;k<p;k++)
{
sum = sum + a[c][k] * b[k][d] ;
}
multiply[c][d] = sum; sum=0;
}
}
System.out.println("Multiplication of matrices: ");
for(c=0;c<m;c++)
{
for(d=0;d<q;q++)
System.out.println(multiply[c][d]+"\t");
System.out.println("\n");
}
Page 200
JAVA
}
}
}
48. write a program for linear search algorithm or count how many times the
character is repeated in a given string.
class Linersearch
{
public static void main(String[] args)
{
String str ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String : ");
str = sc.nextLine(); int count=0;
char[]arr=str.toCharArray(); for
(int i=0;i<arr.length; i++)
{
if(arr[i]=='a')
{
count++;
}
System.out.println(count);
}
}
}
49. To find the character position in the String.
class CharString
{
public static void main(String[] args)
{
String str ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String : "); str
= sc.nextLine();
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position : " +ch);
}
Page 201
JAVA
}
}
50. To replace char ‘A’ with ‘O’ in the given String.
class Replacechar
{
public static void main(String[] args)
{
String s1 ="java"; String s2 =
" " ; char [] arr =
s1.toCharArray(); for (int
i=0;i<arr.length;i++)
{ if(arr[i]=='a
') { s2 = s2 +
'o' ; } else {
s2 = s2 + arr[i];
}
}
System.out.println(s2);
}
}
Page 202