Notes
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,
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
} }
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 10
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 11
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 12
JAVA
Conditional statements
To check for logical conditions, we should go for conditional statements.
1. If – conditions
Syntax : if ( condition )
{
---------
---------
Page 13
JAVA
}
Ex: class Demo {
public static void main(String[] args) {
If (5>3)
{
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 )
Page 14
JAVA
{
---------
} else if ( condition ){
-----
} 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 15
JAVA
------
} else {
------
}
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++;
Page 16
JAVA
Switch case :
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 17
JAVA
Page 18
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 19
JAVA
class Tester {
public static void main(String[] args) {
Tester. Area();
} }
Page 20
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
It will create random It will initialize all the non
memory space into – static members into
the heap memory the heap memory heap
memory
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
Page 21
JAVA
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.
Stack Heap
memory
It has 4 parts
1. stack – It is used for execution which follows last in first out [ LIFO ] .
2. Heap memory – It is used to store non – static members of the class. Whenever
we create an object at the instance non – static members will be stored in the heap
memory.
3. static pool area - It is used to store static members of the class. Whenever class
loader loads the class at that instance static members will get initialized in the
static pool area.
4. method area – It is used to store method body or definition . Irrespective of
static or non – static all the method bodies will be stored in method area.
Page 22
JAVA
System.out.println(result);
}
public static void main(String[] args) {
new Circle().area();
}}
Page 23
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 24
JAVA
Page 25
JAVA
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) {
Demo1 d1 = new Demo1( );
System.out.println(d1);
Demo1 d2 = new Demo1( );
System.out.println(d2);
}}
Output → Demo1 @ 15db9742 ,, Demo2 @ 06d69c
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;
Page 26
JAVA
COMPOSITION / AGGREGATIONS
A class having an object of another class is called as composition.
It is also called as has a relationship.
Page 27
JAVA
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 ( ) ;
}}
Tester Sample
Has a relationship
Void : add ( ) Tester : t1
BLOCKS
There are two blocks
Page 28
JAVA
Page 29
JAVA
Page 30
JAVA
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.
Page 31
JAVA
Syntax :
Class class_name {
Class_name ( ) {
----
Return;
}}
Page 32
JAVA
Sample ( int y ) {
X=y;
}
Public static void main ( String [ ] args) {
Sample s1 = New Sample ( 10 ) ;
System.out.println(s1.x) ;
}}
Constructor
Page 33
JAVA
Page 34
JAVA
This keyword
It is used to point to the current object whenever the local variable and
global variable names are same to differentiate between them we use “ this “
keyword.
➢ This keyword should be used only in the non – static constructor.
➢ This keyword is the default references variables.
Class Demo {
Int a =10 ;
Void add ( ) {
Int a= 20;
System.out.println (a);
System.out.println (this. a);
}}
Page 35
JAVA
System.out.println(e1. emp _ id ) ;
System.out.println(e1. emp _ name ) ;
System.out.println(e1. emp _ Sal ) ;
}}
Page 36
JAVA
ARRAYS
Array is liner data structure which is used to store homogenous type of data.
Drawbacks:
➢ In array the size is fixed
➢ it can store only homogeneous type of data.
Array
Int a=10; Int b=20; Int c=30;
Int a=b;
Array declaration
Syntax: Datatype [ ] array _ name ;
Ex: int [ ] arr ;
Array Initialization
System.out.println(arr [0]);
System.out.println(arr [1]);
Page 37
JAVA
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.
10 20 30 40 50
0 1 2 3 4
class Array{
public static void main ( String [ ] args ) {
int[] arr = new int[3] ;
arr [ 0 ] = 10 ;
arr [ 1 ] = 20 ;
arr [ 2 ] = 30 ;
for ( int i=0; i<= arr . length ; i++ )
{
System.out.println(i+"\t"+ arr[i]);
}}}
class Array {
public static void main ( String [ ] args ){
int[] arr = {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 ‘ ;
Page 39
JAVA
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++ )
{
System.out.println(“ i+ “ \t” + arr [ i ] “ );
}}}
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.
Page 40
JAVA
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 );
}
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);
}
}
Page 41
JAVA
Page 42
JAVA
State : state defines the non – static variables , what data it can hold.
Behaviour : behaviour defines non – static methods and the way it can behave.
➢ Whenever we create an object we get both state and behaviour.
➢ The object address will be stored in reference variable.
➢ Multiple reference variable can hold multiple object address.
Ref1 address object
Ref2 address object
➢ Any changes made to the object through a reference variable, it will not
affect other reference variables.
➢ Multiple reference variable can point ( hold ) single object address.
➢ Any changes made through a reference variable, it will affect other
reference variables.
Ref1 address object
Ref2
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 43
JAVA
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.
Page 44
JAVA
Tester ©
Int : x
Sample © Demo ©
4. MULTIPLE INHERITANCE
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 45
JAVA
Tester 4 ©
Int : x
Demo 4 ©
Sample 6 ©
Void : add ( )
Int : x
Sample 4 ©
Void : disp ( )
Page 46
JAVA
}}
Ex : hierarchical inheritance
Class Tester {
Int y=10;
}
Page 47
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 48
JAVA
}}
Class WhatsApp _ v2 extends WhatsApp _ v1 {
Void status ( ) {
System.out.println ( “status with text , images ,videos ” ) ;
}}
Class Mainclass {
Public static void main ( String [ ] args ) {
WhatsApp w2 = new WhatsApp _ v2 ( ) ;
W2 . status ( ) ;
}}
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 49
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 50
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 51
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 52
JAVA
Converting from one class object to another class type is called Derived /
class type casting.
Up casting → Implicitly , explicitly
Converting from subclass object to superclass type is called as up casting.
➢ up casting can be done both Implicitly and explicitly.
Down casting → explicitly
Converting from superclass object to subclass type is called as Down
casting.
➢ Down casting should be done always explicitly.
➢ Without performing up casting we cannot perform down casting.
➢ Direct down casting is not possible.
➢ To perform upcasting or down casting there should be a Is a relationship.
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 ©
Void : disp ( )
Sub class type
Sub class object
Ex : Class Demo {
Page 53
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 54
JAVA
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 ( ) ;
W1.send (123);
W1.send (“hello”);
W1.send (126 ,”hi”);
Page 55
JAVA
W1.send (“bye”,127);
}}
Page 56
JAVA
Note : In the case of method overriding even though it is upcasted we will get
overridden implementation.
Animal a1=new Cat();
A1.noise();
Animal a1=new Dog();
A1.noise();
Animal a1=new Snake();
A1.noise();
Animal ©
void : noise ( )
Dog d1
Snake s1
Ex:
Package poly;
Class Animal {
Void noise ( ) {
Page 57
JAVA
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();
Snake s1 = new Snake();
Stimulator. anisum (c);
Stimulator. anisum (d1);
Page 58
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 59
JAVA
3. ABSTRACT METHOD
Any method which is declared with a keyword abstract is called as “
Abstract method “.
Ex:
Abstract void disp ( ) ;
4. ABSTRACT Class
Any class which is declared with a keyword abstract is called as “ Abstract
class“.
Ex:
Abstract class Demo {
-----
}
5. If a class is having an abstract method then the class should be declared as
abstract but vice versa is not true.
Ex:
Abstract class Sample {
Abstract void disp ( ) ;
}
6. An abstract class can have both concrete method and as well as abstract
method.
Ex:
Abstract void cool ( )
Void fool ( ) {
System.out.println (“hello”);
Page 60
JAVA
}}
➢ We cannot create object for abstract class and interface.
➢ We can develop only abstract methods in the abstract class.
➢ 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 61
JAVA
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.
Page 62
JAVA
Ex:
( abstract ) interface Sample {
Int a=10; // static final
Void disp ( ); // abstract public
}
Page 63
JAVA
Page 64
JAVA
}
Class Sample extends Tester {
Void cool ( ) {
System.out.println(“hello”);
}
Public static void main ( String [ ]args ) {
Sample s2 = new Sample ( );
s2.test ( );
s2.cool ( );
} }
Page 65
JAVA
a1.wheel ( );
}}
Page 66
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.
➢ Create reference variable of interface type and initialize that reference
variable with the implementation class object. This is how we can achieve
Abstraction.
➢ Through Interface we can achieve 100% Abstraction.
➢ Through abstract class we can achieve up to 100% Abstraction.
Note :
➢ When we don’t know 100% implementation then we should go for interface.
➢ When we know partial implementation, we go for abstract class.
➢ The above points are to justify when to go for abstract class and when to for
interface.
Animal (I)
void : noise ( )
Dog d1
Snake s1
Page 67
JAVA
Ex:
Interface Animal {
Void noise ( )
}
Class Cat implements Animal {
Void noise ( ) {
System.out.println(“meow meow…”);
}
}
Class Dog implements Animal {
Void noise ( ) {
System.out.println(“bow bow…”);
}
}
Class Snake implements Animal {
Void noise ( ) {
System.out.println(“buss tuss”);
}
}
Class Stimulator {
Static void anisum (Animal a1)
{
a1.noise ( );
}
}
Page 68
JAVA
Class Mainclass
{
public static void main (String []args)
{
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;
Page 69
JAVA
Class Films
{ → 3
}
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
Page 70
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
Page 71
JAVA
4. Public
Any members of the class declared with a keyword public is called as “
public access specifier”.
It can be accessed
1. within the class
2. within the package
3. outside the package ( or ) any value.
Note : All the 3 members of the class can have all access specifier and the class
can have only 2 access specifier i.e. : public and default .
public
protected
increase in default / increase in security
visibility private package
package com.family.myfamily;
public class Father {
private void atm ()
{
System.out.println("atm");
}
void car()
Page 72
JAVA
{
System.out.println("car");
}
protected void bike()
{
System.out.println("bike");
}
public void cycle()
{
System.out.println("cycle");
}
}
package com.family.myfamily;
package com.family.unclefamily;
import com.family.myfamily. Father;
public class Aunty extends Father
{
Page 73
JAVA
ENCAPSULATION
Ex 1 : Class Sample {
Private int a =10;
Public int get A ( )
{
return a ;
}
public void set A ( int a )
{
this. a =a ;
}
Page 74
JAVA
}
Class Mainclass {
Public static void main ( String [ ] args) {
Sample s1 = new Sample ( ) ;
Int y = s1.get A ( );
System.out.println( y ) ;
S1.set A (123);
System.out.println( s1.get A ) ;
System.out.println( s1.get A ) ;
}}
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 ( );
Page 75
JAVA
Page 76
JAVA
OBJECT CLASS
Object class is the super most class in java .
Each and every class extends object class.
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.
Page 77
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 ;
Page 78
JAVA
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 ] .
Page 79
JAVA
String s1 = “hi”;
String s2 = “hello”;
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 80
JAVA
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.
Page 81
JAVA
Page 82
JAVA
Page 83
JAVA
Syntax :
Page 84
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 85
JAVA
Throwable
Java . Lang Throwable
Error Exception
Page 86
JAVA
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 .
Page 87
JAVA
➢ Compile time error occurs when we write something between try and catch
block.
Page 88
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 89
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 90
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.
Page 91
JAVA
}
}
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 92
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.
Page 93
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 94
JAVA
Collection
Stack © Linked
hash set ©
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.
Page 95
JAVA
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.
➢ Since it is indexed type of collection we can do random access.
➢ It will grow its size by 50 %.
➢ It is not synchronized.
➢ Since it is not synchronized, the performance is fast.
Package java.util;
Class Arraylist {
Void add ( object obj )
Void add ( int index , object obj )
Void addAll ( collection )
Page 96
JAVA
Page 97
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 ( l2 );
System.out.println ( “---- B----");
System.out.println ( “ l1 → “ +l1);
System.out.println ( “ l2 → “ +l2);
Page 98
JAVA
} } o / p → -------A-------
L1 → [ 10 , 20 , 30 ] l2 → [ A , B , C ]
---------B-------
L1 → [ 10 , 20 , 30 , A , B , C ] l2 → [ A , B , C ]
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);
} } o / p → -------A-------
Page 99
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 100
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-------
Page 101
JAVA
L1 → [ 30 , 40 ] l2 → [ 30 , 40 , 50 , 60 ]
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);
Page 102
JAVA
} } o / p → -------A-------
L1 → [ 10 , 20 , 30 , 40 ] l2 → [ 30 , 40 , 50 , 60 ]
---------B-------
L1 → [ 10 , 20 ] l2 → [ 30 , 40 , 50 , 60 ]
Page 103
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 ( 20 ) ;
l1. Add ( 30 ) ;
l1. Add ( 40 ) ;
System.out.println ( “ l1 → “ +l1);
Collections. Sort (l1) ;
System.out.println ( “ l2 → “ +l2);
} } o / p = l1 → [ 10 , 20 , 30 , 40 ] l2 → [ 30 , 40 , 210 , 410 ]
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Import java.util . collections;
Page 104
JAVA
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 {
Page 105
JAVA
Ex : Package collectiontopic ;
Import java.util . Arraylist;
Import java.util . Arrays;
Import java.util . collections;
Import java.util . list;
Public Class Sample {
Public static void main ( String [ ] args ) {
Int [ ] arr = { 100, 200 , 300 ) ;
list l2 = array arlist ( arr );
}}
Class Sample {
Static Sample disp ( ) {
Sample x = new Sample ( );
Return x ;
}
Public static void main ( String [ ] args ) {
Sample y = disp ( );
Int [ ] abb = { 10, 20 , 30 ) ;
Int [ ] acc = abb;
Page 106
JAVA
}}
2. Vector list
vector list is a class which implements list interface.
Default capacity of vector is 10.
Features of vector 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 will grow its size by 100 %.
➢ 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);
Page 107
JAVA
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
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.
Page 108
JAVA
Page 109
JAVA
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.
➢ 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 follows “ last in first out”.
For – each loop
If we want to traverse set which is not indexed , then we should go for “ for
each loop “ .
Syntax:
For ( array_ type variable name : array name ( or ) collection reference _
variable )
Page 110
JAVA
{
----
}
Page 111
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
➢ 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.
Page 112
JAVA
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);
System.out.println(“ --- poll----");
System.out.println(L1);
System.out.println(L1.poll ( ));
System.out.println(L1);
System.out.println(L1.poll ( ));
System.out.println(L1);
System.out.println(L1.poll ( ));
System.out.println(L1);
System.out.println(“ --- peel----");
Page 113
JAVA
System.out.println(L1);
System.out.println(L1.peek ( ));
System.out.println(L1);
System.out.println(L1.peek ( ));
System.out.println(L1);
System.out.println(L1.peek ( ));
System.out.println(L1);
}}
O / p --> --------poll ----- -----------peek------
[ 10 , 16 , 20 , 100 , 80 ] 80
10 [ 80 , 100 ]
[ 16 , 80 , 200 , 20 ] 80
16 [ 80 , 100 ]
[ 20 , 80 , 100 ] 80
20 [ 80 , 100 ]
[ 80 , 100 ] 80
[ 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
Page 114
JAVA
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)
{
Hashset L1 = new Hashset ( );
L1.add(10);
L1.add(20.56);
L1.add(‘A’);
L1.add(10);
System.out.println(“hello”);
System.out.println(L1);
} } o /p → [ A, 20.56 , 10, hello ]
Page 115
JAVA
3. Tree set
Page 116
JAVA
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.
Page 117
JAVA
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;
Public class Sample
{
Public static void main(String[] args)
{
HashMap <String, Integer> L1= new HashMap <String, Integer> ( );
L1.put(“virat”,123);
L1.put(“Rakesh”,321);
System.out.println(L1);
Page 118
JAVA
}
} o/p → { virat 123 , Rakesh 321 }
Page 119
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);
L1.put(“Rakesh”,321);
System.out.println(L1);
}
} o/p → { virat 123 , Rakesh 321 }
Page 120
JAVA
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
THREAD
Thread is an extension instance which owns of its own CPU time and
memory.
Page 121
JAVA
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 {
Public static void main ( String [ ] args ) {
Page 122
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 123
JAVA
}
class Demo implements Runnable
{
Public void run ( )
{
For( int i=100; i<=110; i++ )
{
System.out.println ( I );
Try
{
Thread. Sleep (2000);
}
Catch (Interrupted exception e)
{
e.printstacktrace ( );
}
}}}
Class Mainclass {
Public static void main ( String [ ] args ) {
Sample s1 = new Sample ( );
Thread th1 = new Thread ( s1 );
th1.start ( );
Demo D1 = new Demo ( );
Thread th2 = new Thread ( D1 );
Th2.start ( );
Page 124
JAVA
}}
o/p → 1 100 2 102 3 4 ……..
Page 125
JAVA
}} 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;
Import java.io.file;
Page 126
JAVA
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 127
JAVA
Page 128
JAVA
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 129
JAVA
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;
Import java.io.filewriter;
Page 130
JAVA
Page 131
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 132
JAVA
Class Sample {
Static int count = 0 ;
Int a =10;
Static Sample s1;
Private Sample ( ) {
Count ++;
}
Public static Sample getInstance ( )
{
If (count<1)
{
S1 = new Sample ( );
}
Return s1;
}
public static void Instance ( int y )
{
S1.a =y;
}
Class Mainclass {
Public static void main ( String [ ] args ) {
Sample s2 = Sample .getinstance ( );
System.out.println (s2.a);
Sample s3 = Sample .getinstance ( );
System.out.println (s3.a);
Page 133
JAVA
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 134
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 135
JAVA
Page 136
JAVA
Sample ( int a ) {
Super ( 10.56 ) ;
System.out.println( “hii” ) ;
}}
Class Mainclass {
Public static void main ( String [ ] args ) {
New Sample ( 10 ) ;
}} o / p → hahaha cool cool hi 10
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 137
JAVA
Sample ©
Interface Demo
{
Int x =10;
}
Interface Tester {
Void disp ( ) ;
}
Class Sample implements Demo , Tester {
Public void disp ( )
{
Page 138
JAVA
System.out.println (“hi”);
}
Public static void main (String [ ] args )
{
Sample s1 = new Sample ( );
S1 .disp ( );
System.out.println (s1.x);
}}
Page 139
JAVA
Page 140
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
super class constructor calling its immediate super class constructor is called as
constructor chaining.
Page 141
JAVA
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
Char Char
Boolean boolean
Page 142
JAVA
Page 143
JAVA
Void call ( ) {
System.out.println (“ missed call “);
}}
Class Sample {
Public static void main (String [] args ) {
Arraylist <mobile> l1 = new Arraylist <mobile> ( );
l1.add(new mobile ());
l1.add(new mobile ());
l1.add(new mobile ());
mobile o1 = (mobile ) l1.get(0);
o1.call ( );
}}
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);
Page 144
JAVA
System.out.println( m1 . mob_name);
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 145
JAVA
Page 146
JAVA
Page 147
JAVA
Page 148
JAVA
o Default Constructor: default constructor is the one which does not accept
any value.
o The default constructor is mainly used to initialize the instance variable
with the default values. It can also be used for performing some useful
task on object creation. A default constructor is invoked implicitly by the
compiler if there is no constructor defined in the class.
o Parameterized Constructor: The parameterized constructor is the one
which can initialize the instance variables with the given values. In other
words, we can say that the constructors which can accept the arguments
are called parameterized constructors.
Page 149
JAVA
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.
29. Define class?
Class is a blueprint or a template to create object .
30. What do you mean by Object?
Object is real time entity which has its own state and behaviour.
31. List the three steps for creating an Object for a class?
An Object is first declared, then instantiated and then it is initialized.
32. What is Singleton class?
Singleton class control object creation, limiting the number to one but
allowing the flexibility to create more objects if the situation changes.
33. What is Inheritance ?
Inheriting the property from one class to another class is called as
Inheritance.
34. Types of Inheritance ?
1. single level Inheritance 2. multi - level Inheritance
3. hierarchical Inheritance 4. multiple Inheritance
5. hybrid Inheritance
35. Is there any limitation of using Inheritance?
Yes, since inheritance inherits everything from the super class and interface,
it may make the subclass too clustering and sometimes error-prone when dynamic
overriding or dynamic overloading in some situation.
36. When 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
Page 150
JAVA
Page 151
JAVA
Page 152
JAVA
Page 153
JAVA
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 .
Processing multiple threads simultaneously is called as “non – Synchronized “.
65. What are the two ways in which Thread can be created?
Thread can be created by - implementing Runnable interface, extending the
Thread class.
66. What invokes a thread's run method?
After a thread is started, via its start method of the Thread class, the JVM
invokes the thread's run method when the thread is initially executed.
67. Describe life cycle of thread?
A thread is a execution in a program. The life cycle of a thread include −
Newborn state, Runnable state, Running state, Blocked state, Dead state
68. What is the difference between processes and threads ?
A process is an execution of a program, while a Thread is a single execution
sequence within a process. A process can contain multiple threads. A Thread is
sometimes called a lightweight process.
69. What is the difference between yielding and sleeping?
When a task invokes its yield method, it returns to the ready state. When a
task invokes its sleep method, it returns to the waiting state.
70. How does multi-threading take place on a computer with a single CPU?
Page 154
JAVA
Page 155
JAVA
Page 156
JAVA
Page 157
JAVA
Page 158
JAVA
This is Web Archive File and used to store XML, java classes, and Java
Server pages. which is used to distribute a collection of Java Server Pages, Java
Servlets, Java classes, XML files, static Web pages etc.
103. What is the difference between object oriented programming language
and object based programming language?
Object based programming languages follow all the features of OOPs except
Inheritance. JavaScript is an example of object based programming languages.
104. Can a constructor be made final?
No, this is not possible.
105. What is final class?
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 UTF-
8 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.
Page 159
JAVA
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?
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?
Page 160
JAVA
Page 161
JAVA
Page 162
JAVA
java.net.Socket class represents the socket that both the client and server use
to communicate with each other.
134. What is the difference between a Choice and a List ?
A Choice is displayed in a compact form that must be pulled down, in order
for a user to be able to see the list of all available choices. Only one item may be
selected from a Choice.
A List may be displayed in such a way that several List items are visible. A
List supports the selection of one or more List items.
135. What is a layout manager ?
A layout manager is the used to organize the components in a container.
136. What is the difference between a Scrollbar and a JScroll Pane ?
A Scrollbar is a Component, but not a Container. A Scroll Pane is a
Container. A Scroll Pane handles its own events and performs its own scrolling.
137. Which Swing methods are thread-safe ?
There are only three thread-safe methods: repaint, revalidate, and invalidate.
138. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
139. What is clipping ?
Clipping is defined as the process of confining paint operations to a limited
area or shape.
140. What is the difference between a Menu Item and a Check box Menu
Item?
The Check box Menu Item class extends the Menu Item class and supports a
menu item that may be either checked or unchecked.
141. How are the elements of a Border Layout organized ?
Page 163
JAVA
The elements of a Border Layout are organized at the borders (North, South,
East, and West) and the center of a container.
142. How are the elements of a Grid Bag Layout organized ?
The elements of a Grid Bag Layout are organized according to a grid. The
elements are of different sizes and may occupy more than one row or column of
the grid. Thus, the rows and columns may have different sizes.
143. What is the difference between a Window and a Frame ?
The Frame class extends the Window class and defines a main application
window that can have a menu bar.
144. What is the relationship between clipping and repainting ?
When a window is repainted by the AWT painting thread, it sets the clipping
regions to the area of the window that requires repainting.
145. What is the relationship between an event-listener interface and an event
adapter class ?
An event-listener interface defines the methods that must be implemented by
an event handler for a particular event. An event adapter provides a default
implementation of an event-listener interface.
146. How can a GUI component handle its own events ?
A GUI component can handle its own events, by implementing the
corresponding event-listener interface and adding itself as its own event listener.
147. What advantage do Java’s layout managers provide over traditional
windowing systems ?
Java uses layout managers to lay out components in a consistent manner,
across all windowing platforms. Since layout managers aren’t tied to absolute
sizing and positioning, they are able to accommodate platform-specific differences
among windowing systems.
148. What is the design pattern that Java uses for all Swing components ?
Page 164
JAVA
The design pattern used by Java for all Swing components is the Model
View Controller (MVC) pattern.
149. What is JDBC ?
JDBC is an abstraction layer that allows users to choose between databases.
JDBC enables developers to write database applications in Java, without having to
concern themselves with the underlying details of a particular database.
150. Explain the role of Driver in JDBC.
The JDBC Driver provides vendor-specific implementations of the abstract
classes provided by the JDBC API. Each driver must provide implementations for
the following classes of the java. sql package : Connection, Statement, Prepared
Statement, Callable Statement, Result Set and Driver.
151. What is the purpose Class. for Name method ?
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
Page 165
JAVA
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 ?
The RMI architecture is based on a very important principle which states
that the definition of the behavior and the implementation of that behavior, are
separate concepts. RMI allows the code that defines the behavior and the code that
implements the behavior to remain separate and to run on separate JVMs.
157. What are the layers of RMI Architecture ?
The RMI architecture consists of the following layers:
• Stub and Skeleton layer: This layer lies just beneath the view of the developer.
This layer is responsible for intercepting method calls made by the client to the
interface and redirect these calls to a remote RMI Service.
• Remote Reference Layer: The second layer of the RMI architecture deals with the
interpretation of references made from the client to the server’s remote objects.
This layer interprets and manages references made from clients to the remote
service objects. The connection is a one-to-one (unicast) link.
• Transport layer: This layer is responsible for connecting the two JVM
participating in the service. This layer is based on TCP/IP connections between
machines in a network. It provides basic connectivity, as well as some firewall
penetration strategies.
Page 166
JAVA
Page 167
JAVA
Page 168
JAVA
converted to a suitable format. This process is called marshalling and the revert
operation is called demarshalling.
167. Explain Serialization and Deserialization.
Java provides a mechanism, called object serialization where an object can
be represented as a sequence of bytes and includes the object’s data, as well as
information about the object’s type, and the types of data stored in the object.
Thus, serialization can be seen as a way of flattening objects, in order to be stored
on disk, and later, read back and reconstituted. Deserialization is the reverse
process of converting an object from its flattened state to a live object.
168. What is a Servlet ?
The servlet is a Java programming language class used to process client
requests and generate dynamic web content. Servlets are mostly used to process or
store data submitted by an HTML form, provide dynamic content and manage state
information that does not exist in the stateless HTTP protocol.
169. Explain the architecture of a Servlet.
The core abstraction that must be implemented by all servlets is the
javax.servlet.Servlet interface. Each servlet must implement it either directly or
indirectly, either by extending javax.servlet.GenericServlet or javax.servlet. http.
HTTP Servlet. Finally, each servlet is able to serve multiple requests in parallel
using multithreading.
170. What is the difference between an Applet and a Servlet ?
An Applet is a client side java program that runs within a Web browser on
the client machine. On the other hand, a servlet is a server side component that
runs on the web server. An applet can use the user interface classes, while a servlet
does not have a user interface. Instead, a servlet waits for client’s HTTP requests
and generates a response in every request.
171. What is the difference between Generic Servlet and Http Servlet ?
Generic Servlet is a generalized and protocol-independent servlet that
implements the Servlet and Servlet Config interfaces. Those servlets extending the
Generic Servlet class shall override the service method. Finally, in order to develop
Page 169
JAVA
an HTTP servlet for use on the Web that serves requests using the HTTP protocol,
your servlet must extend the Http Servlet instead. Check Servlet examples here.
172. Explain the life cycle of a Servlet.
On every client’s request, the Servlet Engine loads the servlets and invokes
its init methods, in order for the servlet to be initialized. Then, the Servlet object
handles all subsequent requests coming from that client, by invoking the service
method for each request separately. Finally, the servlet is removed by calling the
server’s destroy method.
173. What is the difference between doGet() and doPost() ?
Do GET: The GET method appends the name-value pairs on the request’s
URL. Thus, there is a limit on the number of characters and subsequently on the
number of values that can be used in a client’s request. Furthermore, the values of
the request are made visible and thus, sensitive information must not be passed in
that way.
Do POST : The POST method overcomes the limit imposed by the GET
request, by sending the values of the request inside its body. Also, there is no
limitations on the number of values to be sent across. Finally, the sensitive
information passed through a POST request is not visible to an external client.
174. What is meant by a Web Application ?
A Web application is a dynamic extension of a Web or application server.
There are two types of web applications: presentation oriented and service-
oriented. A presentation-oriented Web application generates interactive web pages,
which contain various types of markup language and dynamic content in response
to requests. On the other hand, a service-oriented web application implements the
endpoint of a web service. In general, a Web application can be seen as a collection
of servlets installed under a specific subset of the server’s URL namespace.
175. What is a Server Side Include (SSI) ?
Server Side Includes (SSI) is a simple interpreted server-side scripting
language, used almost exclusively for the Web, and is embedded with a servlet tag.
The most frequent use of SSI is to include the contents of one or more files into a
Page 170
JAVA
Web page on a Web server. When a Web page is accessed by a browser, the Web
server replaces the servlet tag in that Web page with the hypertext generated by the
corresponding servlet.
176. What is Servlet Chaining ?
Servlet Chaining is the method where the output of one servlet is sent to a
second servlet. The output of the second servlet can be sent to a third servlet, and
so on. The last servlet in the chain is responsible for sending the response to the
client.
177. How do you find out what client machine is making a request to your
servlet ?
The Servlet Request class has functions for finding out the IP address or host
name of the client machine. Get Remote Addr() gets the IP address of the client
machine and get Remote Host() gets the host name of the client machine.
178. What is the structure of the HTTP response ?
The HTTP response consists of three parts:
• 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 ?
Page 171
JAVA
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
protocol being tunneled uses to communicate. The masking of other protocol
requests as HTTP requests is HTTP Tunneling.
182. What’s the difference between send Redirect and forward methods ?
The send Redirect method creates a new request, while the forward method
just forwards a request to a new target. The previous requests cope objects are not
available after are direct , because it results in an request. On the other hand, the
previous request scope objects are available after forwarding. Finally, in general,
the send Redirect method is considered to be slower compare to the forward
method.
182. What is URL Encoding and URL Decoding ?
The URL encoding procedure is responsible for replacing all the spaces and
every other extra special character of a URL, into their corresponding Hex
representation. In correspondence, URL decoding is the exact opposite procedure.
Page 172
JAVA
defined between < %@ and % >. The different types of directives are shown
below:
• Include directive: it is used to include a file and merges the content of the file
with the current page.
• Page directive: it is used to define specific attributes in the JSP page, like error
page and buffer.
• Tag lib: it is used to declare a custom tag library which is used in the page.
187. What are JSP actions ?
JSP actions use constructs in XML syntax to control the behavior of the
servlet engine. JSP actions are executed when a JSP page is requested. They can be
dynamically inserted into a file, re-use JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin. Some of the available actions
are listed below:
• jsp : include - includes a file, when the JSP page is requested.
• jsp : useBean - finds or instantiates a JavaBean.
• jsp : setProperty - sets the property of a JavaBean.
• jsp : getProperty - gets the property of a JavaBean.
• jsp : forward - forwards the requester to a new page.
• jsp : plugin - generates browser-specific code.
188. What are Scriptlets ?
In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code
embedded in a JSP page. The scriptlet is everything inside the tags. Between these
tags, a user can add any valid scriptlet.
189. What are Declarations ?
Declarations are similar to variable declarations in Java. Declarations are
used to declare variables for subsequent use in expressions or scriptlets. To add a
declaration, you must use the sequences to enclose your declarations.
Page 174
JAVA
Page 175
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.
17. To find the simple interest.
18. To find the compound interest.
19. To reverse a String using for loop.
20. To reverse a String using while loop.
21. To reverse a String without using loop.
22. To check whether a String is palindrome or not.
23. To accept a character , determine whether the character is a lowercase or uppercase..
24. To find the area and circumference of the circle.
25. To convert days into years , months and days.
26. To find grade of the student.
Page 176
JAVA
Page 177
JAVA
Page 178
JAVA
{
int a=0,b=1;
System.out.print(a+ " " +b+ " ");
for(int i=1;i<=10;i++)
{
int c=a + b;
System.out.print(c+ " ");
a=b;
b=c;
}
}
}
4. To find Fibonacci series for 1st ten number or within the range 100 using
while loop.
class Fibonacci2
{
public static void main(String[] args)
{
int a=0,b=1;
System.out.print(a+ " " +b+ " ");
int i=1;
while(i<=10)
{
int c= a +b;
System.out.print(c+ " ");
a=b;
b=c;
i++;
}
}
}
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++)
Page 179
JAVA
{
if( n % i==0 )
{
flag=false;
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=false;
break;
}
}
if(flag==true)
{
System.out.println("It is a prime number : " +n);
}
}
}
}
7. To find sum of digits of a given number.
Page 180
JAVA
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
{
System.out.println("It is not Armstrong number : "+copy);
}
}
Page 181
JAVA
}
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 182
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;
Page 183
JAVA
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.
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 ( ) ;
Page 184
JAVA
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 ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : ");
n = sc.nextInt();
System.out.println("Enter the power : ");
p = sc.nextInt();
double result = Math.pow(n, p);
System.out.println(n+"^"+p+"="+result);
}
}
16. To compute the quotient and remainder.
class Quetrem
{
public static void main(String[] args)
{
int a , b ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value for a and b : ");
a = sc.nextInt();
b = sc.nextInt();
int quot = a / b ;
int rem = a % b ;
System.out.println("Quotient : "+quot);
System.out.println("Remainder : "+rem);
}
}
17. To find the simple interest.
class SimpleInterest
{
public static void main(String[] args)
Page 185
JAVA
{
float p ,t ,r ,Si;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the principal : ");
p = sc . nextFloat();
System.out.println("Enter the Time period : ");
t = sc . nextFloat();
System.out.println("Enter the Rate of interest : ");
r = sc . nextFloat();
Si = (p*t*r)/100;
System.out.println("Simple interest is : " +Si);
}
}
18. To find the compound interest.
class Compoundinterest
{
public static void main(String[] args)
{
int p , t , n ;
double r ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the principal : ");
p = sc . nextInt();
System.out.println("Enter the Time period : ");
t = sc . nextInt();
System.out.println("Enter the Rate of interest : ");
r = sc . nextDouble();
System.out.println("Enter the number :");
n= sc.nextInt();
double amount = p * Math.pow(1 + (r / n), n * t);
double compinterest = amount - p;
System.out.println("Compound Interest after " + t + " years :
"+compinterest);
System.out.println("Amount after " + t + " years : "+amount);
}
}
19. To reverse a String using for loop.
class Reversestring1
{
public static void main(String[] args)
{
String s1 ;
Page 186
JAVA
Page 187
JAVA
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)
{
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);
Page 188
JAVA
}
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)
{
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);
}
}
Page 189
JAVA
Page 190
JAVA
{
int a , b , c ;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the value of a , b and c : ");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
int largest=a;
int smallest=a;
if(b>largest)
largest=b;
if(c>largest)
largest=c;
if(b<smallest)
smallest=b;
if(c<smallest)
smallest=c;
int seclargest=(a + b + c) - (largest + smallest);
System.out.println("Largest number is : " + largest);
System.out.println("Second largest number is : " + seclargest);
System.out.println("Smallest number is : " + smallest);
}
}
29. To check whether that year is leap year or not.
class Leapyear
{
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);
}
}
}
Page 191
JAVA
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);
System.out.println("Celsius : " +Celsius);
}
}
32. To convert seconds into hours , minutes and seconds.
class Time
{
public static void main(String[] args)
{
int totalseconds ;
int seconds , minutes , hours ;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the totalseconds :");
totalseconds = sc . nextInt() ;
seconds = totalseconds;
hours = seconds/3600 ;
seconds = seconds%3600 ;
minutes = seconds/60 ;
Page 192
JAVA
seconds = seconds%60 ;
System.out.println("Total seconds : " + totalseconds);
System.out.println("Hours : " + hours);
System.out.println("Minutes : " + minutes);
System.out.println("Seconds : " + seconds);
}
}
33. To find the area of the triangle for 3 sides.
class Triangle
{
public static void main(String[] args)
{
int s1 , s2 , s3 ;
Scanner sc = new Scanner ( System .in ) ;
System.out.println("Enter the value of s1 , s2 and s3 :");
s1 = sc . nextInt ( ) ;
s2 = sc . nextInt ( ) ;
s3 = sc . nextInt ( ) ;
int s=(s1+s2+s3)/2;
int area = (s*(s-s1)*(s-s2)*(s-s3));
System.out.println("Area of a Triangle : " + area);
}
}
34. Swap two numbers using 3 rd. variable.
class Swap1
{
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 () ;
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.
Page 193
JAVA
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 ;
}
}
}
for( int i=0 ; i<arr.length; i++)
{
System.out.println( arr[ i ]+ " ");
}
}
}
37. write a program to generate capca or OTP.
Page 194
JAVA
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));
}
}
}
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 : ");
Page 195
JAVA
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();
}
}
}
41. To find the GCD of a number.
class Gcd
{
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();
while(a != b)
{
Page 196
JAVA
if(a > b)
a = a - b ;
else
b = b - a ;
}
System.out.println("GCD of given numbers is : " +b);
}
}
42. to find missing number from the array.
class Missingnum
{
public static void main(String[] args)
{
int [] arr1 = {7,5,6,1,4,2} ;
System.out.println("Missing number from array arr1 :
"+missingNumber(arr1));
int [] arr2 = {5,3,1,2};
System.out.println("Missing number from array arr2 :
"+missingNumber(arr2));
}
public static int missingNumber (int[]arr)
{
int n = arr.length+1;
int sum = n*(n+1)/2;
int remSum = 0;
for(int i=0;i<arr.length;i++)
{
remSum+= arr[i];
}
int missingNumber = sum -remSum;
return missingNumber;
}
}
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();
Page 197
JAVA
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
{
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)
Page 198
JAVA
{
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");
}
}
}
47. multiplication of 2 matrices.
class Multiply2matrix
{
public static void main(String[] args)
{
Page 199
JAVA
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