Final Core Java - 183 Pages
Final Core Java - 183 Pages
Final Core Java - 183 Pages
1. NETWORKS
Ø In computers every thing is treated as bits and bytes.
8 bits = 1 byte
1024 bytes = 1 KB
1024 KB = 1 MB
1024 MB = 1 GB
1024 GB = 1 TB
Ø Software :
v Software is a set of programs.
v A program is a set of instructions.
Ø Hardware :
v Hardware is a physical component in the computer system which we can
see and touch.
v Example :Monitor, CPU, mouse, speakers, etc.,
Ø Protocol :
v A protocol is a specification of rules to be followed by every computer on the
network.
v A protocol contains 2 parts
1. When to send or receive data.
2. How to send or receive data.
v Packet: It represents a group of bytes of data.
A packet is send through Frame.
A frame contains not only a packet, but it also contains some other
information i.e. source address, destination address.
Each packet may be of different sizes.
Frame
Packet
INet Solv 1
Core Java
IIQ: 1
Comp 1
Comp 4 Comp 2
Comp 3
Ø Next, the Org thought to connect computers of different areas, but it is not
possible with the help of cables. Therefore it makes use of already used cables i.e.
Telephone cables. Hence it has taken the permission form the companies like AT
& T, Hyundai etc.,
INet Solv 2
Core Java
Intranet
Extranet
Intranet
Ø ISP: Internet Service Provider is an Org which provides a connection into internet.
Satellite
Client 1
64 KBPS
Internet
50 GBPS
Client 2
128 KBPS
ISP Server
INet Solv 3
Core Java
0011010100100010110101011001010111010011
Program Computer
Translator
2. Compiler : It reads all the lines at a time and gives it to the processor to
execute.
Compiler takes less time to execute than the Interpreter.
Compiler is at least 10 times faster than Interpreter.
INet Solv 4
Core Java
Spark
Not
Executed
Executed
Celeron
Not
Executed
INet Solv 5
Core Java
Spark
Processor
Not
Executed
Executed
add.c add.obj add.exe
Celeron
Processor
Not Executed
Ø In the above example the add.exe is send to 3 different processor’s (Spark,
Pentium, Celeron). The add.exe is executed only in Pentium processor since the
program is written and compiled in Pentium processor , therefore it will not
execute in Spark or Celeron processor because C, C++ is System Dependent.
INet Solv 6
Core Java
4. TYPES OF MICROPROCESSOR’S
a) 4040
b) 8080
c) 8086
d) 8088
e) 80386
f) 80486
g) 80586
h) Pentium- I
i) Celeron
j) Pentium – II
k) Pentium Pro
l) Amd Athelon
m) Pentium - III
n) Pentium – III Pro
o) Pentium – IV
Ø Every processor can understand only group of instructions and every processor
set instructions are different from each other.
Ø 8080, 8088, 8086 can understand only 120 instructions.
Ø Later on, some inst’s are added and some inst’s are removed.
Ø Celeron can understand upto 200 instructions including above added and
removed inst’s.
Ø Pentium III can understand upto 220 instrucitons.
IIQ : 2
Q: Why C & C++ are not used to develop software’s for internet?
R: C, C++ programs are System Dependent because they can be executed only on
the
computer systems where they have been developed. Therefore software for
internet
cannot be developed through C, C++.
Ø To avoid the above problem in C and C++ we make use of System Independent
Programs like JAVA.
INet Solv 7
Core Java
5. INTRODUCTION TO JAVA
Ø Java is an object oriented, multithreaded programming language developed by
Sun Microsystems.
Ø Java is not only a OOPL, but also a concurrent programming language.
Ø In java we can create classes, objects and use inheritance, we can create and
manipulate threads and other object oriented features.
Ø Java is a System Independent Programming Language.
Ø Java is a Purely Object Oriented Programming Language.
Ø In traditional language
Ø In JAVA language
INet Solv 8
Core Java
6. HISTORY OF JAVA
Ø The java language was developed by Sun Microsystems in 1992, a U.S company
has got a project for developing a software to run TV & VCR sets, interactive TV
and VCR.
Ø In 1992, a group of Sun engineers led by Patrick Naughton and Sun fellow
James Gosling (President) wanted do design a small language used for
interactive consumer devices.
Ø In September 1992, the basic system was drafted. The interactive consumer device
was called Star Seven and was part of large project called Green Project.
Ø Since C, C++ was already used for Remote Controller, but C, C++ was System
Dependent.
Ø Therefore they developed software “Oak” named after the tree outside James
Gosling office, but there was already a language named Oak existing.
Ø And later they name this software as JAVA.
Ø This software is named as JAVA because during developing the software the team
members always had to take a cup of Tea , and they thought that because of
taking lots of Tea only we had developed this software. And since this Tea leaves
are mostly available in island called Java they named the software as JAVA.
Ø Java is not an acronym; it is a trademark of Sun Microsystems.
Ø The Green Project spent all of 1993 and half of 1994 looking for people to buy its
technology, but nobody was ready to buy it.
Ø At this time the World Wide Web (WWW) a part of Internet was growing bigger. The
key to the Web is the browser that translates hypertext page to screen.
Ø Therefore, Sun released the new Java capable Hot java, a however written in java
as a vehicle for downloading and running the applets. Finally the java language
was officially released in middle of 1995.
Ø Sun released the first version of java in early 1996 and it was followed by java 1.02
a couple of months later.
Ø However in this version also Sun missed something to satisfy the IT people, so in
1996 Sun released java 1.1 versions with a seemingly endless stream of
improvements and new libraries, which became a most important aspect in java.
Ø In 1998 Sun Microsystems released the latest version as java1.2 which replaces
the early toy like GUI and graphics toolkits with sophisticated and scalable
versions that come a lot closer to the promise of “Write once, Run anywhere”
than their predecessors.
INet Solv 9
Core Java
Advance Java
v Embedded Sys – Writing the programs and directly installing the program in
the Chips. Ex : TV Remotes
v Wireless App’s – Developing programs for Mobiles, Cell phones, PDA’s etc.,
INet Solv 10
Core Java
Byte Code to
Machine Spark
Code
Executed
JVM
Byte Code
to Pentium
Machine
X . java X . class Code Executed
JVM
Byte Code
to Celeron
Machine
Code
Executed
JVM
INet Solv 11
Core Java
10 1010 11
Spark
10 1010 01
JVM Executed
i add a, b 10 1010 11
C=a+C Pentium
=a+b i load c, a 10 1010 01
10 1010 11 Celeron
10 1010 01
JVM Executed
INet Solv 12
Core Java
IIQ : 3
INet Solv 13
Core Java
Ø Generally when we send any mail to a friend what happens is, it first go to the ISP
Server and next go to the other server and next to other server like that it travels
through several different servers and at last reaches your friend server.
Ø But in the process of traveling the mail through different servers we have one
disadvantage that is the mail send by us can be opened by any of the servers,
therefore we do not have security in Internet.
Ø Some of the problems occurred on internet are as follows:
IIQ : 4
INet Solv 14
Core Java
1. Simple
Name bark
Age bite
Color sleep
Height jump
Object
Class
INet Solv 15
Core Java
class Objects
IIQ : 5
3. Distributed
4. Robust
a) Exception Handling:
o Exception means a run time error.
o Exception happens because of some problems in computer memory i.e. improper
allocation of memory
o Exception handling means preventing abnormal termination of a program.
o In Java exception can be handled.
b) Memory Management:
o Generally it is the responsibility of programmer to allocate or deallocate the
memory.
o But in Java the programmer need not allocate or deallocate memory because it
is done by JVM.
o In JVM memory allocation is done by Class loader Sub System.
o In JVM memory deallocation is done by JVM’s Garbage Collector ( which
destroys the variable which are not used ).
INet Solv 16
Core Java
5. Secure
Ø Java is secure because it enables the construction of virus free and tamper free.
6. Architecture Neutral
7. Portability
8. Interpreted
Fig : JVM
INet Solv 17
Core Java
9. Performance
Ø Along with interpreter there will be JIT compiler which enhance the speed of
computer
Native
Method Heap Java Stack PC Method
Area Register Stack
INet Solv 18
Core Java
Ø Run time data AreaThis memory is divided into 5 parts. They are:
1. Method Area :
o The class code and the methods code is stored on method area.
2. Heap :
o Objects are created on heap.
o i.e. memory for objects are created by heap memory.
3. Java Stacks:
o These are the areas where java methods are executed.
o Memories for methods are allocated.
o For example if we have 4 methods, java stack is divided into 4 frames and on
each
frame a separate method is executed.
4. PC Register:
o Register means memory location.
o These register contains memory address of the next instructions to be
executed by the processor.
o Machine language memory address is located at PC Register
o Guide the Micro processor where the machine language instructions are
loaded in the PC Register.
Ø Execution Engine
o It contains interpreter and JIT compiler which converts the byte code into
machine language so that processor executes them.
INet Solv 19
Core Java
1.1 print a
1.2 print b
1.3 Repeat the following 10 times by changing values then 1 to 10
1.4 Print a
Ø Step 1 :First the interpreter reads instruction 1.1 print a and converts it into
machine code and gives it to the processor for execution. For this process it takes
minimum 2
seconds.
Ø Step 2: Next the interpreter reads instruction 1.2 print b and converts it into
machine code and gives it to the processor for execution. For this process it takes
minimum 2 seconds.
Ø Step 3: Next the interpreter reads the instruction 1.3 and executes the instruction
1.4 for the first time as per the instruction 1.3 and this process takes 2 seconds
Ø This process (Step 3) repeats for 10 times as per instruction1.3 and it takes
minimum of 2*10 = 20 seconds.
Ø Overall to execute the above byte code the interpreter takes 2+2+20=24 seconds.
Time taken to execute the above byte code using Interpreter + JIT Compiler
Ø Step 1 :First the interpreter reads instruction 1.1 print a and converts it into
machine code and gives it to the processor for execution. For this process it takes
minimum 2
seconds.
Ø Step 2: Next the interpreter reads instruction 1.2 print b and converts it into
machine code and gives it to the processor for execution. For this process it takes
minimum 2 seconds.
Ø Instruction 1.3 is Hot Spot i.e. the bock of code left for JIT Compiler to improve
speed of execution. Therefore then instruction 1.3 is executed by the JIT compiler.
Ø Next instruction 1.4 is read by JIT compiler, first JIT compiler converts the byte
code into machine code and send to processor and this process takes 2 seconds,
secondly this machine code is pushed into memory and the instruction 1.3 is read
and executes for 10 times and this process takes 2 seconds.
Ø Overall to execute the above byte code the interpreter takes 2+2=4seconds and the
JIT compiler takes 2+2=4seconds and totally it takes 8seconds.
Ø Therefore for instructions 1.3 and 1.4 the interpreter takes 20seconds, but the
JIT compiler takes only 4seconds.
INet Solv 20
Core Java
Ø From this we can say that JIT compiler improves the speed of the computer.
10. Multithread
11. Dynamic
Ø We can develop programs in Java which dynamically interact with the user on the
internet
Example: Applets
INet Solv 21
Core Java
2.Multi-line comments :
These comments start with /* and ends with */
Example: /* This is a multi line comment line1
This is a multi line comment line2
This is a multi line comment line3
*/
3. Java documentation comments:
These comments start with /** and ends with */
These comments are useful to create API (Application Programming
Interface) Document.
IIQ : 6
About API
Ø API is a user manual.
Ø Java doc compiler is used to create an API document.
Ø API document does not contain any source code it contains only description of
classes, methods, etc.,
INet Solv 22
Core Java
import java.lang.*;
class first
{
public static void main (String args[ ] )
{
System.out.println (“Welcome to java”);
}
}
Java library
Packages
Class or interfaces
Methods
INet Solv 23
Core Java
Ø It is written as
import java.lang.System
import java.lang.String
Ø But if we need all the classes existed in java.lang package, we should write as
import java.lang.*
IIQ : 7
#include makes a C, C++ compiler to copy the entire header file code into the
C or C++ programs. Therefore the program size increases and thus it wastes the
memory and processor time.
import :
import statement makes JVM to go to the package and executes the code
there itself and substitute the result into the java program. That is JVM does not
copy any code into program.
So import is more efficient than # include.
IIQ : 8
Properties of object
action of methods
}
INet Solv 24
Core Java
Ø In java programming one method is compulsory since JVM starts execution of java
programming from a main method only.
Ø Other methods in the program are called through main method only.
Ø If main method does not exist in the program then JVM does not execute the java
program.
For example:
Class classname
{
main( )
{
method1( )
{
}
method2( )
{
}
}
}
Ø Functions can receive data and can also return data.
Ø Method Parameter : It is a variable that receives a data from outside.
Ø Main method can also receive data from outside i.e. it can receive group of strings
For example :
Ø Here in the above example String args is a method parameter and values passed
to a method are called arguments.
Ø If the method does not return anything i.e. any values then before main we should
write void.
For example :
INet Solv 25
Core Java
Syntax : objname.methodname( );
Ø To avoid these problems we should call main method without any object.
Ø A static method is method that can be called and executed without creating any
object i.e JVM calls .main method without creating any object.
JVM will call static method by classname.main
INet Solv 26
Core Java
IIQ : 9
INet Solv 27
Core Java
INet Solv 28
Core Java
\n New line
\t <tab>
\r <enter>
\b <backslash>
\\ \
\” “ (double Quotes)
\’ ‘ (Single Quotes)
Examples: java.awt
java.io
javax.swing
2) Each word of class names and interface names start with a capital letter.
Examples: String
DataInputStream
ActionListener
3) Method name start with a small letter, then each word start with a capital.
Examples: println( )
readLine( )
getNumberInstance( )
INet Solv 29
Core Java
4) Variable names also start with a small letter, then each word start with a
capital.
Examples: age
empName
employeeNetSal
5) Constants should be written using all capital letters.
Example: PI
MAX_VLAUE
FONT.BOLD
Example: public
void
import
INet Solv 30
Core Java
o This package contains primary classes and interfaces essential for java
program ie. It consists of wrapper classes, strings, threads etc.,
o Wrapper classes are used to create objects.
o String is a class.
o Thread means executing a group of statements.
2. java.util
o This package contains useful classes and interfaces like stack, linked list,
hashtable, arrays etc.,
3. java.io
4. java.awt
5. javax.swing
6. java.net
7. java.applet
o Applets are java programs which come from a internet server into a client
and get executed on the client machine.
8. java.sql
o This package helps to connect to database like oracle and utilize them in java.
INet Solv 31
Core Java
Ø Example :
1. byte rno = 10;
Here 10 is the literal i.e. a constant which is directly stored in variable.
2. long x = 150L (Here JVM allots exactly 8 bytes)
3. long x = 150 ( Here JVM allots only 2 bytes instead of 8 bytes )
INet Solv 32
Core Java
IIQ : 10
Q: What is the difference between float and double ?
R: Float can represent upto 7 digits after decimal point.
Double can represent upto 15 digits accurately after decimal point.
IIQ : 11
Q: What is UNICODE?
R: It is standard to include the alphabet of all human languages into the
character set of
java. Unicode system uses 2 bytes to represent each character.
INet Solv 33
Core Java
a + b operand
operator
1. Arithmetic Operators + - * / %
2. Unary Operators - ++ --
3. Assignment Operators = += -= *= /= %=
4. Relational Operators < <= > >= == !=
5. Logical Operators && || !
6. Boolean Operators & ! |
7. Bitwise Operators Bitwise complement ~
Bitwise and &
Bitwise or |
Bitwise xor ^
Bitwise leftshift <<
Bitwise rightshift >>
Bitwise zero fill shift >>>
8. Ternary Operators ? :
(conditional operator)
9. Dot / Member Operator .
10. Instance of Operator Instance of operator
11. New Operator new
INet Solv 34
Core Java
1. Arithmetic Operators
Let a= 13 , b=5
+ Addition a+b 18
- Substraction a-b 8
* Multiplication a*b 65
/ Division a/b 2.6
% Modules a%b 3
(Remainder )
2. Unary Operators
INet Solv 35
Core Java
if int x=1(post-decr)
System.out.println (x); 1
System.out.println (x--); 1
System.out.println (x); 0
a) Unary minus ( - )
Negates means converting positive value to negative value and vice-versa.
b) Increment Operator ( ++ )
This operator increases the value of a variable by 1.
Here we have 2 types of increment operators.
i) Pre-Incrementation : Writing ++ before the variable is called pre
incrementation (++x). Here incrementation is done first and other
operations are done next. So top priority is for incrementation.
ii) Post-Incrementation : Writing ++ after a variable is called post
incrementation (x++). Here the other operations are done first then
the incrementation is performed.
IIQ : 12 (Satyam)
++a * a++
R: 8 * 8 = 64
++a * a++
Execution 8 8 8 *9
Prints 8 * 8 = 64
INet Solv 36
Core Java
c) Decrement Operator( - - ) :.
3. Assignment Operator :
4. Relational Operators
INet Solv 37
Core Java
SIMPLE CONDITIONS
if(x<y)
statement1
else
statement2
if(x<=y)
statement1
else
statement2
if(x>y)
statement1
else
statement2
if(x>=y)
statement1
else
statement2
if(x==y)
statement1
else
statement2
if(x!=y)
statement1
else
statement2
5. Logical Operators
COMPOUND
CONDITIONS
if (x>1 || x>2 || x>3)
Statement1
else
Statement2
if (x>1 || x>2 || x>3)
Statement1
else
Statement2
if (x>1 || x>2 || x>3)
Statement1
else
Statement2
INet Solv 38
Core Java
6. Boolean Operators
Ø These operators act upon Boolean variables and return Boolean type result.
a) & Boolean and
b) | Boolean or
c) ! Boolean Not
Ø Example :
Boolean a, b;
a= true;
b= false;
EXAMPLE RESULT
a&b false
a|b True
A&a true
B |b false
!a false
!b true
7. Bitwise operators
2 45
2 22 - 1 45 = 00 101101
2 11 - 0
2 5- 1
2 2- 1 Since we need 8 bits the remaining first 2 bits are 0’s
2 1- 0
0- 1
Ø Convert 0010 1101 into decimal: Multiply each digit by the powers of 2 and
take the sum of the products.
0010 1101 = 45
0 0 1 0 1 1 0 1
27 26 25 24 23 22 21 20
0 0 32 0 8 4 0 1 = 45
INet Solv 39
Core Java
x = 0000 1010
y = 0000 1011
---------------
0000 1010 = 10
-------------
X Y X&Y
0 0 0
0 1 0
1 0 0
1 1 1
INet Solv 40
Core Java
c) Bitwise or ( | )
x = 0000 1010
y = 0000 1011
---------------
0000 1011 = 11
-------------
X Y X|Y
0 0 0
0 1 1
1 0 1
1 1 1
d) Bitwise Xor ( ^ )
x = 0000 1010
y = 0000 1011
---------------
0000 0001 = 1
-------------
X Y X^Y
0 0 0
0 1 1
1 0 1
1 1 0
INet Solv 41
Core Java
x=?
0 0 0 0 1 0 1 0 = 10
0 0 1 0 1 0 0 0 = 40
x=?
0 0 0 0 1 0 1 0 = 10
0 0 0 0 0 0 1 0 = 2
Sign bits
INet Solv 42
Core Java
v Right shift operators shifts the bits towards right, a specified no .of
times and preserves the sign bits i.e. 0 for +ve and 1 for –ve
numbers.
If we use right shift ( >> ) of 2if we use zero fill right shift( >>> ) of 2
a)
0 1 0 0 1 0
0 0 1 0 0 1
b) a)
1 0 1 1 0 1
1 0 0 0 0 0
IIQ : 13
Q: What is the difference between right shift (>>) and zero fill right shift (>>>) ?
R: Right shift (>>) operator shifts the bits towards right, a specified no .of times
preserves the sign bits i.e. 0 for +ve and 1 for –ve numbers.
Zero fill right shift (>>>) operator is also shifts the bits towards right but does
not preserve the sign bit. It always fill zero in the sign bit.
class Bits
{
public static void main(String args[ ])
{
byte x=10, y=11;
System.out.println(“ ~x = ” + (~x) );
System.out.println(“ x&y = ” + (x&y) );
System.out.println(“ x|y = ” + (x|y) );
INet Solv 43
Core Java
Output :
~x = -11
x&y = 10
x|y = 11
x^y = 1
x<<2 = 40
x>>2 = 2
x>>>2= 2
9. Dot operator ( . )
Ø Example : 1. package.class
Java.io.BufferedReader
2. class.var
obj.var
System.out
e.id
3. class.method( ); obj.method( );
math.sqrt( ); br.read( );
INet Solv 44
Core Java
IIQ : 14
Q: write a program to add two numbers without using arithmetic and unary
operators. (Hint : You can use Bitwise operators)?
R:
INet Solv 45
Core Java
1. if else statement
2. do while loop
3. while loop
4. for loop
5. for each loop
6. switch
7. break
8. continue statement
9. return statement
1. if else statement:
if(condition)
Ø Syntax : statement1;
[else statement2;]
Ø Example :
class Demo
{
public static void main(String args[ ])
{
int x ;
x = 5;
if(x==0)
System.out.println(“It is Zero”);
else if(x>0)
System.out.println(x + “is positive “);
else System.out.println(x + “is vegative”);
}
}
Output :
5 is positive
INet Solv 46
Core Java
1st Method
if (condition 1)
statement 1;
else if (condition 2 );
statement 2;
else if (condition 3 );
statement 3;
2nd Method
if (condition 1)
if (condition 2)
if (condition 3)
statement 1;
else statement 2;
else statement 3;
else statement 4;
2. do …. while loop:
do{
statements;
Ø Syntax :
}
while(condition);
Ø do means executes the statements inside the loop then go to while and check the
condition if the condition is true it again go to do statement, if the condition is
false it will go to next instruction of the program.
Ø Example :
//Program to generate numbers from 1 to 10
class Demo1
{
public static void main(String args[ ])
{
int n=1;
do {
System.out.println(n);
n++;
INet Solv 47
Core Java
} while(n<=10);
}
}
Output :
1
2
3
4
5
6
7
8
9
10
3. while loop:
Ø This loop is useful to repeatedly execute stmts as long as the condition is true.
while (condition)
Ø Syntax: {
statements;
}
Ø Example :
class Demo2
{
public static void main(String args[ ])
{
int i=2;
while (i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Output :
2
4
6
8
10
INet Solv 48
Core Java
IIQ : 15
4. for loop:
for(exp1;exp2;exp3)
{
Ø Syntax: statements;
}
Ø For loop is more suitable to execute the statement for a fixed no.of times
Ø exp1 is called INITIALIZATION expression
exp2 is called CONDITIONAL expression
exp3 is called MODIFYING expression
class Demo
{
public static void main(String args[ ])
{
for ( int i=1; i<10; i++ )
{
System.out.println(i);
}
}
}
INet Solv 49
Core Java
Ø Example 3:
class Demo
{
public static void main(String args[ ])
{
int i=1;
for ( ;i<=10; )//removing expression 1 and expression 3
{
System.out.println(i);
i++;
}
}
}
Ø Example 4:
class Demo
{
public static void main(String args[ ])
{
int i=1;
for(; ; ) //removing expressions 1,2 and 3, it is called
infinite loop
{
System.out.println(i);
i++;
if(i>10) break;
}
}
}
Output of above 4 examples :
1
2
3
4
5
6
7
8
9
INet Solv 50
Core Java
class Demo
{
public static void main(String args[ ])
{
int arr[ ] = {10, 22, 45, 56, 99 };
for (int x : arr)
System.out.println(x);
}
}
INet Solv 51
Core Java
6. switch statement:
Ø This statement is useful to execute a particular task depending upon the value
of a variable.
Ø It is mainly used in menu-driven programs.
switch(variable)
{
Case value1:stmt1;
Case value2:stmt2;
Ø Syntax: Case value3:stmt3;
.
.
.
Case value n:stmtn;
[default : default-stmts]
}
Ø When none of the above statements are executed then the default statements are
executed.
Ø Example:
class Demo
{
public static void main(String args[ ])
{
char ch=’g’;
switch(ch)
{
case ‘r’ :
System.out.println(“Red”);
break;
case ‘g’ :
System.out.println(“Green”);
break;
case ‘b’ :
System.out.println(“Blue”);
break;
case ‘w’ :
System.out.println(“White”);
break;
default :
System.out.println(“No color”);
INet Solv 52
Core Java
break;
}
}
}
Output :
Green
switch(ch);
{
case ‘r’ :
case ‘R’:
System.out.println(“Red”);
break;
case ‘g’ :
case ‘G’ :
System.out.println(“Green”);
break;
case ‘b’ :
case ‘B’:
System.out.println(“Blue”);
break;
case ‘w’ :
case ‘W’:
System.out.println(“White”);
break;
default :
System.out.println(“No color”);
break;
}
Ø In switch(ch) we can use characters, integers but we cannot use words, float,
double.
INet Solv 53
Core Java
7. break statement:
IIQ : 16
Ø Example:
class Demo
{
public static void main(String args[ ])
{
boolean x = true;
b1:
{
b2:
{
b3:
{
System.out.println(“Block 3”);
if(x==true) break b2;
}
System.out.println(“Block 2”);
}
System.out.println(“Block 1”);
}
System.out.println(“Out of all”);
}
}
INet Solv 54
Core Java
Output :
Block 3
Block 1
Out of all
8. continue statement:
class Demo
{
public static void main(String args[ ])
{
for( int i=10; i>=1; i--)
{
if(i>5) continue
System.out.println(i);
}
}
}
Output : 5,4,3,2,1.
9. return statement :
class Demo
{
public static void main(String args[ ])
{
int num = 1;
System.out.println(“Before Return”);
if(num ==1 ) return;
INet Solv 55
Core Java
System.out.println(“After Return”);
}
}
Output :
Before Return
IIQ : 17
1.
Print Odd numbers upto 100.
2.
Test whether a number is even or odd.
*3.
Test whether a number is prime or not.
4.
Display a Multiplication Table.
5.
Display the stars in the following form
*
* *
* * *
* * * *
INet Solv 56
Core Java
IIQ : 18
INet Solv 57
Core Java
- - - - - - - - - - - - - - - -BufferedReader
----------------------------
InputStreamReader
Keyboard
import java.io.*;
class Input
{
public static void main(String args[ ])throws IOException
{
//create BufferedReader object
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter a char :”);
char ch = (char)br.read( );
System.out.println(“You Entered “ + ch);
}
}
Output :
Enter a class A
You entered A
Problem 1
Ø read( ) may or may not read in some conditions due to loss of memory then it may
give some errors at runtime and this error is called Exception. Therefore we can
say that read( ) gives an IOException
Ø Solution : Then we have to throws an IOException. Therefore without handling
the IOException just we have to throw it.
INet Solv 58
Core Java
Problem 2
Ø While reading read( ) takes as character but while returning it gives as an integer.
Therefore again we have to convert that integer into character.
Ø Solution : Hence we have to do Type Casting i.e. converting one data type into
another data type.
Ø Example : Char ch = (char)br.read( );
Cast Operator
Ø From keyboard we can give different types of data as follows :
1. String
2. integer
3. float
4. double
INet Solv 59
Core Java
import java.io.*;
class Employee
{
public static void main(String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print(“Enter id = “);
int id = Integer.parseInt(br.readLine( ));
Output :
Enter id = 007
Enter Sex = M
Enter Name = James Bond
Id is 007
Sex is M
Name is James Bond
INet Solv 60
Core Java
Ø To avoid this problem we write the statement br.skip(2); which skips two
character and goes to next line.
6. Accept two numbers from keyboard and find the result of their addition,
subtraction,
multiplication and division.
*7. Print even numbers between m and n.
8. Print Fibonacci Series upto n.
9. Print Prime number series upto n.
INet Solv 61
Core Java
21. ARRRAYS
Ø An array represents a group of elements of same data type.
Ø Arrays make programming easy.
Ø We have 2 types of arrays ;
or 2
0 1 2 3 4 3
Ø In single dimensional arrays we have only one index and it starts with 0.
Ø Creating a one dimensional array
v One dimensional array will have only one index, it represents the position
number of the element in array.
2) we can create an empty array using new operator and later on store the
elements into
the array.
INet Solv 62
Core Java
marks[ 0 ] = 50;
marks[ 1 ] = 51;
marks[ 2 ] = 52;
marks[ 3 ] = 53;
marks[ 4 ] = 54;
Syntax: array.length
Example : marks.length
import java.io.*;
class Arr
{
public static void main(String args[ ]) throws IOException
{
//To accept data from keyboard
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in) );
System.out.print(“ How many subjects”);
int n = Integer.parseInt (br.readLine( ) );
INet Solv 63
Core Java
System.out.println(marks[ i ]);
tot = tot + marks[ i ];
}
System.out.println(“Total marks: “ + tot );
//Percentage
float percent=(float)tot/n;
System.out.println(“Percentage :” + percent);
}
}
Output :
1) we can declare a two dimensional array and directly initialize it with elements.
v Examples :
int marks[ ][ ] = { { 50, 51, 52, 53, 54 }, { 61, 62, 63, 64 }, { 70, 71, 72, 74 } };
float x[ ][ ] = { { 1.1f, 1.2f, 1.3f, 1.4f }, { 2.1f, 2.2f, 2.3f, 2.4f }, { 1.1f, 1.2f, 1.3f, 1.4f } };
INet Solv 64
Core Java
v Here the two indexes are marks[i][j], where i indicates the rows and j indicates
column.
v Two dimensional array is a combination of several one dimensional arrays.
2) we can create a 2D arrays using new operator and allot memory and later store
the element in memory.
v Examples:
int marks[ ][ ] = new int[3][5];
double x[ ][ ] = new double [5][20];
string s[ ][ ] = new string[5][10];
//Program on 2D array reading and display as a matrix.
import java.io.*;
class 2Darr
{
public static void main(String args[ ]) throws IOException
{
//take a 2D array
float x[ ][ ] = { { 1.1f, 1.2f, 1.3f, 1.4f },
{ 2.1f, 2.2f, 2.3f, 2.4f },
{ 1.1f, 1.2f, 1.3f, 1.4f } };
float tot =0.0f;
INet Solv 65
Core Java
C:\>java Arr 10 20 30
Command Line
class Arr
{
public static void main(String args[ ])
{
int n = args.length;
System.out.println(“No.of args =” + n);
System.out.println(“The arguments are”);
for (int i=0; i<n; i++)
System.out.println(args[i]);
}
}
Output :
INet Solv 66
Core Java
//Program to add two numbers while giving the numbers from command
line.
class Arr1
{
public static void main(String args[ ])
{
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double res = a+b;
System.out.println(“Sum = “ + res);
}
}
Output :
INet Solv 67
Core Java
23. STRINGS
Ø A String represents a group of characters.
Ø In C, C++ strings means character array.
Ø In java string means an object of string class.
Ø In C, C++ the statement
Char [ ] = “Krishna/0”;
is valid and /0 indicates the end of the string.
Ø But in java the above statement is not valid.
v JVM internally creates string class objects and in that object, Krishna is stored
and the
object is referenced by name.
2) We can allot memory for a string object using new operator and store a string
there.
Output : H A I
INet Solv 68
Core Java
2. int length( )
Ø Output : 6
INet Solv 69
Core Java
String s1 = “Satish”;
char x = charAt(int 3);
Ø Output : i
Ø It returns a positive value if the calling string comes before str in dictionary order,
it returns a positive value if the string comes after str, it returns 0 if the strings
are equal.
Ø Example :
S1= “Boy”, s2 = “Box”;
int n = s1.compareTo(s2);
if s1 == s2, n ==0
if s1 > s2, n > 0
if s1 < s2, n < 0
Ø startsWith method tests with, that the main string is having a substring or not.
Ø It returns true if the calling string starts with prefix.
Ø It is case sensitive.
INet Solv 70
Core Java
Ø It returns a new string that is obtained by replacing all characters oldchar in the
string with new char.
Ø It returns a new string consisting of all characters from beginIndex until the end of
the strings.
Ø It returns a new string consisting of all characters from beginIndex until the
endIndex(exclusive).
INet Solv 71
Core Java
System.out.println(“s3 = “ + s3);
//join s1 and s2
System.out.println(“s1 joined with s2 = “ + s1.concat(s2) );
class Test
{
public static void main(String args[ ])
{
String s1 = “Hello”;
String s2 = new String(“Hello”);
if(s1==s2)
System.out.println(“Both the strings are same”);
INet Solv 72
Core Java
else
System.out.println(“Both the strings are not same”);
}
}
IIQ : 19
Ø String s1=”Hello”;
vWhen the above statement executes JVM creates an object (“Hello”) in memory
and a hash code (reference number) is generated uniquely for an object.
vHere s1 is reference variable and let us assume the reference number be 125.
Reference Number
125 Hello
S1
Memory
vWhen the above statement executes JVM creates an object (“Hello”) in memory
and a hash code (reference number) is generated uniquely for an object.
vHere s1 is reference variable and let us assume the reference number be 130.
Reference Number
130 Hello
S2
Memory
INet Solv 73
Core Java
Ø if(s1==s2)
vWhen the above statement executes JVM compares the reference numbers of
each object.
vSince both the reference numbers are not same the output we get is “Both the
strings are not same”.
Reference Number
125 Hello
Compared S2 Memory
But not same
Reference Number
130
Hello
S2
Memory
vTherefore by using == symbol only the reference numbers are compared but not
the contents of the objects.
Ø Therefore to overcome the above problem we use .equals( ) which compares the
contents of an object.
IIQ : 20
class Test
{
public static void main(String args[ ])
{
String s1 = “Hello”;
String s2 = “Hello”; //Modified statement from above program
if(s1==s2)
System.out.println(“Both the strings are same”);
INet Solv 74
Core Java
else
System.out.println(“Both the strings are not same”);
}
}
Ø Since we are not using the new operator the output we get is “Both the strings
are same”.
Ø String s1=”Hello”;
vWhen the above statement executes JVM creates an object (“Hello”) in memory
and a hash code (reference number) is generated uniquely for an object.
vHere s1 is reference variable and let us assume the reference number be 125.
Reference Number
Hello
125
S1
IIQ : 21
Ø String s1=”Hello”;
vWhen the above statement executes JVM goes to string constant pool, it check
whether same object “Hello” is available in string construct pool.
vIf the same object “Hello” is available it creates another reference of same object
with same number.
INet Solv 75
Core Java
Reference Number
S1
Hello
125
S2
Ø if(s1==s2)
Reference Number
Hello
125
S1
Compared
And equal
125 String Constant Pool
S2
IIQ : 22
R: In first statement JVM goes to string constant pool and checks the pool. If
same object is available in the string constant pool, JVM does not creates
another object, it creates another reference to the same object. If the same
object is not available in the pool then only JVM creates another object and
stores it in the pool.
In the second statement new operator is used JVM creates a new object
without checking in the string constant pool.
INet Solv 76
Core Java
S1
One
Ø String s2=”Two”;
S2
Two
Ø s1=s1+s2;
One
S1
Two
S2
OneTwo
Ø Here s1 and s2 are concatenated into OneTwo in another new object, but it is
stored in a reference variable s1 only. And the previous object One is deleted in s1.
Ø Stringbuffer class objects are mutable.
INet Solv 77
Core Java
26. java.lang.StringBuffer
1. StringBuffer append(x)
4. String reverse( )
5. String toString( )
6.int length( )
IIQ : 23
import java.io.*;
class Full
{
public static void main(String args[ ] )throws IOException
{
//To accept data from keyboard.
INet Solv 78
Core Java
}
}
Output :
INet Solv 79
Core Java
IIQ : 24
IIQ : 25
2. In procedural approach when the code size exceeds 10,000 lines and before
reaching 1,00,000 lines at a particular point the programmer loose control on the
code. So this approach is not suitable to develop bigger and complex projects. So we
need a new approach for developing bigger and complex projects.
INet Solv 80
Core Java
1. Object / Class :
Raju Object
Variables
Properties
Methods
Actions
Ø A class represents a group of names which specifies properties and actions for the
object.
Ø A class is a model or blueprint for creating the objects.
Ø A class does not exists physically whereas an object exists physically.
Ø For example : House is an object and Plan is a class.
Ø An object is an instance of a class.
Ø Objects are created from class.
Ø Objects cannot exists without a class whereas class can exist without any object.
Ø When we create an object of a class, JVM internally creates a memory in Heap
memory.
INet Solv 81
Core Java
2. Encapsulation :
3. Abstraction :
4. Inheritance :
5. Polymorphism :
Ø Polymorphism word has come from Greek words. Poly means Many and Morph
means forms.
Ø If something exists in many forms, then it is polymorphism.
Ø If a method performs different tasks ,then it is polymorphism.
6. Message Passing :
IIQ : 26
OBPL follow all the features of OOPs except Inheritance. Example Javascript
and VBScript.
INet Solv 82
Core Java
class person
{
//Properties – Instance Variables
String name;
int age;
//Actions – Methods
void talk( )
{
System.out.println(“Hello I am“ + name);
System.out.println(“My age is “ + age);
}
}
class Demo
{
public static void main(String args[ ])
{
person p1 = new person( );
System.out.println(p1.hashcode( ));
p1.talk( );
}
}
Output :
Hello I am Null
My age is 0
IIQ : 27
Ø First, a class with a name person is written and instance variable are declared
like name of string data type and age of integer data type and a method talk( ) is
also written which it simply displays the name and age.
Ø Next a class with main method is written. When the statement person p1= new
person( ); is executed JVM creates an object p1 of person class. And p1 is called
as Reference Variable or hash code. This Hash Code is same for all objects in case
of Strings.
Ø By using p1 we can refer to variables (name, age) and methods (talk( )), but
programmers generally refers only to methods.
INet Solv 83
Core Java
Hello I am Null
My age is 0
Ø Since the instance variables are not initialized by the programmer, the java
compiler adds some code to the class internally and stores default values into
instance variables. Therefore we get the output as above i.e Null is a default value
of String and 0 is default value of integer.
Ø Some of the default values of different data types are as follows;
INet Solv 84
Core Java
Ø Example :
class person
{
String name;
int age;
void talk( )
{
System.out.println(“Hello I am“ + name);
System.out.println(“My age is “ + age);
}
}
class Demo
{
public static void main(String args[ ])
{
person p1 = new person( );
p1.name = “Satish”; //Initailizing variable name using
reference p1
p1.age = 24; //Initializing variable age using reference p1
p1.talk( );
}
}
Output :
Hello I am Satish
My age is 24
Ø But in this type of initialization there is no security for data because any of the
programmer can modify the data.
Ø To provide security to the data the variables are declared as Private, then the data
is not available to other classes.
Ø Example
private String name;
private int age;
Access Specifier : It is a keyword that specifies how to read or access the members of
a class or a class itself. We have 4 types of access specifiers:
1. PRIVATE : Private members of a class are not available outside the class.
It has no security for data.
2. PUBLIC : Public members of a class are available anywhere outside the class.
INet Solv 85
Core Java
TYPE 2 : We can initialize the instance variables directly within the class.
Ø Example :
class person
{
String name = “Satish”; //initializing the var’s directly within the
class
int age = 24; //initializing the var’s directly within the class
void talk( )
{
System.out.println(“Hello I am“ + name);
System.out.println(“My age is “ + age);
}
}
class Demo
{
public static void main(String args[ ])
{
person p1 = new person( );
p1.talk( );
}
}
Output :
Hello I am Satish
My age is 24
INet Solv 86
Core Java
Output:
IIQ : 28
Ø Example:
class person
{
private String name;
private int age;
//default constructor
person( )
{
name = “Satish”;
age = 24;
}
//parameterized constructor
person(String n, int a)
{
name = n;
age = a;
}
INet Solv 87
Core Java
//Action
public void talk( )
{
System.out.println(“Hello I am“ + name);
System.out.println(“My age is “ + age);
}
}
class Demo
{
public static void main(String args[ ])
{
person p1 = new person(“Shreya”, 23 );
p1.talk( );
Hello I am Shreya
My age is 23
Hello I am Iliana
My age is 21
Hello I am Trisha
My age is 24
Ø Writing 2 or more constructors with the same name but with a difference in
parameter is called overloading.
Ø Therefore a constructor can be overloaded.
Ø If any constructor is not written in a class, the java compiler adds default
constructor with default values in the class.
Exercise of OOP’s
16. Create a class with student details like id, name, address, marks…. And create 2
objects to it.
INet Solv 88
Core Java
30. Methods
Ø A method represents a group of statements which performs a task.
Ø A method has two parts :
2. Method Body:
INet Solv 89
Core Java
class Sample
{
//instance variables
double d1, d2;
//parameterized constructor
Sample(double a, double b)
{
d1 = a;
d2 = b;
}
class Demo
{
public static void main(String args[ ])
{
Sample s = new Sample(10, 12.5);
s.sum(10, 12.5); or double res = s.sum(10, 12.5);
System.out.println(“Result = “ + res);
}
}
Output :
Sum is = 22.5
Result = 22.5
INet Solv 90
Core Java
1. Static Method:
Ø A static method is a method that does not act upon instance variables.
Ø Static methods can be called using
Objectname.method( ); and classname.method( );
Ø Syntax : obj.method( );
class Sample
{
//instance variables
double d1, d2;
static int i = 50; //if i is not static, then prg gives an
error that non static variable cannot be
referenced form a static context
//parameterized constructor
Sample(double a, double b)
{
d1 = a;
d2 = b;
}
INet Solv 91
Core Java
}
}
class Demo
{
public static void main(String args[ ])
{
Sample s = new Sample(100, 152.5);
double res = s.sum(100, 15.5);
System.out.println("Result = " + res);
}
}
Output :
i=50
Result = 115.s
IIQ : 29
I 100
10 20 30
i i i
10 20 30
obj 1 obj 2 obj 3 i i i
Output:
10 20 30 obj 1 obj 2 obj 3
Output:
10 20 30
INet Solv 92
Core Java
Ø Static variables, static methods, static blocks are stored on method area.
Ø Ex : Static
{
statements;
}
Ø In an program JVM executes first of all static block then only any other blocks are
executed including main method.
Ø class Test
class Test class Test
{ { {
static( ) static( ) static( )
{
{ {
Sys.out.println(“Static block”);
} Sys.out.println(“Static Sys.out.println(“Static
public static void main(String block”); block”);
args[ ]) } System.exit(0);
{ }
Sys.out.println(“StaticMethod”); } }
}
} Output: Output:
Static Block Static Block
Output:
Error : main method is not
Static Block
Static Method existed
2. Instance Method:
Ø Instance methods are the methods which act upon the instance variables. This
means instance methods act upon the object of the class.
Ø To call the instance methods we can use obj.method( );
class person
{
//instance variables
String name;
int age;
char sex;
//parameterized constructor
person(String name, int age, char sex)
INet Solv 93
Core Java
{
this.name = name;
this.age = age;
this.sex = sex;
}
//Accessor Method
void display( )
{
System.out.println(“Name = “ + name);
System.out.println(“Age = “ + age);
System.out.println(“Sex = “ + sex);
}
//Mutator Method
person modify(person obj)
{
obj.name = “Laxmi”;
--obj.age;
obj.sex = ‘F’;
return obj;
}
}
class Demo
{
public static void main(String args[ ])
{
p1.display( ); //1.5
}
}
P1 Srinu Laxmi
1.1 25 24
Output : M F
Name = Srinu
Age = 25 obj
Sex = M 1.3
Name = Laxmi
Age = 24
Sex = F 1.5
P2
Name = Laxmi
Age = 24
INet Solv 94
Core Java
Sex = F
class Demo
{
public static void main(String args[ ])
{
person p1 = new person(“Srinu”, 25, ‘M’);//1.1
p1.display( ); //1.2
person p2 = p2.modify(new person (“Venkat”, 26 , ‘M’)); //1.3
p2.display( ); //1.4
p1.display( ); //1.5
}
}
obj
P2
class Sample
{
int n;
Sample( )
{
//this( ); //calling the present class default constructor
INet Solv 95
Core Java
Sample(int n)
{
this.n = n; //present class instance variable
}
void display( )
{
System.out.println(“n=” + n);
}
}
class ThisDemo
{
public static void main(String args[ ])
{
Sample s = new Sample(100); (or) Sample s = new Sample( );
s.display( );
}
}
Output :
n=100
Ø In C++ call by value means a variable is passed by value and call by reference
means a variable address is passed by reference.
Ø But in Java there is no pass by reference since we do not use pointers in Java,
we have only pass by value.
3. Factory Methods :
INet Solv 96
Core Java
IIQ : 30
3. Using newInstance( )
Ex : class c = class.forName(“Employee”);
Employee obj = c.newInstance( );
4. Using Cloning
class Circle
{
public static void main(String args[ ])
{
//instance variables
final double PI = 3.14159; //final means constant/fixed i.e PI is
constant
or
INet Solv 97
Core Java
Output :
Area = 754.7669975
Formatted Area = 754.7669975
Or
Area = 720.75
Formatted Area = 720.7500000
IIQ : 31
import java.io.*;
class Arr
{
int arr[ ];
int r,c;
INet Solv 98
Core Java
//constructor
Arr(int r, int c)
{
this.r = r;
this.c = c;
arr = new int[r][c];
}
INet Solv 99
Core Java
class MatixSum
{
public static void main(String args[ ])
{
Arr obj1 = new Arr(3,3);
Arr obj2 = new Arr(3,3);
int x[ ][ ], y[ ][ ], z[ ][ ];
//Result
obj2.putArray(z);
}
}
Output :
Exercise of Methods
Latest IIQ : 32
X 10
b Y 20
Z 30
Object a c
Object b
Object c
//Program to demonstrate how one object members are
available to another object.
class One
{
int x;
Two t; //t is the reference of another class Two
//constructor One
One(Two t)
{
this.t = t; x 10
x = 10;
} t
} object t
class Two
{
int y;
Two( )
{
y = 20;
}
void display( )
{
System.out.println(“y=” + y);
}
}
class Relate
{
public static void main(String args[ ])
{
Two t = new Two( );
One o = new One(t);
o.display( );
}
}
Output:
x = 10
y = 20
Inner class
bal
bal rate
rate
this$0
class InnerDemo
{
public static void main(String args[ ])
{
BankAcct account = new BankAcct(10000);
account.start(5.6);
}
}
Output :
Interest = 560.0
Balance = 10560.0
Exercise of Inner class
20. Create a student class with id and name. In that class create an inner class
“Dob”with dd-mm-yy. Create 2 objects and store 2 students date of birth details.
Find no.of different in the date of births of students.
34. INHERITANCE
Ø Creating new classes from existing class is called Inheritance.
Ø extends is a keyword used in Inheritance.
Ø The class which is already is already existed is called as Super class.
Ø The class which is newly produced is called sub class.
Ø In inheritance all the members of super class are automatically available to the
subclass. The reason is when an object to subclass is created it contains a copy of
the super class.
IIQ : 33
return addr;
}
void setsal(int sal) // Mutator method
{
this.sal = sal;
}
int getsal( ) // Accessor method
{
return sal;
}
}
Output :
Ø From above program we can say that all the members of super class are available
to subclass.
class One
{
One( )
{
System.out.println(“One”);
}
}
class Two
{
Two( )
{
System.out.println(“Two”);
}
}
class const
{
public static void main(string args[ ])
{
Two t = new Two[ ];
}
}
Output :
Two
Ø Next, we may any problem : What happens if the super class contains
Parameterized constructor.
Ø To solve the above problem we use a keyword called super.
Ø Super is a keyword that refers to super class from a subclass. It means super can
refer to super class instance variables, methods and constructors.
One(int x)
{
this.x = x;
}
void show( )
{
System.out.println(“x=” + x);
}
}
class Two extends One
{
int x; //variable x of class Two, different from class One
Two(int a, int b)
{
super(a); //Stores ‘a’ value in ‘x’ of constructor One in
super class
x = b;
}
void show( )
{
System.out.println(“x= “ + x);
super.show( ); //refers to method in super class
System.out.println(super.x); //refers to variable in super class
}
}
class const
{
public static void main(String args[ ])
{
Two t = new Two(10, 22);
t.show( );
}
}
Output :
X =22
X = 10
10
Exercise of Inheritance
21. Create a rectangle class from square class and display the area of both the
rectangle and square.
35. POLYMORPHISM
Ø Polymorphism word has comes from Greek words. Poly means Many and
Morphos means forms.
Ø The ability to exists in different forms is called Polymorphism.
Ø In programming if the same method performs different tasks it is called
polymorphism.
Ø Polymorphism is of 2 types :
1. Static Polymorphism.
2. Dynamic Ploymorphism.
1. Dynamic Polymorphism :
class Sample
{
void add(int a, int b) //Method Signature 1
{
System.out.println(“Sum of two no’s = “ + (a+b) );
}
void add(int a, int b, int c) //Method Signature 2
{
System.out.println(“Sum of three no’s = “ + (a+b+c) );
}
}
class Poly
{
public static void main(String args[ ])
{
Sample s = new Sample( );
s.add(10,22); //Method signature 1 is called through object s
}
}
Output :
Ø If in the above program instead of s.add(10, 22) statement, s.add(10, 20, 30)
statement is given then the output will be 60. Since Method signature 2 with 3
parameters is called.
IIQ : 34
Ø Method Overloading :Writing two or more methods with the name but with a
difference in method signatures is called Method Overloading.
Ø In Method Overloading JVM identifies the correct method by observing the
difference in the method signatures.
Ø Some of the differences in method signatures are as following :
Ø Method OverRiding : Writing two or more methods with same name and same
method signatures are called Method OverRiding.
Ø Subclass methods always over rides the Super class method.
Ø In Method Over riding JVM decides which method to be executed depending upon
the class of the object which is used to call the method.
Ø Method Over riding using instance method is an example of Dynamic
Polymorphism.
class One
{
void calculate(double x)
{
System.out.println(“Square Value = “ + (x*x) );
}
}
class Two
{
void calculate(double x)
{
System.out.println(“Square Root = “ + math.sqrt(x));
}
}
class Poly
{
public static void main(String args[ ])
{
Two t = new Two( );
t.calculate(16);
}
}
Output :
Square Root = 4
Ø Since the object in class Poly is created for class Two, the calculate method in
class Two is executed and the result is 4
Ø But if the code is changed as below :
public static void main(String args[ ])
{
One o = new One( );
t.calculate(5);
}
then the result will be “Square Value = 25” Since the object in class Poly is
created for
class One, the calculate method in class One is executed.
IIQ : 35
2. Static Polymorphism :
Ø final method :
IIQ : 36
Ø We can convert a primitive data type into another primitive data type using
casting.
Ø We can convert an advanced data type into another advanced data type using
casting.
Ø We cannot convert a primitive type into advanced type or vice versa using casting.
For this we can use WRAPPER class method.
a) Widening:
Ø Converting a lower data type into a higher data type is called Widening.
Ø Lower data type use less memory and represents less no. of digits.
Ø Higher data type use high memory and represents more no. of digits.
Ex 1 :
char ch = ‘A’;
int n = ch; //It is invalid statement since integer cannot be assigned to character,
so we
use type casting.
char ch =’A’;
int n = (int) ch; //It is widening
Ex 2 :
b) Narrowing :
Ø Converting a higher data type into a lower data type is called Narrowing.
Ø Narrowing is unsafe because we may lose some digits. Ex Output : 12
Ex 1 :
int n = 66;
char ch = n; //It is invalid statement since character cannot be assigned to integer,
so we use
type casting.
int n = 66;
char ch = (char) n; //It is narrowing explicitly
Ex 2 :
double d = 12.9876l;
int n = (int) d; //It is narrowing explicitly
Ø To convert a referenced type into another referenced type, those classes should
belong to same Inheritance chain( superclass, subclass, sub subclass,etc.)
class One
{
void show1( )
{
System.out.println(“Super class”);
}
}
class Two
{
void show2( )
{
System.out.println(“Sub class”);
}
}
class Cast
{
public static void main(String args[ ])
{
// case 1- Super class reference to refer to Super class obj
One o;
o = new One( ); //Type casting is not required, since LHS data
type (o)
//and RHS data type (One) are same.
o.show1( ); //It is called
}
}
Output :
Super class
Reason for above output : If Super class reference is used to refer to super class
object then the programmer can access only super class methods.
class Cast
{
public static void main(String args[ ])
{
Output :
Super class
Sub class
Reason for above output : If Sub class reference is used to refer to Sub class object
then the programmer can access both the Super class and Sub class methods.
class Cast
{
public static void main(String args[ ])
{
// case 3- Super class reference to refer to Sub class obj
One o;
o = (One)new Two( ); //Type casting(widening) is required,
since LHS
data type(o) and RHS data type (Two) are
not same.
o.show1( ); //It is called
o.show2( ); //It is not called
}
}
Output :
Super class
Reason for above output :
In Widening only super class members are available to programmers.
In Widening sub class methods are not available, unless they over ride super class.
IIQ : 37
Q: Difference between Generalization and Specialization data types?
R:
Generalization :
Moving back from Sub class to Super class is called Generalization.
Converting a Sub class type into a super class type is called up casting or
Widening.
Special;ization :
Coming down from Super class to Sub class is called Specialization.
Converting a Super class type into a Sub class type is called down casting or
Narrowing.
Super Class
Fruits
Generalization Specialization
class Cast
{
public static void main(String args[ ])
{
// case - Sub class reference to refer to Super class obj
Two t;
t = (Two)One( ); //Type casting(Narrowing) is required, since
//LHS data type(t) and RHS data type (One) are not same.
t.show1( ); //It is not called
t.show2( ); //It is not called
}
}
Output :
Error: Error message
Reason for above output : Narrowing using Super class object cannot access Super
class member or Sub class members also Therefore this case is useless.
But we can change the code and can be written as below :
class Cast
{
public static void main(String args[ ])
{
One o;
o = (one)new Two( );
Two t = (Two)o;
t.show1( ); //It is called
t.show2( ); //It is called
}
}
Output :
Reason for above output : Narrowing using Sub class object can access all the
members of Super class and also Sub classes.
Common( )
{ abstract class
statements;
}
calculate( )
{
Method body should be empty
}
Method body is
Calculate( ) Calculate( ) Calculate( ) Written in Sub
{ { {
a + b; a - b; a / b;
classes
} } }
Objects of subclasses
Contains both
Common( ) Common( ) Common( ) common and
calculate
method
calculate( ) calculate( ) calculate( )
IIQ : 38
Q: How can you make the programmer to implement only the method of your
class ?
R: By writing an abstract class or an Interface
//Store regno
Car(int r)
{
regno = r;
}
//every car will have a fuel tank. The mechanism to fill the fuel is
//also same for all cars.
void fillTank( )
{
System.out.println(“Take car key and fill the Tank”);
}
//every car will have steering , but different cars will have
//different steering mechanism.
abstract void steering( int direction);
//every car will have breaks. But different cars have different
//breaking mechanism.
abstract void breaking(int force);
}
//Using a Car
class UseCar
{
public static void main(String args[ ])
{
//create objects to Maruthi and Santro
Maruthi m = new Maruthi(6666);
Santro s = new Santro(1111);
//Use Maruthi
c.fillTank( );
c.steering(2);
c.breaking(200);
}
}
Output : if c = m
Output : if c = s
22. Create an abstract class “Parent” with property details and an abstract method
“calculate ( )”. Now derive “Son” class from parent class and calculate the son’s
property by implementing calculate( ) method.
38. INTERFACES
Ø For example, a software company has given a project to you, to develop software
or program in Java to make a connection to any type of database existed in the
world.
Ø For this purpose if we make use of Classes we have a problem.
Ø Let us see the problem :
void disconnect( )
{
code to disconnet MySql
} Not
Connected
Abstract method
Code to
void connect ( ); Connect
Oracle Oracle
Database
A Connected
Code to
Connect
P Sybase Sybase
Database
Connected
void close( ); I Code to
Connect
MySql MySql
Database
Connected
method 1( )
method 2( )
method 3( )
method 4( )
method 5( ) Abstract methods (without body)
Objects
//Interface
interface MyInter
{
void connect( ); // public abstract
}
//Main method
class Database
{
public static void main(String args[ ])
{
//Accept database name from user through command line argument &
//store it into an object ‘c’
class c = class.forName(args[0]);
//Create another object to that class whose name is in object c
MyInter mi = (MyInter)c.newInstance( );
//Call connect method using the reference mi
mi.connect( );
} Oracle DB
}
c
Output :
IIQ : 39
IIQ : 40
Object class instance var ( 4B )
Q: class A O
{
int x; //4bytes X class A var in class B ( 4B )
}
class B extends A
{
int x; //4bytes X class B var ( 4B )
}
R: >8 Bytes of memory, It takes 4 bytes for variable x of class B and other 4
bytes for variable x of class A which is in class B. Another 4 bytes of memory for
the “object class instance variable” existed in class A (Since object is a Super
class for all classes in java).
1. Single Inheritance
2. Multiple Inheritance
1. Single Inheritance : Producing Sub classes from a single Super class is called
Single Inheritance.
Ex : 1. 2.
A A
B B C D
class A class A
class B extends A class B extends A
class C extends A
class D extends A
2. Multiple Inheritance : Deriving Subclasses from more than One super class is
called Multiple Inheritance.
Ex: 1. 2.
A B A B C
C
D E
class A class A
class B class B
class C extends A,B //invalid class C
class D extends A,B,C //invalid
class E extends A,B,C //invalid
IIQ : 41
interface Father
{
int PROP1 = 500000; //public static final by default
float HT1 = 6.2 F;
}
interface Mother
{
int PROP2 = 300000;
float HT2 = 5.0 F;
}
//Multiple Inheritance
class Child implements Father, Mother
{
void property( )
{
System.out.println(“Childs property = “ + PROP1+PORP2);
}
void height( )
{
System.out.println(“Childs Height = “ + (HT1+HT2/) );
}
}
//Main method
class Multi
{
public static void main(String args[ ])
{
child ch = new child( );
ch.property( );
ch.height( );
}
}
Output :
Exercise of Interface
40. PACKAGES
Ø A packages represents a sub directory that contains a group of classes and
interfaces.
Ex :
import java.io. * ;
io
Sub Directory Sub Sub Directory All classes and methods of
Sub Directory io
java
Package
Advantages of Packages :
1. Packages hide the classes and interfaces, so accidental deletion is not possible.
2. The classes of one package are Isolated(separated) from the classes of another
package.
It means same class name can be used in 2 different packages.
this.d2 = d2;
}
Directory of C:\psk\pack
Output : 25.5
Ø Since the source code is not available to the user, he does not know whether to
pass parameters or not whenever calling a method.
Ø To know where the parameters should be passed or where not the user should
refer to API document.
package pack;
public class Subtraction
{
public static double Sub(double a, double b)
{
return(a-b);
}
}
C:\psk\javac –d . Subtraction.java
C:\psk\cd pack
C:\psk\pack\dir
Volume in drive C is SATISH
Volume serial Number is 1472-0B9D
Directory of C:\psk\pack
Ø The above added Subtraction class to package pack should be used (called) in
package pack by rewriting the class Use as following :
Output :
25.5
Result = 35.0
import pack.Addition;
import pack.Subtraction;
class Use
{
public static void main(String args[ ])
{
Addition obj = new Addition(10, 15.5);
obj.Sum( );
Output :
25.5
Result = 35.0
import pack.*;
class Use
{
public static void main(String args[ ])
{
Addition obj = new Addition(10, 15.5);
obj.Sum( );
Output :
Step 1 : Java compiler searches for package in .jar format in the following directory.
C:\program files\Java\Jre1.5.0\lib\ext
IIQ : 42
Step 2 : Java compiler takes the current directory as the package and searches for the
.class files in the current directory ( c:\psk ).
Step 3 : Java compiler searches for the package pack in present directory C:\psk.
If the pack Directory is removed from C:\psk and moved to any other folder in another
drive (let us assume it is moved to D:\Zoom . Then go to step 4.
Step 4 : Finally java compiler searches for the package directory in a the class path.
If it is failed, then set the class path.
Zoom is the directory which contains the pack directory. %classpath% is not required,
but by writing this the actual available class path is not disturb.
package pack;
public interface MyDate
{
void showDate( ); //public and abstract by default
}
Compile as following
C:\psk>javac –d . MyDate.java
C:\psk>cd pack
C:\psk\pack>dir
Volume in drive C is SATISH
Volume serial Number is 1472-0B9D
Directory of C:\psk\pack
Compile as following
C:\psk>javac –d . MyDateImpl.java
C:\psk>cd pack
C:\psk\pack>dir
Volume in drive C is SATISH
Volume serial Number is 1472-0B9D
Directory of C:\psk\pack
First Method
import pack.MyDateImpl;
class Use
{
public static void main(String args[ ])
{
MyDateImpl obj = new MyDateImpl( );
obj.showDate( );
}
}
In the above program by using “obj” only MyDateImpl methods can be accessed.
import pack.MyDateImpl;
class Use extends MyDateImpl //using inheritance
{
public static void main(String args[ ])
{
Use obj = new Use( );
obj.showDate( );
}
}
In the above program “obj” refers to the object of subclass, therefore super class
methods can also be accessed.
This method is Most Effective method than First Method. But Output is same for
both the methods.
Compile as following
C:\psk>javac Use.java
C:\psk>java Use
Thu Jul 26 07:36:34 PDT 2007
package inet.solv;
Compile as following
C:\psk>javac –d . Sample.java
C:\psk>cd inet
C:\psk\inet>cd solv
C:\psk\inet>solv>dir
Volume in drive C is SATISH
Volume serial Number is 1472-0B9D
Directory of C:\psk\pack
import inet.solv.Sample;
class Use
{
public static void main(String args[ ])
{
Sample s = new Sample( );
s.show( );
}
}
Compile as following
C:\psk>javac Use.java
C:\psk>java Use
Hello Student
C:\psk>del Sample*.*
C:\psk>javac Use.java
C:psk>java Use
Hello Student
Ø Move the inet directory from C:\psk to any other drive say D:\abc
Ø Then again compile the program Use as C:\psk>javac Use.java
Ø You will be getting an error like
C:\psk>set classpath=D:\abc;.;%classpath%
C:\psk>javac Use.java
C:\psk>java Use
Hello Student
1. private
2. public
3. protected
4. default
not
public available
available
not
available
available protected
not
available available
default
Package 1 package 2
Private :
Ø Private members of a class are not available in other classes of same package.
Ø The scope of private specifier is class Scope
Pubic :
Ø Public members of a class are accessible any where in other classes of the same
package or another package.
Ø The scope of public specifier is global scope.
Protected :
Ø Protected members are available to the classes of the same package but not in
another package.
Default :
Ø Default members of a class are accessible in the classes of same package but not
in another package.
Ø The scope of default specifier is package Scope (within that package only it is
accessible).
Note : If C is a sub class of Class A, protected members are always available in the
sub class either in the same package or in another package.
Compile it as following
C:\psk>javac –d . A.java
Volume in drive C is SATISH
Volume serial Number is 1472-0B9D
Directory of C:\psk\pack
07/25/2007 11:35 PM <DIR> .
07/25/2007 11:35 PM <DIR> ..
07/25/2007 11:35 PM 271 A .class
1 File(s) 271 bytes
2 Dir(s) 384,724,992 bytes free
package Same
import same.A
public class B
{
A obj = new A( );
System.out.println(obj a);
System.out.println(obj b);
System.out.println(obj c);
System.out.println(obj d);
}
save it as B.java in C:\psk
Compile it as following
C:\psk>javac –d . B.java
Error : a is not accessible
package another
import same A
Public class C
{
public static void main(String args[ ] )
{
C obj = new C( );
System.out.println(obj a);
System.out.println(obj b);
System.out.println(obj c);
System.out.println(obj d);
}
}
3 Errrors :
package another
import same A
public class C extend A
{
public static void main(String args[ ] )
{
C obj = new C( );
A obj = new A( )
System.out.println(obj a);
System.out.println(obj b);
System.out.println(obj c);
System.out.println(obj d);
}
}
2 Errrors :
Exercise of packages
24. Create an “Figure” class with 2 instance variables x,y in a package called
“geopack:. Then import that package into rectangle class, to find the area of the
Rectangle(your rectangle class extends figure). Similarly derive circle class and
trinangle class and display
25. Create a package with 3 classes to calculate square root value, power value and
factorial values. Import this package into a main program and display these values.
C:\psk\pool>javadoc abc.java
Generating constant-values.html...
Open My Computer go to C:\psk\pool you will find an API document named “java.doc”
43. ERROR’S
Ø An error in a software is called a Bug.
Ø Removing the errors is called Debugging.
Ø There are 3 types of errors :
Ø These are the errors which are detected by the java compiler at the time of
compilation.
Ø These errors are due to “Bad Syntax” or “Improper Grammer”.
Ø Java compiler can display only 1st 100 errors in a program.
Ø These errors can be detected by “Desk Checking” (Checking line by line or word
by word).
Ø These errors occur at run time and are detected by the JVM.
Ø These errors are due to insufficient of memory or inefficiency of the processor to
execute the statement.
Ø Run Time errors are also called exception.
3. Logical Error :
IIQ : 43
The exception which are detected at run time by the JVM are called
unchecked exceptions.
java.lang
Throwable
Exceptions
Errors
RunTime All
All errors Exception Exception
UnChecked Exceptions
IIQ : 44
IIQ : 45
Q: What is throwable?
R: Throwable is a class that represents all exceptions and errors in java.
class Ex
{
Public static void main(String args[ ])
{
System.out.println(“Open files “);
int n = args.length;
System.out.println(“n=” + n);
int a = 45\n;
System.out.println(“a=” + a);
System.out.println(“Close files”);
}
}
C:\javac Ex.java
C:\java Ex 44 55 66
Open files
n = 3
a =
close files
1. The programming should write all the statements where they may be an exception,
inside
“try” block.
Syntax : try
{
Statements;
}
When there is an exception is try block JVM does not abnormally terminate the
program. JVM
stores exception details in an exception stack and then jumps into catch block.
2. The programmer should display exception display and also any other messages to
the use in
catch block.
3. The programmer should close all files and database inside finally block.
Syntax : finally
{
Statements;
}
class Ex
{
public static void main(“Open files”)
{
try
{
finally
{
System.out.println(“Close files”);
}
}
}
C:\javac Ex.java
C:\java Ex
Open files
n= 0
java.lang.arithematic Exception by Zero
please type data while running this program.
Close files
Ø We can insert another exception in the existing program and these are called
multiple exceptions.
Ø Multiple exceptions can be handled by writing multiple catch blocks.
Ø A try block can be followed by several several catch blocks.
Ø A catch block does not exists without a try block.
Ø But a try block exists without a catch block.
Ø Finally block is always executed irrespective of the exception.
Ø Catch block is executed only when there is an exception.
class Ex
{
public static void main(“Open files”)
{
try
{
try
{
int b[ ] = {10, 11, 12};
b[50] = 100;
}
catch
{
aie.printStackTrace( );
System.out.println(“pls see that the array is with the
range”);
}
finally
{
System.out.println(“Close files”);
}
}
}
Ø In the first stage the programmer will try to write the program to perform a
particular task.
Ø In the second stage only the programmers try to handle the exception in a
program. And perform try, catch and throw in the program.
Ø
//Not handling the exception
class Sample
{
void accept( )
{
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println(“Enter your name = “);
String name = br.readLine( ); //reads string from keyboard
System.out.println(“Hello” + name);
}
}
class Ex
{
public static void main(String args[ ])
{
Sample s = new Sample( );
s.accept( );
}
}
C:\javac Ex.java
C:\java Ex
Unexception exception
Ø To avoid the above problem we should use throws statement after accept( ) and
public static void main(String args[ ])
Ø Since we know the exception is from Input and Output we write as throws
IOException.
Ø To handle any type of exceptions we can simple throws Exception.
Ø Therefore the above program can be written as follows :
class Ex
{
public static void main(String args[ ]) throws IOException
{
Sample s = new Sample( );
s.accept( );
}
}
C:\javac Ex.java
C:\java Ex Satish
Hello Satish
catch(NullPointerException ne)
{
ne.printStackTrace( );
}
}
Output :
Inside demo( )
Java.lang.NullPointerException
IIQ : 45
Uses of throw
1. Throw is used in software testing to test whether a program is handling all the
excepted as claimed by the programmer.
2. Throw is used to create user defined exceptions and throw than out to handle them.
Ex:
1. Arithematic Exception.
2. ArrayIndexOutOfBoundException.
3. StringIndexOutOfBoundException.
4. IOException.
5. NumberFormatException.
6. FileNotFoundException.
7. NoSuchMethodException.
8. ClassNotFoundException.
9. NullPointerException. //if object is not existed
10.InterruptedException.
Ø The user can also create an exception which are called user defined exception.
MyException( ){ }
MyException(String args[ ])
{
super(str);
}
Output :
26. Create an program that accepts 2 members as input from command line. Your
program should throw RunTime Exception, if exactly 2 numbers are not given.
27. Create a student class with some students names and their marks in maths. Rise
your own exception like “UnReasonableMarks” if any student gets more than 100
marks in maths.
Application 1 Application 2
Objects
Ø Because of the above reasons, primitive data types should be converted into
objects.
Ø To convert a primitive data type into object form we need Wrapper Classes.
Ø A wrapper class wraps(contains) a primitive data type within its objects.
Ø Example :
Wrapper class
Character
I. Character Class :
Ø The character class wraps a value of the primitive type ‘char’ in an object. An
object of type Character a single field whose type is char.
Constructor
1. Character(char ch)
Methods
1. char charValue( )
Output: A
Output : True
2. char x = ‘A’;
Character.isDigit(x)
Output : True
import java.io.*;
class CharTest
{
public static void main(String args[ ]) throws IOException
{
//To accept data from keyboard
BufferedReader br = new BufferedReader( new
InputStreamReader(System.in));
System.out.println(“Enter a character = “);
char ch =(char)br.read( );
II . Byte Class
The Byte class wraps a value of primitive type byte in an object. An object of type Byte
contains a single filed whose type is byte.
Constructors
1. Byte(byte num)
2. Byte(String str)
Methods
2. int compareTo(Byte b)
Returns the byte equivalent of the number contained in the string specified by ‘str’.
4. string toString( )
Return a string that contains the decimal equivalent of the invoking object.
Return a byte object that contains the value specified by the string ‘str’.
import java.io.*;
class Bytes
{
public static void main(String args[ ]) throws IOException
{
//To accept the data from keyboard.
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter byte no =”);
String str = br.readLine( );
Constructors
1. Integer(int num)
2. Integer(String str)
Methods
1. int intValue( )
Compares the numerical value of the invoking object with that of “obj”. Returns 0, -ve
or +ve value.
Output : 123
Ex: String s =”Hello”;
int n = Integer.parseInt(s);
Output : NumberFormatException
4. String toString( )
import java.io.*;
class Convert
{
public static void main(String args[ ]) throws IOException
{
//To accept data from keyword
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter an integer = “);
String str = br.readLine( );
str = Interger.toOctalString(n);
System.out.println(“In Octal =” + str);
str = Integer.toHexString(n);
System.out.println(“In Hexa = “ + str);
}
}
Constructors
1. Float(float num)
2. Float(String str)
Methods
1. float floatValue( )
2. double doubleValue( )
3. int compareTo(Float f)
Compares the numerical value of the invoking object with that of ‘f’. Return 0, -ve or
+ve values.
4. static float parseFloat(String str) throws NumberFormatException
5. String toString( )
Returns the Float object with the value specified by String str.
V. Double Class
The Double class wraps a value of primitive type ‘double’ in an object. An object of
type Double contains a single field whose type is double.
Constructors
3. Double(double num)
4. Double(String str)
Methods
1. double doubleValue( )
2. float floatValue( )
3. int compareTo(Double d)
Compares the numerical value of the invoking object with that of ‘d’. Return 0, -ve or
+ve values.
5. String toString( )
Returns the Double object with the value specified by String str.
Methods
if(n = = 0)
System.exit(0);
Thread.sleep(3300);
}
}
}
Exercise of Wrapper classes (java.lang)
28. Create a class Calculate with static methods to find factorial value, power value,
square root value and sine value using static methods.
java.util
Objects
Collection class
Collection Object
Collection Object
Ø A collection class or a container class is a class whose object can store a group of
other objects.
Ø All collection classes are defined in java.util package.
IIQ : 47
create again 8KB of memory which is wasted. Therefore a collection object stores
only references of other objects.
Objects
Collection object
containing the
References of objects
Ø All the classes of collection frame work have been divide into 3 groups
Ø Collections cannot store primitive data types it can store only objects.
IIQ : 48
1. Stack
1. To create a stack
boolean b = st.empty( );
st.push(element);
int i = st.search(element);
import java.lang.*;
import java.util.*;
class StackDemo
{
static void stpush(stack st, int a)
{
st.push(new Integer(a));
}
InputStreamReader(System.in));
Stack st = new stack( );
int element, pos;
int choice = 0;
//Menu
while(choice<4)
{
System.out.println(“STACK OPERATIONS”);
System.out.println(“1. PUSH ELEMENT”);
System.out.println(“2. POP ELEMENT”);
System.out.println(“3. PEEP ELEMENT”);
System.out.println(“4. EXIT”);
System.out.println(“YOUR CHOICE”);
case 1:
System.out.println(“Enter Element=”);
element = Integer.parseInt(br.readLine( ));
stpush(st, element);
break;
case 2 :
stpop(st);
break;
case 3:
System.ou.println(Enter Element =”);
element = Integer.parseInt(br.readLine( )(;
pos = stsearch(st, element);
if(pos = = 1)
System.out.println((st,element);
else
System.out.println(“Element found at position is “ + pos);
break;
default :
return;
}
System.out.println(“Stack =” + st);
}
}
C:\psk>javac StackDemo.java
Note : StackDemo.java uses unchecked or unsafe operation
2. Linked List
A Linked List represents a set of nodes such that each node contains two fields :
Data field and Link fields.
The data field stores data and the Link field stores the reference to the next node.
Data Link
Node
1. To create a linked list
ll.add(element);
ll.removeFirst( );
ll.set(2, NEWelement);
import java.io.*;
import java.util.*;
class LLDemo
{
public static void main(String args[ ]) throws IOException
{
//Create an empty linked list
//Variables
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String element;
int pos, choice = 0;
//Menu
while(choice<4)
{
System.out.println(“LINKED LIST OPERATIONS”);
System.out.println(“1. Insert Element”);
System.out.println(“2. Remove Element”);
System.out.println(“3. Change Element”);
System.out.println(“4. Exit ”);
System.out.println(“Enter Your Choice = ”);
case 2 :
System.out.println(“Enter position”);
pos = Integer.parseInt(br.readLine( ));
ll.remove(pos);
break;
case 3 :
System.out.println(“Enter new element”);
element = br.readLine( );
System.out.println(“Enter position”);
pos = Integer.parseInt(br.readLine( ));
ll.set(pos, element);
break;
default :
return;
}
System.out.println(“List =” + ll);
}
}
}
Ø To retrieve the elements from a collection object we can use any one of the
following interface :
1. Iterator
2. List Iterator
3. Enumerator
3. Arrays
Arrays class contains method to handle any array.
Array.sort(arr);
This sorts the elements of “arr” starting from start till “end-1” elements.
Array.binarySearch(arr, element);
This searches for elements in the array “arr” and returns its position. If the
“element” is not found, it returns a negative value.
Arrays.equals(arr1, arr2);
This returns true if arr1 and arr2 are same else it returns false.
import java.io.*;
import java.util.*;
class Arr1
{
public static void main(String args[ ])throws IOException
{
BufferedReader br = new BufferedReader( new
InputStreamReader(System.in));
System.out.println(“How many elements?”);
int n = Integer.parseInt(br.readLine( ));
display(arr);
if(pos < 0)
System.out.println(“Element not found”);
else
System.out.println(“Element found at positon” + (pos+1));
}
49. CLONING
Ø In general cloning is a technology to obtain exact of a plant, a bird, an animal or a
human being.
Ø But in JAVA, creating bit wise exact copy of an existing object is called cloning in
Java.
Ø There are 2 types of cloning :
1. Shallow Cloning : Here any modifications to the cloned object will modify the
original object.
2. Deep Cloning : Here any modifications to the cloned object will not effect the
original object.
Original
Object
Performed some
operations
Modified Modified
Object Cloning Object
Employee(int i, String n)
{
id = i;
name = n;
}
void display( )
{
System.out.println(“ID =” + id);
System.out.println(“Name = “ + name);
}
class CloneDemo
{
public static void main(String args[ ]) throws
CloneNotSupportedException
{
System.out.println(“Before Cloning”);
Employee e1 = new Employee (10, “Satish”);
e1.display( );
Output :
Before Cloning
id = 10
Name = Satish
After Cloning
id = 10
Name = Satish
Cloneable interface doesn’t contains any methods or members. But the above
statement is needed since it indicates that this clas(Employee) objects are cloneable. It
is called Tagging or Marking Interface.
It is a method to clone object of Employee class and returns Employee class object
only.
Clone method belongs to Object class.
As we know Object class is a super class of all classes, so we use super keyword.
super.class( ) is object type, so convert it into Employee type by “Type Casting”.
Employee(int i, String n)
{
id = i;
name = n;
}
void display( )
{
System.out.println(“ID =” + id);
System.out.println(“Name = “ + name);
}
class CloneDemo
{
public static void main(String args[ ]) throws
CloneNotSupportedException
{
System.out.println(“Before Cloning”);
Employee e1 = new Employee (10, “Satish”);
e1.display( );
Output :
Before Cloning
id = 10
Name = Satish
After Cloning
id = 10
Name = Satish
2Q: Why C & C++ are not used to develop software’s for internet?
R: C, C++ programs are System Dependent because they can be executed only on the computer sys
where they have been developed. Therefore s/w for internet cannot be developed through C, C++.
3Q: What is the difference between .exe file and .class file ?
R: 1) .exe file contains machine language instructions understandable to the micro processor.
.class file contains byte code instructions understandable to JVM
#include makes a C, C++ compiler to copy the entire header file code into the C or C++ programs. So
the program size increases and thus it wastes the memory and processor time.
import :
import statement makes JVM to go to the package and executes the code there itself and substitute the
result into the java program. That is JVM does not copy any code into program.
So import is more efficient than # include.
++a * a++
R: 8 * 8 = 64
13Q: What is the difference between right shift (>>) and zero fill right shift (>>>) ?
R: Right shift (>>) operator shifts the bits towards right, a specified no .of times preserves the sign bits
i.e. 0 for +ve and 1 for –ve numbers.
Zero fill right shift (>>>) operator is also shifts the bits towards right but does not preserve the sign
bit. It always fill zero in the sign bit.
14Q: write a program to add two numbers without using arithmetic and unary operators.
(Hint : You can use Bitwise operators)?
R:
System.out.println(“Hello”);
System.err : It is used to display the error message on the monitor.
System.out.println(“Error Message”);
20Q: What is the difference between == and equals( ) while comparing strings?
R: == operator compare references of the string objects and hence it gives unreliable result.
equals( ) compare the contents of the string objects hence to compare two strings we should use
equal( ) method.
R: In first statement JVM goes to string constant pool and checks the pool. If same object is available
is string constant pool, JVM does not create another object, it creates another reference to the same object.
If the same object is not available in the pool then only JVM creates another object and stores it in the
pool.
In the second statement new operator is used JVM creates a new object without checking in the
string constant pool.
26Q: What is the difference between Object Oriented Programming Language’s(OOPL) and
Object Based Programming Languages(OBPL)?
R: OOPL follow all the features of OOPs. Example : C++, Java, Simula 67, Samlltalk.
From simula 67 and smalltalk only Java has been developed.
From C++ only syntax are taken inot Java.
OBPL follow all the features of OOPs except Inheritance. Example Javascript and
VBScript.
28Q: What is the main functional difference between Default Constructor and Parameterized
Constructor?
R: In Default Constructor each object has same data.
In Parameterized Constructor each object has different data.
29Q: What is the difference between instance variable and static variable ?
R: Instance Variable is a variable whose separate copy is available to the objects of the class. So if an
instance variable of an object is modified it will not effect the other objects.
Static variable is a variable whose single copy in memory is shared by all the object.
If static variable is modified it effects all the objects.
3. Using newInstance( )
Ex : class c = class.forName(“Employee”);
Employee obj = c.newInstance( );
In the above example first statement indicates that, forName method creates an object to a class
Class and in that object it stores the classname. And in the second statement indicates that, using the
object c(of first statement) a newInstance of Employee is created in obj.
5. Using Cloning
Latest IIQ : 32
Method Over Riding is used to provide a different implementation for the same
feature. Method OverRiding is Code Replacement.
Special;ization :
Coming down from Super class to Sub class is called Specialization.
Converting a Super class type into a Sub class type is called down casting or Narrowing.
38Q: How can you make the programmer to implement only the method of your class ?
R: By writing an abstract class or an Interface
40Q: class A
{
int x; //4bytes
}
class B extends A
{
int x; //4bytes
}
How much memory is occupied by class B’s object ?
a) 4B b) 8B c) >8 d) <8
R: >8 Bytes of memory, It takes 4 bytes for variable x of class B and other 4 bytes for variable x of class
A which is
in class B. Another 4 bytes of memory for the “object class instance variable” existed in class A (Since
object is a
Super class for all classes in java).