Sunteți pe pagina 1din 183

Core Java

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

Ø Network: Interconnection of computers is called Networks.


Ø For any communication in computer system we need 3 things.
1. Software
2. Hardware
3. Protocol

Ø 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

Other info Data Other info


Fig: Format of a Frame
v The mostly used protocol is TCP / IP
v TCP / IP: It is a combination of different protocols, therefore it is called TCP
/IP protocol suite.

INet Solv 1
Core Java

v Client: It is a machine which sends a request for some service.


v Server: It is a machine which provides services to client.
v A network is also called a Client Server Model.
v Advantage of Network is Resource Sharing.
v Resource Sharing : It means Sharing memory, sharing data, sharing
software, sharing hardware, sharing processor etc.,
v Dumb Terminal: A client without CPU.

IIQ: 1

Q: What is Hand Shaking Mechanism?


R: Two computers establishing a connection, communication with each other
& finally disconnecting from each other. (Decides when to send/receive data )

Ø In 1969 Department of Defence (DoD) a U.S military Organization has 4


computers. The Org made a thought to connect these 4 computers in a network.
These four computers are connected using Cables. It was the first network made,
and it is called as ARPANET (Advanced Research Project Agency Network).

Comp 1

Comp 4 Comp 2

Comp 3

Fig: ARPANET the first Network build

Ø 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.,

Ø Internet: It is a network of computers existing on the earth.


It is a Global network of networks.
Ø Intranet: It is a network of computers within an Org.
Ø Extranet : It is a network of computers outside an Org connecting it with the
network of another Org.

INet Solv 2
Core Java

Intranet

Extranet

Intranet

Ø ISP: Internet Service Provider is an Org which provides a connection into internet.

v ISP will have a two parts :


1. Gateway
2. Server Name

Satellite

Client 1
64 KBPS

Internet

50 GBPS
Client 2
128 KBPS

ISP Server

INet Solv 3
Core Java

v ISP uses some satellite services.


v ISP can give upto 50GBPS of bandwidth.
v This 50GBPS is divided and distributed to different clients with 64kbps,
128kbps.
v Web Browser: The software that is installed on internet client.
Ex: Internet Explorer, Netscape Navigator, Mozilla FireFox, Moziac.
v Web Server: The software that is installed on internet server.
Ex: Internet Information Server (IIS) for Microsoft Web logic, web sphere, web
dynamic, apache, Jboss.
v Many protocols are used in Internet

1. HTTP - It is used to transfer the web pages.


2. FTP - It is used to upload or download the files.
3. SMTP - It is used to send mails.
4. POP - It is used to receive mails.

Ø Computers can understand only Machine language.


Ø Machine language means all the information is given in the form of bits (0’s or
1’s)
Ø Therefore every program should be converted into machine language which is
understandable by the processors.
Ø Translator: It is a program that converts a computer program into machine
language.

0011010100100010110101011001010111010011
Program Computer

Translator

Ø We have 3 three types of translators:

1. Interpreter: It reads line by line and gives it to the processor to execute.

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.

3. Assembler: It converts assembly language program into machine language.


Here we have instructions like add, sub, mul, div, Inc, dec etc.
Software’s of assembly language are Micro language, Macro
language.

INet Solv 4
Core Java

2. BLOCK DIAGRAM OF COMPILATION OF C PROGRAM

Spark
Not
Executed

X.C X . obj X . exe Pentium

Executed

Celeron

Not
Executed

Ø X.C contains the actual program typed by the programmer


Ø X.Obj contains the equivalent code for your program. That is object code means
only Machine Code.
Ø X.exe is a fully fledge executable file. It includes same machine code as in X.obj
and it also contains the header file code.
Ø A header file is a Pre-defined Function.

INet Solv 5
Core Java

3. HOW C PROGRAM IS EXECUTED?


Ø At first the program is written in the editor and save it as a Filename.C
Ø Let us say the file is saved as add.c and compiled by pressing Alt+F9.
Ø When the C program is compiled for the first time, then the C compiler creates
another file with the same file name but with extension .Obj. That is when ADD.C
is compiled, then ADD.Obj file is created by the C compiler.This add.obj contains
the equivalent machine code for the program in ADD.C. That is the whole program
is converted into machine code except the header file( <stdio.h> )
Ø After this add.exe is created which contains the machine code of ADD.Obj and
also header file code. That is after creating the add.obj the <stdio.h> which is not
converted into machine code is compiled by C compiler , then the C compiler goes
to stdio.h header file existed in the c:\tc\bin… and takes the code of stdio.h and
include it in the place of of stdio.h
Ø Then this add.exe is executed and send to the particular processor.

Spark
Processor

Not
Executed

#include <stdio.h> 110011 <stdio.h> 110011 101101010101100101


main( ) 1110 1110
{ 1100 11 10 Pentium
c=a+b; 1101 01 00 1100 10 10 Processor
printf( c ) ; 1001 10 01 1101 00 00
} 0011 01 1001 10 01
0011 01

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

v A traditional language allows us to write a program and it is compiled using a


compiler which converts the program into machine language which varies for
different machines, depending upon their internal configuration.
v After compilation, we have to execute this compiled program on our machine.
v Since different computers have different machine languages, a program
compiled for one machine cannot be executed on another machine.
v But for putting a program on a web page, the browser should compile the
program each time and then run it.
v Moreover the risk involved is of viruses getting transferred from such a program
during the compilation process.

Ø In JAVA language

v In java, the situation is completely different.


v The compiler has a specialty in that it generates the same machine code for
each and every machine type in the world to be precise.
v The java compiler assumes a theoretically defined machine called Java Virtual
Machine, and compiles code for it and such compiled code is known as byte
code.
v This byte code is machine independent, so that we can run this executable
code in any type of machine across the Internet.
v This results in Java referred to as a Machine-independent or Platform-
independent 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

7. HOW IS JAVA DIVIDED

Java 2 Standard Edition (J2SE)


Core Java

Advance Java

Java 2 Enterprise Edition (J2EE)

Java 2 Micro/Mobile Edition (J2ME)

Ø Java SE - It deals with developing standalone(app’s or programs that can be run


in individual computers) application’s as well as basic networking programs.

Ø Java EE – It deals with developing Enterprise (business solutions) solutions for a


network.

Ø Java ME – It deals with developing Embedded Systems and Wireless


applications.

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

8. BLOCK DIAGRAM OF EXECUTION OF JAVA PROGRAM

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

Ø X.java contains the Source Code.


Ø X.class contains the byte-code of the program.
Ø In Java we have 200 instructions and its each instruction size is of 1byte and
hence it is called ByteCode.
Ø JVM converts byte-code into machine-code.

INet Solv 11
Core Java

9. HOW JAVA PROGRAM IS EXECUTED ?


Ø At first the program is written in the editor and it is saved with an extension .java.
Let the file saved as x.java
Ø Next the java program is compiled by the java compiler which creates a file with an
extension .class with the same name i.e the file x.class is created.
Ø Next this byte-code is send to JVM. JVM understands this byte-code and converts
it into machine code.
Ø And this machine code is send to the processor to execute.
Ø Since JVM is system independent the program is executed in different
processors.

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

X. java X. class JVM Executed

10 1010 11 Celeron

10 1010 01

JVM Executed

INet Solv 12
Core Java

10. ABOUT JVM (Java Virtual Machine)


Ø JVM is a program created by SUN MICRO SYSTEM’S.
Ø JVM is program developed in C language and it is named as java.c
Ø JVM converts byte-code instructions into machine code and sends to the
processors to executed.
Ø JVM know all the 200 instructions.
Ø JVM first checks the memory available in the system, Operating system used and
then it converts the byte-code into machine code so that the byte code is
understandable by that particular processor. Therefore the java program is
executed in any system.
Ø JVM is System Independent i.e it differs form computer to computer.
Ø X. class file is System Independent.

IIQ : 3

Q: 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

2) .exe file is System Dependent


.class file is System Independent

INet Solv 13
Core Java

11. Why Java is suitable for Internet ?


Ø Because java is System Independent.
Java programs are system independent because they do not depend on that
system where they have been developed.

Ø Internet is a public network.

Security problems on Internet

Ø 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:

1. Eaves Dropping : Reading others data illegally.


2. Tampering : Not only reading others data but also modifying the data.
3. Impersonation : A person acting as another person.
4. Virus : It is a harmful program that can damage data, s/w, h/w of a
computer.
Ø To overcome the above problems some of the solutions are as following:
1. Encryption / Decryption for Eaves Dropping.
2. Encryption / Decryption for Tampering.
3. Digital Signatures for Impersonation. Digital Signature is an encrypted file
that contains personal identification information.
4. Since virus can be spread through files with .exe, .com, .doc and image files
like .gif, .jpeg, audio and video files. Generally text files cannot have virus. So
in java we create .class files which are same as text files and hence virus
cannot be loaded.
Ø In C, C++ we use .exe, .com files therefore we have virus.
Ø But by using java major security problems can be eliminated.

IIQ : 4

Q: Why pointers are not available in JAVA ?


R: 1) Pointers leads to confusion for a programmers, even both beginners and
Experience persons face problems.
2) Pointers can easily crash the program. Crashing means terminating the
program abnormally.
3) By using pointers virus and hacking programs can be developed. i.e there is
no security. Because by using pointers we can change the data in memory.

INet Solv 14
Core Java

12. FEATURES OF JAVA


1. Simple
2. Object Oriented Programming Language
3. Distributed
4. Robust
5. Secure
6. Architecture Neutral
7. Portability
8. Interpreted
9. High Performance
10.Multithread
11.Dynamic

1. Simple

Ø Java is Simple Programming Language


Ø Learning and practicing java is easy because of its with C and C++.
Ø Syntactically java looks like C and C++.
Ø No pointers are used in java.

2. Object Oriented Programming Language

Ø Java uses Objects and Classes.


Ø Object- An object is any thing that really exists in this world
An object exists physically
An object is instance of a class
Instance means physically happening
An objects contains properties and perform actions
Variables are used to represent their properties
Action means functions, but functions are called as methods in java
Therefore the object contains variables and methods.
Ø Class – A class is a group name which specifies the behavior of the objects.
A class does not exists physically
A class specifies properties and action
A class also contains variables and methods
A class may or may not contain objects.
A class is a model or plan to create object
Ø Example :

Pinky (Dog) Properties actions

Name bark
Age bite
Color sleep
Height jump
Object
Class

INet Solv 15
Core Java

class Objects

Dog Pinky, Tommy, Julie, browny

Actor Chiru, Venki, Mahesh

Sweet Jammuun, peda, mysorepak

Furniture Chair, bed ,sofa

IIQ : 5

Q: What is the difference between a Function and a Method ?


R: Method
1) In java we have no functions
2) A method is a function written inside a class i.e in java we write functions
only
within a class and called as member function
Function
A function can be written anywhere in the program.

3. Distributed

Ø Information is distributed on various computers in a network.

4. Robust

Ø Robust means strong.


Ø Java programs are Robust i.e they do not crash in the middle.
Ø Java is Robust because of two reasons:

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

Ø Java byte code is not machine dependent.


Ø This byte code can be run on any machine with any processor and with any O.S

7. Portability

Ø Portability means yielding (getting) the same result on any computer.


Ø Java can be run on any computer i.e. everything is defined in Java specification
and nothing is left to O.S.

8. Interpreted

Ø Java programs are compiled to generate the byte code.


Ø This byte code can be downloaded and interpreted by the interpreter in Java.
Ø But in JDK 1.0 we face many problems i.e. here java programs are running very
slow.
Ø To overcome this problem Sun Micro Systems used JIT (Just In Time) compiler.

Interpreter JIT Compiler

Fig : JVM

INet Solv 17
Core Java

9. Performance

Ø Along with interpreter there will be JIT compiler which enhance the speed of
computer

.class files Class loader


Sub System

Native
Method Heap Java Stack PC Method
Area Register Stack

Run Time Data Area

Native Method Native Method


Interface Libraries
Execution Engine

Fig: JVM Architecture

Ø Class Loader Sub System

It does the following tasks:


1. It loads .class file into memory
2. It verifies the byte code instructions i.e. it will check whether all the instructions
are byte code or if any other virus instruction are there. If any virus instruction
exists it will not execute.
3. Then class loader sub system allots necessary memory for the program.

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.

5. Native Method Stack


o These are the places where Native methods( c, c++, functions) are executed.
o Functions written in other language other than Java.
o JVM can execute c, c++ programs.
o But c, c++ programs including some header file code are required which are
stored in
native method libraries and loaded into JVM

Ø Native Method Interface


o It is a program that loads native method libraries ( c, c++ ) into JVM

Ø Execution Engine
o It contains interpreter and JIT compiler which converts the byte code into
machine language so that processor executes them.

Interpreter JIT Compiler


Fig: Execution Engine

INet Solv 19
Core Java

Example : Assume the following byte code

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

Time taken to execute the above byte code using Interpreter

Ø 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.

1.1 print a // 2seconds


1.2 print b // 2seconds
1.3 Repeat the following 10 times by changing values then 1 to 10
1.4 Print a // 2+2+2+2+2+2+2+2+2+2 = 20seconds

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.

1.1 print a // 2seconds


1.2 print b // 2seconds
1.3 Repeat the following 10 times by changing values then 1 to 10 //Hot Spot
1.4 Print a // 4seconds

10. Multithread

Ø Thread means a statement which is under execution.


Ø In Java we can create different threads.
Ø i.e. in java several thousands statements are executed at a time.
Ø Each thread can serve multiple clients.

11. Dynamic

Ø We can develop programs in Java which dynamically interact with the user on the
internet
Example: Applets

INet Solv 21
Core Java

13. FUNDAMENTALS OF JAVA PROGRAMMING


Ø Comments: It describes the features (variables, methods, class) of a program.
It increases the readability (understandability).
Comments are not executable.
Ø Syntax : Syntax means a correct format which is to be followed by the
programmer.
Ø We have 3 types of comments in Java.
1. Single line comments :
These comments start with // and the comment is written in a single
line.
Example: //This is a single comment.

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

Q: What is an API (Application Programming Interface) document ?


R: API document is a HTML file that contains description of all the features of a
software, a product or a technology.

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

Java Program API document

/** class Demo


comments on class comments on class
*/ --------------------------------
class Demo void mymethod( )
{ comments on method
/** --------------------------------
Let us write a first java program using “ Multi line comments “
comments on methods
/* */
voidThis
method(
is )my first java program, to display a simple message.
{ Author : Inetsolv
} Version : v1.0
} Project : pro 112
*/

import java.lang.*;
class first
{
public static void main (String args[ ] )
{
System.out.println (“Welcome to java”);
}
}

Java library

Packages

Class or interfaces

Methods

Ø Generally some classes and methods are used by programmers to write a


program.
Ø For writing the above program we need 2 types of classes like System and String
class.
Ø To make use of these two classes first we should import them and these classes
are available in a package called java.lang.
Ø So first we have to import those particular 2 classes from java.lang package.

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.*

Ø What happens if the statement import java.lang.* is written


By seeing this statement the java converts this statement into byte code then
the java compiler searches where this java.lang package is available.
After getting the java.lang package from the c:\jdk\bin or in some other folder
where the java is stored, it is executed there itself and substitute the result in the
program without copying the whole byte code in the program.

IIQ : 7

Q: What is the difference between #include and import ?


R:
#include :

#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

Q: What is JRE (Java Runtime Environment)?


R: JRE = JVM + Java library

Ø Java library is available in JDK (Java Developer Kit)


Ø JDK = binary file + JRE
Ø Binary files are like java c.exe, java doc.exe
Ø In java we have to write at least one class, since java is purely object oriented.

Syntax : Class classname


{

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 :

main( String args[ ] )

Ø 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 :

void main(String args[ ] )

Ø If the method returns any integer value


For example:

int main(String args[ ] )

Ø If the method returns any character value


For example:

char main(String args[ ] )

INet Solv 25
Core Java

14. How to call a method( ) in java


Ø To call a method we have two steps :

1. Create an object to the class.

Syntax : Classname obj = new classname( );

Example : Sum s = new Sum( );

2. We should call the method

Syntax : objname.methodname( );

But here we have two problems

1. To call main method we need an object


2. But after calling main method only we can create an object

Ø 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

Ø Public means it is available to JVM ie. Outside the program.


If public is not written it is not available to JVM, therefore the statements will not
execute.
For example: public static void main(String args[ ])

Ø Print method is used to display the message on the monitor.


ü Print method belongs to print stream class, to access this method we
should create object of print stream class. But it is not possible to create
an object.
ü To create an object of print stream we use the class System.out
ü System is a class and out is a static variable.

example: System.out.print( “Welcome to Java”)

ü If we call System.out internally it creates print stream.object


ü Println is also a method which displays the result and throws the cursor
into next line.
ü Print displays the result and keeps the cursor in the same line.

Ø Variable represents a memory location to store data with some name.


Ø In java program every statement should terminate with a semicolon (;)
Ø Java is case sensitive programming language.

INet Solv 26
Core Java

Ø Command line arguments :


These are the values passed to main method from command prompt.
These are stored in array args[ ]
Ø = means storage i.e if x=10 it means10 is stored in a variable x
Ø To save the java program : We should save the java program as “filename.java”,
here the double quotes indicates to save the program as it is, i.e. it do not add any
.txt
Ø To compile the program : c:\psk\javac filename.java
Ø To execute the program : c:\psk\java filename
Ø JVM is loaded into memory only when command is runned i.e. JVM does not stay
in memory permanently.

IIQ : 9

Q: What happens if we do not write string args[ ] after main ?


R: JVM will compile the main( ) but it will not run.

Single line Comments


//program to find the sum of 2 numbers
import java.lang.*;
class Sum
{
public static void main(String args[ ])
{
//declaration of variables
int x,y;

// storing values into variables


x=10;
y=25;

// add the values


int z=x+y;

// display the sum


System.out.println( “Sum of two numbers =” + z );
}
}
Output :

Sum of the numbers = 35


System.out.print( “Sumof two no’s =” +z);
Output : Sum of two no’s = 35

System.out.print ( “Sumof two no’s =” + x+y);


Output : Sum of two no’s = 1025

System.out.print( “Sumof two no’s =” + (x+y) );


Output : Sum of two no’s = 35

INet Solv 27
Core Java

Public static void main ( String args[ ] )

Public A static If the method Main method String args[ ]


means it is method is does not can receive is a method
available to method that return data from parameter
JVM ie. can be called anything i.e. if outside i.e. it (variable that
Outside the and executed any values is can receive receives a data
program without not returned group of from outside)
creating any then before strings. and values
object i.e JVM main we passed to a
calls .main should write method are
method without void. called
creating any arguments.
object.

INet Solv 28
Core Java

15. BACKSLASH CODE’S OR ESCAPE SEQUENCE

BACKSLASH CODES MEANING

\n New line

\t <tab>

\r <enter>

\b <backslash>

\\ \

\” “ (double Quotes)

\’ ‘ (Single Quotes)

Ø Since java is case sensitive we should follow some naming conventions.


Ø Naming Conventions are some rules which are followed while writing the names
of classes and methods.

Ø Some of the naming conventions are as follows:

1) Package names in java are written in all small letters.

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

6) All key words should be written in all small letters.

Example: public
void
import

Ø There should be no spaces between the words of classes, methods, variables,


keyword and constants.
Ø java.lang package is imported into every java program by default i.e. there is
no need to write the statement import java.lang.*, but for other packages we
should compulsorily write the statement.

INet Solv 30
Core Java

16. TYPES OF PACKAGES IN JAVA


1. java.lang

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

o This package handles files and input-output related tasks.

4. java.awt

o awt means “abstract window toolkit ”


o This package helps to develop GUI. i.e. it contains of an important sub
packages like
java.awt.event

5. javax.swing

o Here x stands for extended.


o This package helps to develop GUI like java.awt.

6. java.net

o Here net mean network.


o Client Server programming can be done using this package.

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

17. DATA TYPES


Ø A data type represents the type of data stored in memory (variable).

1. Integer Data types.


2. Float Data types.
3. Character Data types.
4. String Data types.
5. Boolean Data types.

1. Integer Data types

Ø These data types represents numbers without any decimal point.


Ø Examples : 10, 25, -50, 0, 100 etc.,

DATA TYPE MEMORY MIN AND MAX VALUES


SIZE
1. byte 1 byte -128 to +127
2. short 2 bytes -32768 to +32767
3. int 4 bytes -2147483648 to +2147483647
4. long 8 bytes -9223372036854775808 to +9223372036854775807

Ø 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 )

2. Float Data types

Ø These data types represent numbers with decimal points.


Ø Examples : 4.5, -0.1 etc.,

DATA TYPE MEMORY MIN AND MAX VALUES


SIZE
1. float 4 byte 1.4e-45 to +3.4e38
2. double 8 bytes 4.9e-324 to -1.8e308

Ø Float means single precision floating pint number.


Example :
float pi = 3.142F; ( JVM allots only 4 bytes )
float pi = 3.142; ( JVM allots 8 bytes since it is treated as double by default )
1.4e-45 is equal to 1.4 * 10-45

INet Solv 32
Core Java

Ø Double means double precision floating point number.


Example : double x = 1.98e8;

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.

3. Character Data types


Ø It represents a single character like a,b,…….z,*,?,etc.,
Ø Examples : char = ‘x’

DATA TYPE MEMORY MIN AND MAX VALUES


SIZE
1. char 2 byte 0 to 65,535

Ø We cannot store integer numbers into char datatype.


Ø Every character is having internally separate number called ASCII numbers(0 to
65,535).
Ø We have 220 characters in keyboard therefore only 1 byte is enough for each char
data type, but java uses 2 bytes for each char data type.
Ø This another 1 byte is used to support all human languages like Chinese,
Japanese, French, etc) and this 1 byte is called as UNICODE.

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.

4. String data types


Ø A string represents a group of characters.
Ø Example :
string name = “ Inetsolv ”;
string str = new string (“ Astring “);
Ø In java strings are string class objects.

5. Boolean Data type


Ø These data types store Boolean values only i.e.True or False
Ø True/False are Boolean literals.
Ø In C, C++
0 represents False
1 represents True
Ø But in java
0 represents 0
true represents true
false represents false

INet Solv 33
Core Java

18. OPERATORS IN JAVA


Ø An operator is a symbol that performs an operation.
Ø Operator acts on operands

a + b operand

operator

Ø If an operator acts on single operand, it is called Unary operator.


Ø If an operator acts on two operands, it is called Binary operator.
Ø If an operator acts on three operands, it is called Unary operator.

NAME OF THE OPERATOR 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

Ø These operators perform basic arithmetic calculations.

Let a= 13 , b=5

OPERATOR MEANING EXAMPLE RESULT

+ 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

Ø These operators act upon a single operand.


Ø This operator negates the value of a variable.

OPERATOR MEANING EXAMPLE RESULT

- Unary Minus if int x=5


System.out.println (x); 5
System.out.println (-x); -5
System.out.println (-(-x) ); 5

++ Increment if int x=1(Pre-incr)


System.out.println (x); 1
System.out.println (++x); 2
System.out.println (x); 2

Ex :if a=1, b=2 (pre-incr)


a=++b a=3, b=3

if int x=1 (post-incr)


System.out.println (x); 1
System.out.println (x++); 1
System.out.println (x); 2

Ex: if a=1, b=2 (post-incr)


a=b++ a=2, b=3

INet Solv 35
Core Java

-- Decrement if int x=1(Pre-decr)


System.out.println (x); 1
System.out.println (--x); 0
System.out.println (x); 0

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)

Q: What is the result of the following if a=7

++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( - - ) :.

This operator increases the value of a variable by 1.


Here we have 2 types of increment operators.

iii) Pre-Decrementation : Writing -- before the variable is called pre


decrementation (--x). Here decrementation is done first and other
operations are done next. So top priority is for decrementation.
iv) Post-Decrementation : Writing -- after a variable is called post
decrementation (x--). Here the other operations are done first then
the decrementation is performed.

3. Assignment Operator :

Ø These operators are useful to store values in variables.


Ø int x=5 this is useful to store a value 5 into a variable x.
Ø int x=y this operator is useful to store a value of a variable into another value i.e.
RHS value is store in LHS.
Ø int x=y+z-4 this is useful to store the value of an expression into a variable x.
Ø Note 1: We cannot use more than one variable at the left side of assignment
operator.
Example : int x+y=10 // it is an invalid statement.
Ø Note 2: The expanded notations can be written in a shortcut way called compact
notations.

EXPANDED NOTATIONS COMPACT NOTATIONS

num=num+500 num += 500


Sal=sal-10 Sal -=10
P=p*k P*=k
X=x/30.5 x/=30.5
i=i%2 i%=2

4. Relational Operators

Ø These operators are useful to compare 2 Quantities.


Ø These operators are used in construction of simple conditions.

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

Ø These operators are used to construct compound conditions.

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

Ø These operators act upon individual bits (binary digits) of a number.


Ø These bitwise operators are used in Embedded Systems.
Ø Convert 45 into binary : Divide the number successively by 2 and take the
remainders from bottom to top.

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

a) Bitwise Complement (~)

v The symbol used for bitwise compliment is called Tilde.


v This operator gives the compliment form of given number.

v Rule : Add 1 and change the sign


v Example : int x = 10;
~x;
output : -11

b) Bitwise And ( & )

v This operator performs Anding operation on individual bits of


operators (numbers).
v Rule : Perform multiplication of each individual operators.
v The table showing the relationship between input and output bits is
called Truthtable.
v This operation is performed by an electronic device called AND Gate.
v It looks as follows:
v Example : if x=10 y=11
then x & y = ?

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 ( | )

v This operator performs Oring operation on each individual bits.


v Rule : Add the individual bits.
v This operation is performed by an electronic circuit called OR Gate.

v Example : if x=10 y=11


then x | y = ?

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 ( ^ )

v Xor means eXclusive or, it is a special type of OR operation.


v It is indicated by a symbol ^ which is called as
Caret/Cap/Circumfrence.
v This operator performs exclusive oring operation on bits.
v Rule : If odd no.of 1’s are there in input, then output will be 1.

v Example : if x=10 y=11


then x ^ y = ?

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

e)Bitwise left shift ( << )


v This operator shifts the bits towards left for a specified no.of times
(position).
v Left shift means removes the left most bits and add zero’s at
remaining position of the right side.
v Example :
int x =10;
x<<2;

x=?

0 0 0 0 1 0 1 0 = 10

0 0 1 0 1 0 0 0 = 40

f) Bitwise right shift ( >> )


v This operator shifts the bits towards right for a specified no.of times
(position).
v Right shift means removes the right most bits and add zero’s at
remaining position of the left side.
v Example :
int x =10;
x>>2;

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.

f) Bitwise zero fill right shift ( >>> )


v This operator is also shifts the bits towards right but does not
preserve the sign bit. It always fill zero in the sign bit.
v Example:

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.

//Program to demonstrate Bitwise operators.

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

System.out.println(“ x^y = ” + (x^y) );


System.out.println(“ x<<2 = ” + (x<<2) );
System.out.println(“ x>>2 = ” + (x>>2) );
System.out.println(“ x>>>2 = ” + (x>>>2) );
}
}

Output :

~x = -11
x&y = 10
x|y = 11
x^y = 1
x<<2 = 40
x>>2 = 2
x>>>2= 2

8. Ternary or Conditional operators

Ø This operators are called ternary because it acts as 3 variables.


Ø This operator are also called conditional operators because it represents a
conditional statement.
Ø Ternary operators are ? and :

Ø Syntax : var = exp1 ? exp2 : exp3;

Ø Example : max = (a>b) ? a : b;


If (a>b) is true then exp2 i.e. a is stored in max
If (a<b) is true then exp3 i.e. b is stored in max

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

10. Instanceof Operator

Ø This operator is used to test whether an object belongs to a class or not.

Ø Syntax: Boolean x = obj instanceof class;

Ø Example: Boolean x = emp instanceof employee;

11. new operator

Ø This operator is used to create object for a class.


Ø JVM creates object on heap memory.
Ø JVM allots dynamic memory.

Ø Syntax : classname obj = new classname( );

Ø Example : employee obj = new employee( );

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

19. CONTROL STATEMENTS


Ø Sequential Execution :Executing the statements one by one is called Linear
Execution . Sequential execution is useful to develop simple programs.
Ø Random execution: Executing the statements randomly and repeatedly is called
Random execution. Random execution is useful to develop better and complex
programs . Random execution is possible using control statements.
Ø Control statements: Control statements are statements which change the flow of
execution in a program. The following are the controlling statements in 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:

Ø This statement executes a task(one or more statements) depending upon whether


a condition is true or not.

if(condition)
Ø Syntax : statement1;
[else statement2;]

Ø Example :

//Test if a given number is +ve or –ve

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

Ø If condition can also be written as other 2 ways

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:

Ø This loop repeatedly executes a group of statements as long as a condition is


true.

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 :

//Program to display even numbers upto 10

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

Q: DO WHILE or WHILE which is efficient?


R: While loop provides better control for programs right from the beginning of
execution
so it is more efficient than do… while.

4. for loop:

Ø This loop executes a group of statements as long as a condition is true.For


loop is more suitable to execute the statements a fixed no.of times.

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

Ø Example 1: //Program to demonstrate for loop

class Demo
{
public static void main(String args[ ])
{
for ( int i=1; i<10; i++ )
{
System.out.println(i);
}
}
}

Ø Example 2: //Program to demonstrate for loop without expression 1


class Demo
{
public static void main(String args[ ])
{
int i=1;
for ( ; i<10; i++ ) //removing expression 1
{
System.out.println(i);
}
}
}

INet Solv 49
Core Java

Ø Example 3:

//Program to demonstrate for loop without expression 1 and 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:

//Program to demonstrate for loop without expression 1,2 and 3

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

Ø NOTE : We can write for loop without expression1 or expression2 or expression3


or any 2 expressions or all 3 expressions.
Ø Infinite loops are executed for ever and these are the draw backs.
Ø If the program is entered into infinite loop we should terminate the program by
pressing Ctrl + C.
Ø break statement is used to come out of loop.
Ø NOTE: It is possible to write a loop within another loop , called Nested loop.

Ø Example of nested loop:

for( int i=1; i<=3; i++ )


{
for( int j=1; j<=3; j++ )
{
Statements ;
}
}

5 . for each loop:

Ø This loop repeatedly executes a group of statement for each element of a


collection.
Ø COLLECTION : Group of elements or group of objects.
Ø Example : Array, java.util.classes

for (var : collection)


Ø Syntax: {
statements;
}

Ø It is used to retrieve elements line by line.


Ø It will be working only in JDK 1.5 and above only.
Ø Example:

//Programs to demonstrate for each loop

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:

//Program to demonstrate switch statement

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

Ø Break statement is useful to come out of the switch.


Ø If we want to use both small and capital letters in ch the above program should be
written as the following:

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:

Ø break is used in 3 different ways,


1. It is a statement to come out of a loop.
2. It is used to come out of a switch block.
3. It is used in the nested block . (a group of stmts written inside a left &
right curly braces is called a block). In nested block break is used to go to the
end of a block.
Ø Syntax :
break blockname;

IIQ : 16

Q: Go to statements are not available in java.why?


R: 1. GO TO stmts lead to confusion for a programmer.
2. GO TO stmts form infinite loops.
3. GO TO stmts make documentation difficult.
4. GO TO ‘S are not part of structural programming.bcoz of above reasons GO
TO has been eliminated.

Ø Example:

//Program to demonstrate break statement.

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:

Ø Continue statement is used to repeat the next iteration of a loop.


Ø Any subsequent statements after continue are not executed.
Ø Example:

//Program to demonstrate 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 :

Ø It is used to come out of a method, back to the calling method.


Ø A method contains a group of statements which performs a task.
Ø Return is used to return some result from a method to the calling method.
Ø Example :
return x;
return i;
return 10.5;
Ø Note : Return in main method will terminated the entire applications.
Ø Example ;

//Program to demonstrate 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

Ø We can replace the statement if(num == 1) return; by if(num==1)


System.exit(0);
Ø Here the System.exit(0) is used to terminate from any method or main method
and comes back to system prompt.

IIQ : 17

Q: Difference between System.exit(0) and System.exit(1)


R: System.exit(0) represents normal termination of a program.
System.exit(1) represents termination due to errors in program.

Exercise of Control Statements

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

20. HOW TO ACCEPT INPUT FROM THE KEYBOARD


Ø A stream represents a flow of data from one place to another place.
Ø Stream can carry data from one place to another place.
Ø We have 2 type of streams

1. Input Stream : It read or accept data.


2. Output Stream : It send or write data.

Ø All streams are represented as classes in java.io.package.


Ø Keyboard is represented by System.in
Ø When System.in is written internally it creates inputstream obj and it represents
keyboard.
Ø When System.out is written internally it creates printstream obj and it
represents Monitor.
Ø When System.err is written internally it creates printstream obj and it represents
monitor.

IIQ : 18

Q: What is the difference b/w System.out and System.err?


R: System.out : It is used to display general messages on the monitor.
System.out.println(“Hello”);
System.err : It is used to display the error message on the monitor.
System.out.println(“Error Message”);

Ø Streams are representing I/O devices.


Ø InputStreamReader can read the data from keyboard and it is connected to other
stream called BufferedStream which can read the data from the
InputStreamReader.

Ø Steps to accept the input from the keyboard are as following:

1. Attach keyboard to InputStreamReader

Syntax : classname obj = new classname;

Example : InputStreamReader obj = new InputStreamReader;

2. Attach InputStreamReader to BufferedReader.

Example :BufferedReader br = new BufferedReader(obj);

INet Solv 57
Core Java

3. Now read data from br using read( ) or readLine( ) methods.

Ø Step 1 and step2 can be combined and written as the following ;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Stream (flow of data)

- - - - - - - - - - - - - - - -BufferedReader
----------------------------

InputStreamReader

Keyboard

//Program to accept a character from 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

Ø read( ) can read only 1 character.


Ø With read( ) we have 2 problems

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

Ø Example : public static void main(String args[ ]) throws IOException.

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

Accepting a String from keyboard

Ø String is a group of characters.

System.out.println(“Enter a name :”);


String ch = br.readLine( );

Ø We can use throws IOException.


Ø There is no need of type casting.

Accepting an integer number from keyboard

System.out.println(“ Enter integer value “);


String str = br.readLine( );
int n = Integer.parseInt(str);

Class Static Method


Ø parseInt is a method which convert a string into integer.
Ø Integer is a class of parseInt.

Accepting an float number from keyboard

System.out.println(“ Enter float value =”);


float n = Float parseInt( br.readLine( ) );

Ø Float can accept upto 7 digits only after a decimal point.


Ø Example : 55.1234567

INet Solv 59
Core Java

Accepting an double number from keyboard

System.out.println(“ Enter double value =”);


double n = Double parseInt( br.readLine( ) );
Ø Float can accept upto 15 digits after a decimal point.
Ø Example : 55.1234567891234

//Program to accept Employee details.

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( ));

System.out.print(“Enter Sex = “);


char sex = (char)br.read( );
br.skip(2);

System.out.print(“Enter name = “);


String name = br.readLine( );

System.out.println ( “id is “ + id);


System.out.println ( “Sex is “ + sex);
System.out.println (“Name is “ + name );
}
}

Output :

Enter id = 007
Enter Sex = M
Enter Name = James Bond

Id is 007
Sex is M
Name is James Bond

Ø Once the object br is created we can use in many times in memory.


Ø Keyboard can take only one input at a time.
Ø While entering the data for “Enter Sex =” we may enter data as M/F if we enter like
this M is taken by Enter Sex and /F may be taken by Enter name and the
program may terminate because any letter followed by a slash (/a or /b or /z
etc., ) indicates the end of the input. Therefore we have a problem.

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.

Exercise of Input Output Programs

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 ;

1. Single Dimensional Arrays or 1D Arrays.


2. Multi Dimensional Arrays or 2D,3D………

1. Single Dimensional Arrays

Ø It represents only one row or coloum of element.


Ø Example – Marks obtained by a student in 5 subjects.

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

1) we can declare and directly initialize a one dimensional array.

Syntax : datatype arrayname[ ] = { element 1, element 2,……element n};

Example : int marks[ ] = ( 50, 51, 52, 53, 54 };

v One dimensional array will have only one index, it represents the position
number of the element in array.

Example : int marks[ i ];


float sal[ ] = { 5690.22, 4563.25, 7526.00 };
char ch[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ };
String names = { “rani”, “raju”, “venu”, “kumar” };

2) we can create an empty array using new operator and later on store the
elements into
the array.

Syntax : datatype arrayname[ ] = new datatype[ size ];

INet Solv 62
Core Java

Example : int marks[ ] = new int[5];


double x[ ] = new double[ 50 ];
byte b[ ] = byte[ 100 ];

v Later on we can store in program as

marks[ 0 ] = 50;
marks[ 1 ] = 51;
marks[ 2 ] = 52;
marks[ 3 ] = 53;
marks[ 4 ] = 54;

v we can give elements from keyboard also.


v Note: array.length gives the size of the array; where length is the
property of an array.

Syntax: array.length

Example : marks.length

//Program to get total marks and percentage

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( ) );

//Create an array with size n


int marks[ ] = new int[n];

//store elements into marks[ ]


for(int i=0; i<n; i++)
{
System.out.print(“Enter Marks:”);
marks[i] = Integer.parseInt(br.readLine( ));
}

//find total marks


int tot=0;
for(int i=0; i<n; i++)
{

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 :

How many Subjects : 3


Enter Marks : 100
Enter Marks : 100
Enter Marks : 100
Total Marks : 300
Percentage : 100.0

2. Multi Dimensional Arrays


Ø It represents several rows and columns of elements.
Ø In Multi dimensional arrays we have two indexes and it starts with (0,0).
Ø Example : Marks obtained by a group of students in 5 different subjects.
Columns M1 M2 M3 M4 M5
0,0 0,1 0,2 0,3 0,4 50 51 52 53 54
Sub1
1,0 1,1 1,2 1,3 1,4 60 61 62 63 64
Rows Sub2
2,0 2,1 2,2 2,3 2,4
Sub3 70 71 72 73 74

Ø Creating a two dimensional arrays:

1) we can declare a two dimensional array and directly initialize it with elements.

datatype arrayname[ ][ ] = { {element 1, element 2,……element n},


Syntax :
element 1, element 2,……element n},
element 1, element 2,……element n} };

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;

//read and display the array elements


System.out.println(“The matrix is :”);
for(int i=0; i<3; i++)
{
for(int j=0; j<4; j++)
{
System.out.println(x[i][j] + “\t”);
tot = tot + x[i][j];
}
System.out.println( );
}
System.out.println(“ Total =” + tot);
} }
Output :The matrix is :
1.1
1.2
1.3
1.4
2.1
2.2
2.3
2.4
1.1
1.2
1.3
1.4
Total =19.0

INet Solv 65
Core Java

22. COMMAND LINE ARGUMENTS


Ø The values passed to main method from command prompt are called command
line arguments and they are stored in args[ ]
Ø Example : c:\>java Arr 10 20 30

Command line arguments

C:\>java Arr 10 20 30
Command Line

Stored in Stored in Stored in


args[0] args[1] args[2]
Ø To know the no.of command line arguments we use the following

Syntax : int n = args.length

Ø Where n indicates the no. of command line arguments.

//Program to read from a 2D array and display no.of command line


arguments.

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 :

C:\> javac Arr.java


C:\> java Arr One Two Three
No.of args = 3
One
Two
Three

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 :

C:\> javac Arr1.java


C:\> java Arr1 10 20
Sum = 30.0

10. Program to display Sum of a matrix.


11. Program to display Transpose of a matrix.
*12. Take a 2D array and display a;; its elements using only one loop.

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.

Ø Creating String in Java

1) We can declare a string class variable and assign a string to it.

v Example : String name = “Krishna”;

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.

v Example : String str = new String(“Hello”);


v Here we are allotting memory for a string object str using new operator and
storing a string called Hello.

3) we convert a character array into a string object.

v Example 1 : Char arr[ ] = (‘H’, ‘A’, ‘I’);


String str = new String(arr);
System.out.print(str);

Output : H A I

v Example 2 : char arr[ ] = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ );


String str = new String(arr, 1, 3);
System.out.print(str);
Output : b c d

v In above statement String(arr, 1, 3) where 1 indicates the starting character


and 3 indicates the position number from the starting character. In example 1
indicates the starting character b since the index looks like (a in 0, b in1, c in 2,
d in 3, e in 4, f in 5) And 3 indicates the characters c and d since the position
number end at index 3.

INet Solv 68
Core Java

24. MEHTODS IN STRING CLASS

Ø In string class java soft people created many methods.


Ø These methods are included in java.lang.string
Ø Some of them are:

1. String concat(String str)


2. int length( )
3. char charAt(int index)
4. int compareTo(String str)
5. boolean equals(String str)
6. boolean equalsIgnoreCase(String str)
7. Boolean startsWith(String prefix)
8. Boolean endswith(String suffix)
9. int indexof(Sting str)
10.int lastindexof(Sting str)
11.String replace(char oldchar, char newchar)
12.String substring(int beginIndex)
13.String Substring(int beginIndex, int endIndex)
14.String toLowerCase( )
15.String toUpperCase( )
16.String trim( )

1. String concat(String str)

Ø concat is a method which accepts a string and returns a string value.


Ø It concatenates the calling string with str.
Ø Note : + symbol will also do the same.
Ø Example :
String s1 = “Hyder”, s2 = “bad” ;
String x = s1.concat(s2);
Ø Output : Hyderabad

2. int length( )

Ø This method returns the length of a string.


Ø Example :
String s1 = “Satish”;
int n = s1.length( );

Ø Output : 6

3. char charAt(int index)

Ø charAt is a method that returns a character at a specified location starting from


zero.
Ø Example :

INet Solv 69
Core Java

String s1 = “Satish”;
char x = charAt(int 3);
Ø Output : i

4. int compareTo(String str)

Ø 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

5. boolean equals(String str)

Ø It returns true if the calling string is equal to str.


Ø It is case sensitive.

6. boolean equalsIgnore(String str)

Ø It is same as above but it is case insensitive comparision.

7. boolean startsWith(String prefix)

Ø 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.

8. boolean endsWith(String suffix)

Ø It returns true if the invoking string ends with suffix.


Ø It is also case sensitive.

9. int indexof(String str)

Ø It returns the first occurrence of str in the string.


Ø Example :
String str = :This is a book”;
int n = str indexof(“is”);
Ø Output : 2nd and 4th position includes the string “is”

INet Solv 70
Core Java

10. int lastindexof(String str)

Ø It returns the last occurrence of str in the string.


Ø Note : Both the methods int indexof(String str) and int lastindexof(String str)
returns positive if str is not found in the calling string.
Ø The counting starts from 0.

11. String replace(char oldchar, char newchar)

Ø It returns a new string that is obtained by replacing all characters oldchar in the
string with new char.

12. String substring( int beginIndex)

Ø It returns a new string consisting of all characters from beginIndex until the end of
the strings.

13. String substring( int beginIndex, int endIndex)

Ø It returns a new string consisting of all characters from beginIndex until the
endIndex(exclusive).

14. String toLowerCase( )

Ø It converts all the characters into lower case.

15. String toUpperCase( )

Ø It converts all the characters into upper case.

16. String trim( )

Ø It eliminates all leading and trailing spaces.

//Program to demonstrate strings


class str
{
public static void main(String args[ ])
{
//create 3 strings
String s1 = “This is java”;
String s2 = new String(“I like it”);
char arr[ ]= { 'I', 'N', 'E', 'T', , 'S', 'O', 'L', 'V'};
String s3 = new String(arr);

//display the strings


System.out.println(“s1 = “ + s1);
System.out.println(“s2 = “ + s2);

INet Solv 71
Core Java

System.out.println(“s3 = “ + s3);

//find no.of characters in s1


System.out.println(“length of s1 = “ + s1.length( ) );

//join s1 and s2
System.out.println(“s1 joined with s2 = “ + s1.concat(s2) );

//join 3 strings using +


System.out.println(s1 + “at” + s3 + s2);

//Test if s1 starts with “This” or not


boolean x= s1.startsWith(“ This “);
if( x == true )
System.out.println(“s1 starts with This “);
else
System.out.println(“s1 does not start with This”);

//Extract substring from s2 and s3


String p = s2.substring(0,6);
String q = s3.substring(0);
System.out.println( p+ q );

//convert the case of s1


System.out.println(“Upper s1 = “ + s1.toUpperCase);
System.out.println(“Lower s1 = “ + s1.toLowerCase);
}
}
Output : s1 = This is Java
S2 = I like it
S3 = INETSOLV
Length of s1 = 12
S1 joined with s2 = This is Java I like it
This is java at inetsolv I like it
S1 Does not start with This
I like INETSOLV
Upper s1 = THIS IS JAVA
Lower s1 = this is java

//Program to demonstrate the equality of strings

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”);
}
}

Output: Both the strings are not same

IIQ : 19

Q: What is Hash Code?


R: Hash Code is a unique id number allotted by JVM to an object. Hash code is
also called
Reference number.

Explanation of above program

Ø 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

Ø String s2 = new String(“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 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

Q: 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.

//The above program can be modified and written as below

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”);
}
}

Output: Both the strings are same.

Ø Since we are not using the new operator the output we get is “Both the strings
are same”.

Explanation of above modified program

Ø 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

String Constant Pool

IIQ : 21

Q: What is String Constant Pool?


R: When JVM creates string object it stores the string object into a separate
memory block which is called String Constant pool.

Ø 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

125 String Constant Pool

Ø if(s1==s2)

Reference Number

Hello
125
S1
Compared
And equal
125 String Constant Pool

S2

Ø Therefore the output will be “Both the strings are same”.

IIQ : 22

Q: What is the difference between the following 2 statements:


1. String s = “Hello”;
2. String s = new string(“Hello”);

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

25. TYPES OF OBJECTS


1. Mutable object: These are the objects whose contents can be modified.
2. Immutable object: These are the objects whose contents cannot be
modified.String objects are immutable.

//Program to demonstrate string objects are immutable (IIQ)


class Test
{
public static void main(String args[ ])
{
String s1= “One”;
String s2=”Two”;
s1= s1 + s2;
System.out.println(s1);
}
}
Output : OneTwo

Explanation of above program


Ø String s1=”One”;

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.

Creating StringBuffer object

1. StringBuffer sb = new StringBuffer(“Hello”);


2. StringBuffer sb = new StringBuffer(50); //empty

INet Solv 77
Core Java

26. java.lang.StringBuffer
1. StringBuffer append(x)

Ø Appending means adding data at the end of existing data.


Ø X may be int, float, double, char, string or StringBuffer.
Ø It will be appended to the calling StringBuffer.

2. StringBuffer insert(int offset,x)

Ø X may be int, float, double, char, string or StringBuffer.


Ø It will be inserted into the StringBuffer at offset.

3. StringBuffer delete( int start, int end)

Ø Removes the characters from start to end.

4. String reverse( )

Ø Reverse the characters Sequence in the StringBuffer.

5. String toString( )

Ø Convert StringBuffer into a string.

6.int length( )

Ø Returns the length of the StringBuffer.

IIQ : 23

Q: Difference between String and StringBuffer?


R: 1. String class objects are immutable(i.e cannot be changed)
StringBuffer objects are mutable.
2. Data manipulation methods(delete( ), reverse( ) ) are not available in strings.
They
are available in StringBuffer.

//Program to read Fullname and display.

import java.io.*;

class Full
{
public static void main(String args[ ] )throws IOException
{
//To accept data from keyboard.

INet Solv 78
Core Java

BufferedReader br = new BufferedReader(new


InputStreamReader (System.in));

System.out.print(“Enter Sur name = ”);


String sur = br.readLine( );

System.out.print(“Enter Middle name = ”);


String mid = br.readLine( );

System.out.print(“Enter Last name = ”);


String last = br.readLine( );

//Create the empty StringBuffer


StringBuffer sb = new StringBuffer( );

//Append sur, last to sb


sb.append(sur);
sb.append(last);

//insert mid after sur in sb


int n = sur.length( );
sb.insert(n, mid);

//display fullname and it reverse also


System.out.println(“Full name = “ + sb);
System.out.println(“In Reverse = “ + sb.reverse( ) );

}
}

Output :

Enter Sur Name = Pedapudi


Enter Middle Name = Satish
Enter Last Name = Kumar

Full Name = Pedapudi Satish Kumar


In Reverse = ramuKhsitaSidupadeP

INet Solv 79
Core Java

27. Object Oriented Programming System (OOPS)


Ø C, Pascal, Fortran, Basic, Cobol etc languages are called Procedural Language
because they follow procedural approach.
Ø In procedural languages Procedures and Functions are written to solve any
problem.
Ø C++, Java etc., are called Object Oriented Languages because they follow object
oriented approach.
Ø In Object Oriented Approach Objects and Classes are used in the program.

IIQ : 24

Q: What is an SRS (Software Requirement Specification)?


R: SRS is a document that contains client requirements along with the
strategies(plans) to full fill those requirements. SRS is prepared by PROJECT
LEADER.

IIQ : 25

Q: What is an SDS (Software Design Specification)?


R: SDS is a document that contains IO Screens, Pseudo code (algorithms), Data
Flow Diagrams(DFD’s), Backend Database Description etc., It contains the logic
part that contains how to solve a particular problem. SDS is written by MODULE
LEADER.

Problems in Procedural Language

1. In procedural approach the programmer’s concentration will be on the problem and


its solution. So developing full fledged software is not possible. Therefore we need
another approach where the programmer studies the entire behavior of the system
and then only the software is developed.

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.

3. In procedural approach programming is completely unnatural and it does not


reflect human being life. Therefore we need another approach where programming
reflects human being life.

Ø Therefore to avoid above problems a new approach or methodology is developed


which is called Object Oriented.

INet Solv 80
Core Java

28. FEATURES IN OOPS


1. Object / Class
2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism
6. Message Passing

1. Object / Class :

Ø Object is any thing that exists really in this world.


Ø For example: chair, pen, table, animal, human being are objects but plans, ideas
are not objects.
Ø An object contains properties and can perform actions.
Ø Properties are represented by variables.
Ø Actions are represented by methods.
Ø Therefore we can say that an object contains variables and methods.
Ø Example :

Raju Object

Variables
Properties

Name, Height, Weight,


age, color etc.,

Methods
Actions

Talk, walk, sing, fight,


sleep etc.,

Ø 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 :

Ø Building up of data and methods as a single unit is called Encapsulation.


Ø For example : writing a class.
Ø By encapsulating we can protect the data and methods from the outsiders by
keeping them in a class. Therefore it is a protective mechanism for data and
methods.
Ø The members of one class are separated from members of another class. i.e. a
method with same name can be in 2 different classes. So the programmers can
use same name for members of different class.

3. Abstraction :

Ø Hiding the un-necessary data from the user is called Abstraction.


Ø For example : Parts of a car (Engine, Radiator, Meter, Electric wires etc.,).
Ø Abstraction is implemented using some keywords like public, private, etc.,

4. Inheritance :

Ø Producing new classes from existing class.


Ø One of the main advantage of Inheritance is Reusability of code in developing
your won classes.

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 :

Ø Calling a method and passing data to a method is called Message Passing.

IIQ : 26

Q: 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 into Java.

OBPL follow all the features of OOPs except Inheritance. Example Javascript
and VBScript.

INet Solv 82
Core Java

//Program to demonstrate Class and objects

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

Q: Is class a data type or not ?


R: Yes, class is a user defined data type.

Explanation of above program

Ø 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

Ø Output of the above program is

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;

DATA TYPES DEFAULT VALUES


Int 0
Float 0.0
Double 0.0
Char a space
String Null
Boolean false

INet Solv 84
Core Java

29. Types of Initializing the Instance Variables


Type 1 : We can initialize the instance variables of a class in another class using the
reference .

Ø 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

It has security for data.


It is used for methods.
3. PROTECTED : Protected members are available outside the class.
4. DEFAULT :When no access specifier is used, java compiler uses default
specifier internally. Ex : void talk( )
Default members are also available outside the class.

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

Ø In this every object is initialized with same data

public static void main(String args[ ])


{
person p1 = new person( );
p1.talk( );

person p2 = new person( );


p2.talk( );

INet Solv 86
Core Java

Output:

Name = Satish //Result of object p1


Age = 24

Name = Satish //Result of object p2


Age = 24

Ø This type of initialization is used for constants not for variables.


Ø For declaring constants we use a keyword called Final.
Ø Ex : final double PI = 3.14159;

TYPE 3 : We can initialize the instance variable using a Constructor.

Ø A constructor is similar to a method which is used to initialize the instance


variable.
Ø A constructor without parameter is called Default Constructor.
Ø A constructor with parameter is called Parameterized Constructor.
Ø A constructor name and a class name must be same.
Ø A constructor does not return any value and it not even returns void.
Ø A constructor is called only once per object.

IIQ : 28

Q: 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.

Ø 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( );

person p2 = new person(“Iliana”, 21 );


p2.talk( );

person p3 = new person(“Trisha”, 24 );


p3.talk( );
}
}
Output :

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 :

1. Method prototype or Method header


2. Method body

1. Method prototype or Method Header :

Ø It contains method name method parameter and method return type.


Ø Syntax: returntype methodname( parameter1, parameter2,…);
Ø Method parameters are local variables which receive data from outside.
Ø Variables declared in method or constructor is called local variables.
Ø Example :
1. void main( )
2. int sum(int a, int b)
3. double power(double x, int n)
4. double sqrt(double num)
5. long fact(int x)
6. float calculatetax(float sal)

2. Method Body:

Ø It is a group of statements written inside left parenthesis { and right parenthesis }


which performs the task.
Ø Note: If a method returns any value we should use return statement inside the
method body
Void main( )
{
statements;
Ø Syntax :
return x;
}

Ø A method can return only one value /entity.


Ex : return x;
return obj;
return arr;
Ø A method cannot return more than one value if it returns more than one value
then that statement is invalid.
Ex: return x, y; //invalid statement
Ø Note: A method is executed only when it is called.
Ø To call a any method we should write
Objectname.methodname( ); i.e. obj.method( ); ex: s.sum( );
Ø A method can be called any no.of times.

INet Solv 89
Core Java

// Program to understand methods

class Sample
{
//instance variables
double d1, d2;

//parameterized constructor
Sample(double a, double b)
{
d1 = a;
d2 = b;
}

//method to add a and b


double sum(double d1, double d2)
{
double d3 = d1 + d2;
System.out.println(“Sum is “ + d3);
return d3;
}
}

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

Ø Instance method is a method that acts on instance variables.


Ø D3 is a local variables.

INet Solv 90
Core Java

31. Types of methods in java


1. Static Method
2. Instance Method
a) Accessor Method
b) Mutator Method
3. Factory Methods.

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( );

Ø Example : double res = s.sum(10, 22.5);


double res = sample.sum(10, 22.5);
Ø Static method cannot read instance variables because JVM first of all executes
static method and they only creates objects, so at the time of executing static
methods the instance variables are not available to it.
Ø Static variables are accessible directly by static methods.
Ø A static variable should be declared as static using static. Ex : static int i = 50;

// Program to understand STATIC methods

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;
}

//static method to add a and b


static double sum(double d1, double d2)
{
System.out.println(“i” + i );
double d3 = d1 + d2;
return d3;

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

Q: What is the difference between instance variable and static variable ?


R: 1. 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.

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

Instance Variable Static Variable

INet Solv 92
Core Java

2. Instance variables are stored in Heap.


Static variables are stored in Method area.

Ø 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( );

a. Accessor Method : These methods access (read) the instance variables.


b. Mutator Method : These are the methods which not only read the instance
variables but
also modify them.

// Program demonstrate Accessor and mutator methods

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[ ])
{

person p1 = new person(“Srinu”, 25, ‘M’); //1.1


p1.display( ); //1.2

person p2 = p1.modify(p1); //1.3


p2.display( ); //1.4

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

Ø Reference variables are passed to methods by value.


Ø If object is passed instead of reference we should write as bellow :

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

}
}

Srinu Venkat Laxmi


25 26 24
P1 M M F

obj

P2

Ø Objects are passed to methods by value.


Ø “This” is a keyword that refers to the present/current class. It means “this” can
refer to present class variables, present class constructors and present class
methods.
Ø Example :

//Program to demonstrate “this” keyword

class Sample
{
int n;

Sample( )
{
//this( ); //calling the present class default constructor

INet Solv 95
Core Java

this(100); /calling the present class parameterized constructor


this.display( ); //calling the present class method constructor
}

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 :

Ø It is a method that returns an object of the class to which it belongs.


Ø All factory methods are static methods but all static methods are not factory
methods.

Ø Syntax : NumberFormat obj = NumberFormat.getNumberInstance( );

INet Solv 96
Core Java

IIQ : 30

Q: In how many ways we can create an object in JAVA?


R:
1. Using new operator

Syntax : classname obj = new classname( );


Example : Employee obj = new Employee( );

2. Using Factory Method

Syntax : NumberFormat obj = NumberFormat.getNumberInstance( );

3. Using newInstance( )

Ex : class c = class.forName(“Employee”);
Employee obj = c.newInstance( );

In class.forName(“Employee”) statement class is a Class, forName is a


Factory method and Employee is a string.

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.

4. Using Cloning

Cloning is a mechanism to obtain exact copy of an existing object.


Example : Employee e1 = new Employee( );
Employee e2 = e1.clone( );
In above example, a new object e2 is created by cloning e1(existing object).

//Program to demonstrate Factory Methods


//To find Area of a Circle

import java.text.*; //Used for formatting text

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

final double PI = 22/7; //Here we have a problem since int/int


gives int value ie. PI value will be only 3
double r = 15.5;

//Find area of circle and display


double area = PI * r * r;
System.out.println(“Area = “ + area);

//Create NumberFormat object


NumberFormat obj = NumberFormat.getNumberInstance( );

//Store format information into object


obj.setMaximumFractionDigits(2);
obj.setMinimumFractionDigits(7);

//Apply format to area


String str = obj.format(area);
System.out.println(“Formatted Area = “ + str );
}
}

Output :

Area = 754.7669975
Formatted Area = 754.7669975

Or

Area = 720.75
Formatted Area = 720.7500000

IIQ : 31

Q: Is it possible to pass complete arrays to method and display it?


R: Yes it is possible.
Example 1: Passing one dimensional arrays
int[ ] myMethod(int arr[ ]);
Example 2: Passing two dimensional arrays
int[ ][ ] myMethod(int arr[ ][ ]);

//Program to demonstrate passing arrays to methods


//To add the matrices using methods

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];
}

//Accept matrix from keyboard


int[ ][ ] getArray( )throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader (System.in) );
for( int i=0; i<r; i++)
{
for( int j=0; j<c; j++)
{
System.out.println(“Enter Elements =”);
arr[ ][ ] = Integer.parseInteger(br.readLine( ));
}
}
return arr;
}

//Find sum of two matrices


int [ ][ ] findSum( int a[ ][ ], int b[ ][ ] )
{
int temp[ ][ ] = new int[r][c];
for( int i=0; i<r; i++)
{
for( int j=0; j<c; j++)
{
temp[ ][ ] = a[i][j] + b[i][j];
}
}
return temp;
}

//Display the sum of matrix


void putArray( int res[ ][ ] )
{
for( int i=0; i<r; i++)
{
for( int j=0; j<c; j++)
{
System.out.println( res[i][j] + “/t” );
}
System.out.println( );
}
}

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[ ][ ];

System.out.println(“/n Enter Matrix 1 = “);


x = obj1.getArray( );

System.out.println(“/n Enter Matrix 2 = “);


y = obj2.getArray( );

//Add the Matrices


z = obj1.findSum(x,y);

//Result
obj2.putArray(z);
}
}

Output :

Exercise of Methods

17. Write a method to swap 2 given values.


18. Multiply 2 matrices and display the product of a matrix using methods.
19. Write a method to accept a year number, and then test and display whether it is
a leap year or not.

INet Solv 100


Core Java

32. Relating objects of two classes


Ø We can relate objects of 2 classes by taking one class reference as an instance
variable in another class.
Ø When the objects are related in memory it is possible to access the members of
one object from another object.

Latest IIQ : 32

Q: What is Object Graph ?


R: It is a graph showing relationship b/w different objects in memory.

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

//display object o Two


void display( )
{
System.out.println(“x= “ + x); y 20
t.display( );
}

} object t
class Two
{
int y;
Two( )

INet Solv 101


Core Java

{
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

INet Solv 102


Core Java

33. Inner Class


1. Inner class is a class within another class.
2. Inner class is a safety mechanism.
3. Inner class is hidden in the outer class from other class.
4. An object to inner class cannot be created in any other class.
5. An object to inner class can be created only in its inner class.

Only Authorized persons can access inner


Outer class Class though inner class object created in
Outer class
object
Other class

Inner class

Other classes cannot access inner class

Outer class acts as FIREWALL to inner class

6. Only inner class can be declared as private.


7. Outer class members are available directly to inner class.
8. Outer class objects and inner class object are executed in separate memory
location.

bal
bal rate

rate
this$0

It is wrong BankAcct Interest

Separate Memory Locations of outer & inner class


9. Inner class object contains an invisible additional field called “this$0” which
stores the reference of outer class object.

INet Solv 103


Core Java

10.Outer class members are referenced as : outerclass this.member


11.Inner class members are reference as : this.member

//Program to demonstrate Inner classes


class BankAcct
{
private double bal;
BankAcct( double b)
{
bal = b;
}
void start( double r )
{
Interest in = new Interest(r);
in.calculateInterest( );
}
private class Interest
{
private double rate;
Interest(double r)
{
rate = r;
}
void calculateInterest( )
{
double Interest = bal * rate/100;
System.out.println(“Interest=” + Interest);
bal+= Interest;
System.out.println(“Balance =” + bal);
}
} }

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.

INet Solv 104


Core Java

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.

Ø Syntax : class subclass extends superclass

Ø 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

Q: What is the advantage of Inheritance?


R: Reusability of the code is the main advantage. Because of this reusability the
overall productivity of a programmer and also of the company will be increased.

//Program to demonstrate Inheritance using extends keyword


class Teacher //super class
{
int id;
String name,addr;
float sal;

void setid(int id) // Mutator method


{
this.id = id;
}
int getid( ) // Accessor method
{
return id;
}
void setname(String name) // Mutator method
{
this.name = name;
}
int getname( ) // Accessor method
{
return name;
}
void setaddr(String addr) // Mutator method
{
this.addr = addr;
}
int getaddr( ) // Accessor method
{

INet Solv 105


Core Java

return addr;
}
void setsal(int sal) // Mutator method
{
this.sal = sal;
}
int getsal( ) // Accessor method
{
return sal;
}
}

class Student extends Teacher // sub class


{
int marks;
void setmarks(int marks)
{
this.marks = marks;
}
int getmarks( )
{
return marks;
}
}

class Use //Use student class


{
public static void main(String args[ ])
{

//create student class object


Student s = new Student( );

//store data into s


s.setId(10);
s.setName(“Satish”);
s.setAddr(“EWSH 284, Moulali, Hyderabad”);
s.setMarks(900);

//Retrieve data from s


System.out.println( “Id = “ + s.getId( ) );
System.out.println( “Name = “ + s.getName( ) );
System.out.println( “Address = “ + s.getAddr( ) );
System.out.println( “Marks = “ + s.getMarks( ) );
}
}

Output :
Ø From above program we can say that all the members of super class are available
to subclass.

INet Solv 106


Core Java

Ø But what happens if the super class contains default constructor.


Ø Let us see an example :

//Program in which the super class contains Constructors

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

Ø From the above program we can understand 2 points:

1. Default constructor of Super class is automatically available to the sub class


i.e. First of all, super class constructor is executed and then only subclass
constructor is executed.

2. Super class, parameterized constructor is not available by default to the


subclass.

Ø 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.

INet Solv 107


Core Java

//Program in which super class contains parameterized constructor


class One
{
int x; //variable x of class one

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.

INet Solv 108


Core Java

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 :

Ø This is the polymorphism exhibited at Runtime.


Ø In this a method call is bound to the method body at run time by the JVM. So it is
also called as Dynamic Binding or Runtime Polymorphism.

// Program to demonstrate Dynamic Programming – Method Overloading

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 :

Sum of two no’s = 32

Ø 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.

INet Solv 109


Core Java

IIQ : 34

Q: What is a Method Signature?


R: Method name and its parameters combinedly are called Method Signatures.

Ø 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 :

1. Difference in no. of parameters.


Ex : void add(int a, int b)
Void add(int a, int b,int c)

2. Difference in data types of parameters.


Ex: void add(int a, int b)
void add(double a, double b)

3. Difference in sequence of parameters.


Ex: int swap(char a, int b)
Int swap(int a, char b)

Ø Method Overloading using instance methods will come under Dynamic


Polymorphism.

Ø 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.

// Program to demonstrate Dynamic Programming – Method Over Riding

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));

INet Solv 110


Core Java

}
}

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

Q: Difference between Method Overloading and Method Over Riding?


R: Functional Difference :

Method Overloading is used to extend an already available features of the


software. Method Overloading is Code Refinement.

Method Over Riding is used to provide a different implementation for the


same feature. Method OverRiding is Code Replacement.

2. Static Polymorphism :

Ø The polymorphism exhibited at compilation time is called Static Polymorphism.


Ø Here the compiler knows which method is called. It means a method call is bound
with the method body at compilation time. So it is also called as Static Binding or
Compile Time polymorphism.
Ø Method Overloading and Method Overriding using
static methods
private methods
final ,methods
are examples for static polymorphism.

INet Solv 111


Core Java

Ø final method :

v A final class is a class which is declared as final.


v A final method is a method which is declared as final.
v Generally final keyword is used for 2 purpose :
v First, final keyword is used to declare constants. Ex: final double PI =
3.14591.
v Secondly, final keyword before a class name prevents Inheritance. i.e we
cannot access
subclass to a final class.
v By default all the methods of a final class will become final methods.
v Therefore final methods cannot be overridden.
v Example : final class A
Class B extends A //invalid statement

Ø Private methods also cannot be overridden.

INet Solv 112


Core Java

36. TYPE CASTING


Ø Converting one data type into another data type is called Type Casting.
Ø Data type represents the type of data stored into the variable.
Ø There are two types of data types :

1. Primitive data types or Fundamental data types.


2. Advanced data types or referenced data types.

IIQ : 36

Q: Difference between Primitive and Advanced data types?


R: Primitive data types
These data types represents single values.
Methods are not available to handle primitive data types.
Ex : char, byte, short, int, long, float, double, Boolean.

Advanced data types


These data types can store several values.
Methods are also available to handle advanced data types.
Ex : any array, any class(String, employee…)

Ø 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.

1. Casting Primitive Data types:

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.

Char, byte, short, int, long, float, double, Boolean


Lower <------------------------------------------------------------- > Higher

Ex 1 :
char ch = ‘A’;
int n = ch; //It is invalid statement since integer cannot be assigned to character,
so we
use type casting.

Therefore the above statement should be written as below:

INet Solv 113


Core Java

char ch =’A’;
int n = (int) ch; //It is widening

Ex 2 :

int num = 12;


float f = (float) n; //It is widening implicitly

Ø In widening, digits or precision is not lost. Ex : Output : 12.456

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.

Therefore the above statement should be written as below :

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

2. Casting Advanced Data types :

Ø To convert a referenced type into another referenced type, those classes should
belong to same Inheritance chain( superclass, subclass, sub subclass,etc.)

//Program on Advanced data types

class One
{
void show1( )
{
System.out.println(“Super class”);
}
}

INet Solv 114


Core Java

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.

Ø Let us see the case 2 in advanced data type

class Cast
{
public static void main(String args[ ])
{

// case 2- Sub class reference to refer to Sub class obj


Two t;
t = new Two( ); //Type casting is not required, since LHS data
type (t) and RHS data type (Two) are same.
t.show1( ); //It is called
t.show2( ); //It is also called
}
}

Output :

Super class
Sub class

INet Solv 115


Core Java

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.

Ø Let us see the case 3 in advanced data type

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.

INet Solv 116


Core Java

Super Class
Fruits

Citrus Non Citrus Sub classes

Lemon Orange Sub Sub Banana Mango


Classes

Generalization Specialization

Ø Let us see the case 4 in advanced data type

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.

INet Solv 117


Core Java

37. DATA ABSTRACTION


Ø Sometimes the implementation of a method changes depending upon the
requirement of the individual object. In that case we can’t write body for the
method in the Super class, we should write body in the Sub class.
Ø A method without body is called Abstract Method.
Ø Abstract method should declared using a keyword “abstract”.
Ø A class that contains some abstract method is called abstract class.
Ø Abstract classes are declared using a keyword “abstract”.

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( )

Ø An abstract class is a class that contains 0 or more abstract method.


Ø An abstract class can contain instance variable and concrete methods also in
addition to abstract methods.
Ø We cannot create an object to abstract class.
Ø We can create a reference of abstract class.
Ø All the abstract methods of the abstract class should be Implemented (body) in its
Subclass.
Ø If any method is not implemented, then that subclass should be declared as
“abstract”.
Ø Abstract class reference cannot refer to the individual methods of the sub class.
Ø A class cannot be both abstract and final.
Ex: abstract final class A //Invalid statement

INet Solv 118


Core Java

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

//Program to demonstrate Abstract classes

//This is a class Car


abstract class Car
{
//every car will have a registration number
int regno;

//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);
}

//This is a concrete Subclass of a Car class


class Maruthi extends Car
{
Maruthi(int regno)
{
super(regno);
}
void steering(int direction)
{
System.out.println(“Maruthi uses manual steering”);
System.out.println(“Please drive the car”);
}

INet Solv 119


Core Java

void breaking(int force)


{
System.out.println(“Maruthi uses Hydraulic Breaks”);
System.out.println(“Please stop the car”);
}
}
//This is a concrete Subclass of car class
class Santro extends Car
{
Santro(int regno)
{
super(regno);
}

void steering(int direction)


{
System.out.println(“Santro uses Power Streeing”);
System.out.println(“Start it”);
}

void breaking(int force)


{
System.out.println(“Santro uses Gas breaks”);
System.out.println(“Stop it”);
}
}

//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);

//Create a reference to car class


Car c;

//Use reference to refer to the object


c =m; or c = s;

//Use Maruthi
c.fillTank( );
c.steering(2);
c.breaking(200);
}
}

INet Solv 120


Core Java

Output : if c = m

Take car key and fill the Tank


Maruthi uses Manual Steering
Please drive the car
Maruthi uses Hydraulic breaks
Please stop the car

Output : if c = s

Take car key and fill the Tank


Santro uses Power Steering
Please drive the car
Santro uses Gas breaks
Please stop the car

Exercise of Abstract class

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.

INet Solv 121


Core Java

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 :

S/W or Program in Java


Oracle
Connected
void connect( )
{
class code to connect
Oracle Database
} Sybase Not
Connected

void disconnect( )
{
code to disconnet MySql
} Not
Connected

Ø In the above figure a program is written in java to make a connection to any


database. Here the programmer make use of class, in a class a method void
connect( ) is written in which it contains the code to connect Oracle database
only (Since the programmer had thought according to Oracle database only ). But
when the client who purchased this software uses Sybase database this program
does not work and it does not make any connection to the database. Similarly to
MySql database, this program does not work.

Ø So the problem by using class is we cannot perform different tasks. Therefore by


using classes we cannot write a code to connect any type of database.

Ø To solve this problem only we make use of Interfaces.

INet Solv 122


Core Java

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

Abstract Class Implementation classes


Or Drivers
Written by 3rd party vendors

Ø Therefore the solution to the above problem is we should use Interfaces.


Ø In interfaces we use abstract class and Implementation class.
Ø Implementation class contains the code to connect the particular database
and it is given by the 3rd party vendor. Implementation class is also called
Drivers.
Ø A person should purchase Implementation class from the 3rd party vendor along
with the software he has purchased.
Ø Methods used in the Implementation class(written by 3rd party vendor) should
be same as the methods used in the abstract class(written by programmer).
Ø The 3rd party vendor can know which methods are used by programmer in
Interface by seeing the API document.

INet Solv 123


Core Java

Any 5 methods Interface

method 1( )
method 2( )
method 3( )
method 4( )
method 5( ) Abstract methods (without body)

Above 5 Above 5 Above 5 Implementation


methods are methods are methods are classes
described in described in described in
one way other way another way
Above methods with
Body in diff ways

Objects

Ø An Interface is a specification of method prototype.


Ø All the methods of the interface are public and abstract by default.
Ø An interface can contain variables which are public, static and final by default.
Ø An interface contains zero or more abstract methods. i.e. Yes we can write an
abstract class without any methods.
Ø We cannot create an object to the interface.
Ø We can create a reference variable of interface type.
Ø All the methods of interface should be implemented in its implementation classes.
Ø If any method is not implemented, then that implementation class should be
declared as “abstract”.
Ø Interface reference can be used to refer to the objects of its implementation class.
Ø Once an interface is written, any third party vendor can provide implementation
classes to it.

Ø An interface cannot implement another interface.


Ø An interface can extend another interface.
Ø It is possible to write a class within an interface.
Ø A class can implement multiple interfaces.

INet Solv 124


Core Java

//Program to demonstrate Interface

//Interface
interface MyInter
{
void connect( ); // public abstract
}

//implementation class for Oracle Database


class OracleDB implements MyInter
{
public void connect( )
{
System.out.println(“Connection to Oracle Database.. .. .”);
}
}

//implementation class for Sybase Database


class Sybase implements MyInter
{
public void connect( )
{
System.out.println(“Connection to Sybase Database.. .. .”);
}
}

//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 :

C:\> javac Database.java


C:\> java Database OracleDB

Connecting to Oracle Database.. .. .


mi
Connect( )

INet Solv 125


Core Java

IIQ : 39

Q: What is the difference between abstract class and Interface ?


R: 1. A programmer creates an abstract class when there are some common
featuresshared by all the object.
A programmer writes an Interface when array feature is implemented
differently for different objects.
2. When abstract class is written it is the duty of a programmer to provide
subclasses to it.
When Interface is written any 3rd party Vendor can provide implementation
classes to it.

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 )
}

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).

INet Solv 126


Core Java

39. Types of Inheritance


Ø In Java we have 2 types of inheritance

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

INet Solv 127


Core Java

IIQ : 41

Q: Multiple Inheritance is not available in Java Why?


R: 1. Multiple Inheritance leads to confusion for a programmer.
2. Multiple Inheritance can be achieved by suing Interfaces.

Ex: class Z implements A, B


Here A, B are interfaceses but not super classes.

3. Multiple Inheritance can be achieved by repeated use of Single


Inheritance.

Ex : The above statement can be written as


class B extends A //valid , Single inheritance 1
class Z extends B //valid, Single inheritance 2

//Program to demonstrate Multiple Inheritance

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/) );
}
}

INet Solv 128


Core Java

//Main method
class Multi
{
public static void main(String args[ ])
{
child ch = new child( );
ch.property( );
ch.height( );
}
}

Output :

Childs property = 800000


Childs Height = 5.6

Exercise of Interface

23. Create an interface “Shape” with PI value as 3.14159 and a method


“volume(float a, float b)” , implement this interface individually in Sphere and
Cylinder classes to find their volume.

Hint : Volume of sphere = 4 * PI * r * r * r/3


Volume of Cylinder = PI * r * r * n

INet Solv 129


Core Java

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.

These classes and interfaces are stored in


C:\program files\java\jdk 1.5.0 \Jre\lib\rt.jar
rt Executable jar file contains all the packages(classes and methods) require
by java.

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.

3. Packages provide Reusability of Code.

4. It is possible to extend the available packages and create user defined


packages.

Creating our own package named pack :

package pack; // package is a keyword, pack is a package name


public class Addition
{
private double d1,d2;

public void Addition(double d1, double d2)


{
this.d1 = d1;

INet Solv 130


Core Java

this.d2 = d2;
}

public void Sum( )


{
System.out.println(“Sum = “ + (d1+d2) );
}
}

Let us save it as Addition.java in a folder psk in C:

If we compile normally the output is


C:\psk\javac Addition.java
error: cannot read: Addition.java

But if we compile as shown below the output is


C:\psk\javac –d . Addition.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

07/25/2007 11:35 PM <DIR> .


07/25/2007 11:35 PM <DIR> ..
07/25/2007 11:35 PM 727 Addition.class
1 File(s) 727 bytes
2 Dir(s) 384,970,752 bytes free

Ø In javac –d . Addition.java command –d indicates the switch option and .(dot)


indicates the current directory, and when this command is executed java creates a
sub directory Addition.class in package called pack folder and a normal
Additon.java file in psk folder.

How to use the methods of Addition class of package pack

//Using the package pack


class Use
{
public static void main(String args[ ])
{
pack.Addition obj = new pack.Addition(10, 15.5);
obj.Sum( );
}

INet Solv 131


Core Java

Save it as Use.java in folder psk of C:\> and compile normally

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.

Adding another class to already existing package pack

package pack;
public class Subtraction
{
public static double Sub(double a, double b)
{
return(a-b);
}
}

save it as Subtraction.java in psk folder of c:\> and compile as below

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

07/25/2007 11:35 PM <DIR> .


07/25/2007 11:35 PM <DIR> ..
07/25/2007 11:35 PM 727 Addition.class
07/25/2007 11:35 PM 285 Subtraction.class

2 File(s) 1582 bytes


2 Dir(s) 384,970,752 bytes free

Ø The above added Subtraction class to package pack should be used (called) in
package pack by rewriting the class Use as following :

//Using the package pack


class Use
{
public static void main(String args[ ])
{

INet Solv 132


Core Java

pack.Addition obj = new pack.Addition(10, 15.5);


obj.Sum( );

double result = pack.Subtraction Sub(60,20.5);


System.out.println(“Result = “ + result);
}

Output :
25.5
Result = 35.0

Ø Only one package is added at a time.


Ø import statements eliminates writing the package name before the class
repeatedly.

import pack.Addition;
import pack.Subtraction;

class Use
{
public static void main(String args[ ])
{
Addition obj = new Addition(10, 15.5);
obj.Sum( );

double result = Subtraction Sub(60,20.5);


System.out.println(“Result = “ + result);
}

Output :

25.5
Result = 35.0

Ø But if instead of using both the statements


import pack.Addition;
import pack.Subtraction;

we can write in a single statement as import pack.*;

Ø Let us see what happens

import pack.*;

class Use
{
public static void main(String args[ ])
{
Addition obj = new Addition(10, 15.5);

INet Solv 133


Core Java

obj.Sum( );

double result = Subtraction Sub(60,20.5);


System.out.println(“Result = “ + result);
}

Output :

error: Bad class file : .\Addition.java

How a compiler searches for your program

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

Q: What is java archive file or .jar file ?


R: .jar file is a compressed version of several .java or .class files.
To create a .jar file “jar” command should be used.

Step 2 : Java compiler takes the current directory as the package and searches for the
.class files in the current directory ( c:\psk ).

Example : It searches for Addition.class or Subtraction.java in current directory


C:\psk, but it finds Addition.java and it is failed. Therefore we have an error like

error : Bad class file : .Additon.java

Solution : Go to My Computer and Create a new folder “Pool” in current directory


C:\psk.
Cut Addition.java and Subtraction.java from psk folder and paste it in
C:\psk\pool
Then the program executes properly.

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.

To see the current path the command is echo %classpath%

Let us see the current path


C:\psk\echo %classpath%

INet Solv 134


Core Java

C:\program file\Java\JDK 1.5.0; . ;

Let us set the new path


C:\psk> set class path = D:\zoom; . ; %classpath%

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.

After setting the new path the program executes properly.

How to create an Interface in a package pack

package pack;
public interface MyDate
{
void showDate( ); //public and abstract by default
}

save it as MyDate.java in C:\psk>

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

07/25/2007 11:35 PM <DIR> .


07/25/2007 11:35 PM <DIR> ..
07/25/2007 11:35 PM 727 MyDate .class
1 File(s) 727 bytes
2 Dir(s) 384,970,752 bytes free

Go back to psk directory


C:\psk\pack>cd..
C:\psk>

But an interface needs an implementation class. So write an implementation class for


MyDate interface

An Implementation class for MyDate in package pack

//Program to display the System date and time


package pack;

import java.util.*; //Since Date class is available in java.util


import pack.MyDate;

INet Solv 135


Core Java

public class MyDateImpl implements MyDate


{
public void showDate( )
{
//display System date and time
Date d = new Date( );
System.out.println(d);
}
}

save it as MyDateImpl.java in C:\psk>

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

07/25/2007 11:35 PM <DIR> .


07/25/2007 11:35 PM <DIR> ..
07/25/2007 11:35 PM 727 MyDate .class
07/25/2007 11:35 PM 447 MyDateImpl .class
2 File(s) 727 bytes
2 Dir(s) 384,970,752 bytes free

Go back to psk directory


C:\psk\pack>cd..
C:\psk>

How to use the implementation class of package 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.

INet Solv 136


Core Java

Second Method : Using Inheritance

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.

Save it as Use.java in C:\psk

Compile as following
C:\psk>javac Use.java
C:\psk>java Use
Thu Jul 26 07:36:34 PDT 2007

Creating a Sub package in main package pack

package inet.solv;

public class Sample


{
public void show( )
{
System.out.println(“ Hello Student”);
}
}

save it as Sample.java in C:\psk>

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

07/25/2007 11:35 PM <DIR> .

INet Solv 137


Core Java

07/25/2007 11:35 PM <DIR> ..


07/25/2007 11:35 PM 405 Sample .class
1 File(s) 405 bytes
2 Dir(s) 384,749,568 bytes free

Go back to psk directory


C:\psk\inet>solv>cd..
C:\psk>inet>cd..
C:\psk

How to use methods in simple class of package inet.solv

import inet.solv.Sample;
class Use
{
public static void main(String args[ ])
{
Sample s = new Sample( );
s.show( );
}
}

Save it as Use.java in C:\psk

Compile as following

C:\psk>javac Use.java
C:\psk>java Use
Hello Student

Ø In the above program instead of using import inet.solv.Sample; if we use


import inet.solv.*

An error will be displayed as

Use.java :cannot access Sample


Bad class file : .\Sample.java
File does not contain class Sample
Please remove or make sure it appears in the subdirectory of the
class path

Sample s = new Sample( );

So delete the Sample.java class from C:\psk as following

C:\psk>del Sample*.*

Then compile as following

INet Solv 138


Core Java

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

Use.java : package inet.solv does not exist


import inet.solv.*;

Use.java : cannot resolve symbol


symbol : class Sample
location : class Use
Sample s = new Sample( );
^

Therefore set the class path and compile as

C:\psk>set classpath=D:\abc;.;%classpath%
C:\psk>javac Use.java
C:\psk>java Use
Hello Student

INet Solv 139


Core Java

41. ACCESS SPECIFIERS


Ø An access specifier is a keyword that represents how to access the members of a
class or the class itself.
Ø There are 4 access specifiers in Java

1. private
2. public
3. protected
4. default

Class B Class A Class C


not
available available
private

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.

INet Solv 140


Core Java

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.

//Program to demonstrate Access specifiers


package Same
class A
{
private int a;
public int b;
protected int c=3;
int d=4; //default
}
save it as A.java in C:\psk

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

INet Solv 141


Core Java

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.

Hint : double value = Math.pow(x,n);


double value = Math.sqrt(x);

INet Solv 142


Core Java

42. API DOCUMENT


Ø API document is a HTML file that contains description of all the features of a
software,
a product or a technology.

Save it as java.doc in C:\psk\pool>abc.java

Compile it as the following

C:\psk\pool>javadoc abc.java

Constructing Javadoc inofrmation...


Standard Doclet version 1.4.1

Generating constant-values.html...

Open My Computer go to C:\psk\pool you will find an API document named “java.doc”

INet Solv 143


Core Java

43. ERROR’S
Ø An error in a software is called a Bug.
Ø Removing the errors is called Debugging.
Ø There are 3 types of errors :

1. Compile Time 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).

2. Run Time Error :

Ø 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 :

Ø These are errors in the logic of the program.


Ø Logical errors are not detected by the java compiler or JVM.
Ø By comparing the program output with manually calculated result we can
suspect.

IIQ : 43

Q: What are Checked and Unchecked Exception?


R: The exception which are detected by the compiler at compilation Time are
called Checked Exception.

The exception which are detected at run time by the JVM are called
unchecked exceptions.

Ø Any abnormal event in the program is called an Exception.


Ø All exceptions are represented by classes in java.

INet Solv 144


Core Java

java.lang

Throwable

Exceptions

Errors

RunTime All
All errors Exception Exception

UnChecked Exceptions

IIQ : 44

Q: All exceptions of Sub classes of which Java?


R: Exception Class.

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

INet Solv 145


Core Java

C:\java Ex 44 55 66
Open files
n = 3
a =
close files

Ø If command line arguments are not passed we get an error(exception) in statement


“int a=45\n “ and an abnormally terminates the program.
Ø That is if there is an exception, JVM displays exception details and then
abnormally terminates the program.
Ø The error is :
Ø So the problem is the files and database will not be closed leading to lose of data.

Ø In case of an exception the program should do the following :

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.

Syntax : catch(Exception obj)


{
Statements;
}

3. The programmer should close all files and database inside finally block.

Syntax : finally
{
Statements;
}

Finally block is always executed whether there is an exception or not.

INet Solv 146


Core Java

class Ex
{
public static void main(“Open files”)
{
try
{

System.out.println(“Open files “);


int n = args.length;
System.out.println(“n=” + n);
int a = 45\n;
System.out.println(“a=” + a);
}

catch(Arithematic Exception ae)


{
System.out.println(ae);
System.out.println(“Please type data while running this
program”);
}

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.

INet Solv 147


Core Java

class Ex
{
public static void main(“Open files”)
{
try
{

System.out.println(“Open files “);


int n = args.length;
System.out.println(“n=” + n);
int a = 45\n;
System.out.println(“a=” + a);
}

try
{
int b[ ] = {10, 11, 12};
b[50] = 100;
}

catch(Arithematic Exception ae)


{
System.out.println(ae);
System.out.println(“Please type data while running this
program”);
}

catch
{
aie.printStackTrace( );
System.out.println(“pls see that the array is with the
range”);
}

finally
{
System.out.println(“Close files”);
}
}
}

INet Solv 148


Core Java

Not handling the exception

Ø 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[ ])

INet Solv 149


Core Java

44. throws Statement


Ø throws statement is useful to throw an exception out of a method without
handling it.
Ø throws Exception represents any type of exception to be thrown out without
handling them.

Ø 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 :

//Program to demonstrate throws Statement


class Sample
{
void accept( ) throws IOExcetion //without handling exec it is
thrown
{
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[ ]) throws IOException
{
Sample s = new Sample( );
s.accept( );
}
}

C:\javac Ex.java
C:\java Ex Satish
Hello Satish

INet Solv 150


Core Java

45. throw Statement


Ø This statement is useful to create an exception object and throw it out of try block.

//Program to demonstrate throw Statement


class Demo
{
static void main( )
{
try
{
System.out.println(“Inside demo( )”);
throw new NullPointerException(“My data”);
}

catch(NullPointerException ne)
{
ne.printStackTrace( );
}
}

public static void main(String args[ ])


{
Demo.Demo( ); //Need not create an object since it is static.
}
}

Output :

Inside demo( )
Java.lang.NullPointerException

IIQ : 45

Q: Difference between throws and throw?


R: Throws statement is useful not to handle the exception and throw it out of a
method.
Throw statement is useful to create exception object and handle it.
Both are Quite Contradictory.

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.

INet Solv 151


Core Java

46. Throw of Exception


1. Built in Exceptions

Ø These are the exception already available in java.

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.

2. User defined Exception

Ø The user can also create an exception which are called user defined exception.

Creating User Defined Exception

1. Create user Exception class as a sub class to exception class.


2. Create a default constructor in user exception class super class constructor
from there.
3. To rise an exception create user exception class object and throw it using throw
statement.

//Program to demonstrate user defined exception

class MyException extends Exception


{
private static int accno[ ] = {1001, 1002, 1003, 1004, 1005};
private static String name[ ] = {“Raju”, “Raju”, “Vani”, “Gopal”,
“Vijay”};
private static double bal[ ] = {1234.00, 3000.00, 5462.32, 1004,
1561.01};

MyException( ){ }
MyException(String args[ ])
{
super(str);
}

INet Solv 152


Core Java

public static void main(String args[ ])


{
try
{
System.out.println(“AccNO” + “\t” + “Name” + “/t” + “Balance”);
for(int i=o; i<5; i++)
{
System.out.println(accno[ ] + “/t” + name[i] + “/t” + bal[ ]);

//If balance<2000 then use the exception


if(bal[i]<2000)
{
MyException me = new MyException(“Balance Amount is less “);
throw me;
}
}
}
catch(MyException me)
{
me.printStackTrace( );
}
}

Output :

Exercise of Exception Handling

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.

INet Solv 153


Core Java

47. WRAPPER CLASSES


1. Different applications on internet communicate by sending and receiving data
in the form of objects.
2. java.util class objects handle groups of objects

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 :

char A A field with primitive data type

Wrapper class

Character

In the above example a Character Wrapper Class contains a char primitive


data type with a field which contains a character A.

PRIMITIVE DATA TYPE WRAPPER CLASSES


char Character
byte Byte
int Integer
float Float
double Double
long Long

INet Solv 154


Core Java

Ø All wrapper classes are defined in java.lang package.

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)

Ex: char ch = ‘A’;


Character obj = new Character(ch); or Character obj = new Character(‘A’);

Methods

1. char charValue( )

Returns the char value of the invoking object.

Ex: char ch = ‘A’;


Character obj = new Character(ch);
Character x = obj.charValue( );
System.out.println(x);

Output: A

2. static boolean is Digit(char ch)

Returns true if ch is a digit (0 to 9) otherwise return false.


Ex: 1. char x =’A’;
Character.isDigit(x);

Output : True

2. char x = ‘A’;
Character.isDigit(x)

Output : True

3. static Boolean isLetter(char ch)

Returns true if ch is a letter (A to Z or a to z)

4. static Boolean isUpperCase(char ch)

Return true if ch is an Upper case letters(A to Z)

INet Solv 155


Core Java

5. static Boolean isLowerCase(char ch)

Return true if ch is an Lower case letters(a to z)

6. static Boolean is SpaceChar(char ch)

Return true if ch is coming from SPACEBAR

7. static Boolean is Whitescape(char ch)

Return true if ch is coming from TAB, ENTER, BACKSPACE.

8. static char toUpperCase(char ch)

Return ch into Upper case

9. static char toLowerCase(char ch)

Return ch into lower case.

//Prgram to Test a Char

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( );

//Test the value of ch


if(Character.isDigit(ch))
System.out.println(“It is a digit”);
else if(Charcter.isUpperCase(ch))
System.out.println(“It is Uppercase letter”);
else if(Charcter.isLowerCase(ch))
System.out.println(“It is Lowercase letter”);
else if(Character.isSpaceChar(ch))
System.out.println(“It is coming form space bar”);
else if(“It is white space character”);
System.out.println(“It is white space character”);
else System.out.println(“Soory invalid character”);
}
}

INet Solv 156


Core Java

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)

It is accepting primitive byte num.

Ex: byte b = 99;


Byte Obj = new Byte(b);

2. Byte(String str)

Ex: Byte obj = new Byte(“99”) or String str = ‘99’;


Byte obj = new Byte(str);
IIQ : 46

Q: Which of the wrapper classes contains only one Constructor ?


Or
Which of the wrapper classes does not contain a string parameterized
constructor.

R: Character Wrapper Class.

Methods

1. byte byte Value( )

Returns the value of invoking object as a byte.

2. int compareTo(Byte b)

Ø It compares the numerical value o invoking object with that of ‘b’.


Ø Returns 0 if the values are equal.
Ø Returns a negative value if the invoking object has a lower value.
Ø Returns a positive value if the invoking object has a greater value.
Ø Example :
int n = b1.compareTo(br)
if b1 = = b2; n= =0;
if b1>b2; n>0;
if b1<b2; n<0;
3. static byte parseByte(String str) throws NumberFormatException

Returns the byte equivalent of the number contained in the string specified by ‘str’.

INet Solv 157


Core Java

4. string toString( )

Return a string that contains the decimal equivalent of the invoking object.

5. static Byte ValueOf(String str) throws NumberFormatException

Return a byte object that contains the value specified by the string ‘str’.

//Creating and comparing Byte Object

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( );

//Convert str into Byte object 1st method


Byte b1 = new Byte(str);
System.out.println(“Enter another byte no =”);
str = br.readLine( );

//Convert str into byte object 2nd method


Byte b2 = Byte.valueOf(str);

//Compare the two Byte Objects


int n =b1.compareTo(b2);
if(n==0)
System.out.println(“Both are same”);
else if(n>0)
System.out.println(b1 + “is bigger than “ + b2);
else System.out.println(b1 + “is lesser than “ + b2);
}
}

INet Solv 158


Core Java

III. Integer Class


The integer class wraps a value of the primitive type ‘int’ in an object. An object of type
Integer contains a single field whose type is int.

Constructors

1. Integer(int num)
2. Integer(String str)
Methods

1. int intValue( )

Returns the value of the invoking object as an ‘int’;

2. int compareTo(Integer obj)

Compares the numerical value of the invoking object with that of “obj”. Returns 0, -ve
or +ve value.

3. static int parseInt(string str) throws NumberFromatException

Returns int equivalent of the string str.

Ex: String s= “123”;


int n = Integer.parseInt(s);

Output : 123
Ex: String s =”Hello”;
int n = Integer.parseInt(s);

Output : NumberFormatException

4. String toString( )

Returns a string form of the invoking object.

5. static Integer valueOf(String str) throws NumberFormatException

Returns an Integer object that contains the value shown by str.

6. static String toBinaryString(int i)

Returns a string representation of the integer argument in base 2.

7. static String toHexString(int i)

Returns a string representation of the integer argument in base 16

INet Solv 159


Core Java

8. static String toOctalString(int i)

Returns a string representation of the integer argument in base 8

//Converting decimal format into another system

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( );

//Convert str into decimal int


int n = Integer.parseInt(str);
System.out.println(“In decimal = “ + str);

//Convert into other systems


str = Integer.toBinaryString(n);
System.out.println(“In binary =” + str);

str = Interger.toOctalString(n);
System.out.println(“In Octal =” + str);

str = Integer.toHexString(n);
System.out.println(“In Hexa = “ + str);
}
}

INet Solv 160


Core Java

IV. Float Class


The Float class wraps a value of primitive type ‘float’ in an object. An object of type
Float contains a single field whose type is float.

Constructors

1. Float(float num)
2. Float(String str)

Methods

1. float floatValue( )

Return the value of the invoking object as a float.

2. double doubleValue( )

Returns the value of the invoking object as a double.

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

Returns the float equivalent of the string str.

5. String toString( )

Returns the string equivalent of the invoking object.

6. static Float valueOf(string str) throws NumberFormatException

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)

INet Solv 161


Core Java

Methods

1. double doubleValue( )

Return the value of the invoking object as a double.

2. float floatValue( )

Returns the value of the invoking object as a float.

3. int compareTo(Double d)

Compares the numerical value of the invoking object with that of ‘d’. Return 0, -ve or
+ve values.

4. static double parseDouble(String str) throws NumberFormatException

Returns the double equivalent of the string str.

5. String toString( )

Returns the string equivalent of the invoking object.

6. static Double valueOf(string str) throws NumberFormatException

Returns the Double object with the value specified by String str.

VI. Math Class

The class Math contains methods for performing numerical operations

Methods

1. static double sin(double arg)

Returns the sine value of the arg. arg is in radians.

2. static double cos(double arg)

Returns the cosine value of the arg. arg is in radians.

3. static double tan(double arg)

Returns the tangent value of the arg. arg is in radians.

4. static double log(double arg)

INet Solv 162


Core Java

Returns the natural algorithm value of the arg. arg is in radians.

5. static double pow(double x, double n)

Returns x to the power of n value.

6. static double sqrt(double arg)

Returns the square root arg.

7. static double abs(double arg)

Returns the absolute value of arg.

8. static double ceil(double arg)

Returns the smallest integer which is greater or equal to arg.


Ex: Math.ceil(4.5) is 5.0

9. static double floor(double arg)

Returns the greatest integer which is lower or equal to arg.


Ex: Math.floor(4.5) is 4.0

10. static double min(arg1, arg2)

Returns the minimum of arg1 and arg2

11. static double max(arg1 and arg2)

Returns the maxmimum of arg1 and arg2.

12. static double round(arg)

Returns rounded value of arg.


Ex: Math.round(4.6) is 5.
Ex: Math.round(4.4) is 4.

13. static double random( )

Returns a random number between 0 and 1.

14. static double toRadians(double angle)

Convert angle in degrees into radians

15. static double toDegree(double angle)

INet Solv 163


Core Java

Convert angle in radians into degrees.

//Program to generate random numbers between 0 and 1


class Rand
{
public static void main(String args[ ])
{
while(true)
{
double d = 10*Math.random( );
int n = (int)d;
System.out.println(n);

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.

INet Solv 164


Core Java

48. COLLECTION CLASSES


Ø We can use an array to store a group of objects but there are 2 limitations here

1. We cannot store different class type objects in same array.


2. Methods are not available to insert or delete the objects in the middle of the
array.

//Program to demonstrate above limitations. To store 100 Emp class


objects

Employee arr[ ] = new Employee[100];


for(int i=0; i<100; i++)
{
arr[i] = new Employee(data);
}

Ø A collection object or container object is an object that stores a group of other


objects.

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

Q: What is Collection Frame Work?


R: It is a class library to handle groups of objects. Collection frame work is
implemented
in java.util package.

Ø A collection object stores only references of other objects.


Ø The above collection object is waste of memory. Because if each object is of 2KB
then the 4 objects takes 8KB and to store these 4 objects, Collection objects has to

INet Solv 165


Core Java

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

1. Sets : It represents a collection of elements. Here duplication is not allowed.


2. Lists : It represents a ordered collection of elements. Here duplication is
allowed.
3. Maps : It stores the elements in the form of KEY-VALUE pairs.
Ex: Key ---> Hall Ticket No, Value ---> Result

Ø Collections cannot store primitive data types it can store only objects.

IIQ : 48

Q: Which of the collections do not allow duplicate elements?


R: Sets

1. Stack

Ø A stack represents a group of elements arranged in Last In First Out(LIFO).


Ø Inserting and deleting the elements from the stack are done only from one side,
called TOP of the stack.
Ø The Other side of the stack is closed.
Ø Inserting an element into the stack is called PUSH operation.
Ø Deleting an element from the stack is called POP operation.
Ø Searching an element in the stack is called PEEP operation.
Ø Example : 1. A pile of plates in a Cafeteria
2. Shunting of Coaches to a railway engine
3. Bangles to a hand.
4. Stack of charis.

INet Solv 166


Core Java

1. To create a stack

stack st = new stack( );

2. To know whether a stack is empty or not, use empty( )

boolean b = st.empty( );

3. To push an element into a stack

st.push(element);

4. To pop an element from a stack

Object element = st.pop( );

5. To search for an element in the stack

int i = st.search(element);

This method returns -1 if the element is not found.

//Program to demonstrate stack with int values

import java.lang.*;
import java.util.*;
class StackDemo
{
static void stpush(stack st, int a)
{
st.push(new Integer(a));
}

static void stpop(stack st)


{
Integer a = (Integer)st.pop( );
System.out.println(“Popped =” + a);
}

static int stsearch(stack st, int a)


{
int i = st.search(new Integer(a));
return;
}

public static void main(String args[ ]) throws Exception


{
//vars
BufferedReader br = new BufferedReader(new

INet Solv 167


Core Java

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”);

choice = Integer.parseInt(br.readLine( ));

//perform a task depending on choice


switch(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

INet Solv 168


Core Java

Note : Recompile with


C:\psk>java StackDemo

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

Linked List ll = new LinkedList( );

2. To add elements(object) to a linked list

ll.add(element);

To add element in 2nd position.


ll.add(2, element);

3. To remove the element from the linked list.

ll.removeFirst( );

To remove last element from the linked list


ll.removeLast( );

To remove 2nd element.


ll.remove(2);

4. To change the 2nd element with a NEW element.

ll.set(2, NEWelement);

//Program to demonstrate a linked list with strings.

import java.io.*;
import java.util.*;
class LLDemo
{
public static void main(String args[ ]) throws IOException
{
//Create an empty linked list

INet Solv 169


Core Java

LinkedList ll = new LinkedList( );

//Store names of countries into ll


ll.add(“America”);
ll.add(“India”);
ll.add(“Japan”);
ll.add(“China”);
ll.add(“Korea”);

//display the linked list contents


System.out.println(“List = “ + ll);

//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 = ”);

choice = Integer.parseInt(br.readLine( ));

//perform a task depending on choice


switch(choice)
{
case 1 :
System.out.print(“Enter element = ”);
element = br.readLine( );
System.out.print(“Enter position =”);
pos = Integer.parseInt(br.readLine( ));
ll.add(pos, element);
break;

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( );

INet Solv 170


Core Java

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.

1. To sort the elements of an array into ascending order

Array.sort(arr);

2. To sort only a range of elements of the array .

Array.sort(arr, start, end);

This sorts the elements of “arr” starting from start till “end-1” elements.

3. To search for an element in an array

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.

4. To compare two arrays to know if they are same or not

Arrays.equals(arr1, arr2);
This returns true if arr1 and arr2 are same else it returns false.

INet Solv 171


Core Java

//Program to demonstrate sorting and searching in an array.

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( ));

//Create an array with size n


int arr[ ] = new int[n];

//Store elements into the array


for(int i=0; i<n; i++)
{
System.out.println(“Enter Elements”);
arr[i] = Integer.parseInt(br.readLine( ));
}

display(arr);

//Sort into ascending order


Arrays.sort(arr);
System.out.println(“Sorted array is”);
display(arr);

//Search for an element in arr


System.out.println(“Enter element to search”);
int x = Integer.parseInt(br.readLine( ));
int pos = Arrays.binarySearch(arr, x);

if(pos < 0)
System.out.println(“Element not found”);
else
System.out.println(“Element found at positon” + (pos+1));
}

static void display(int arr[ ])


{
for(int i : arr)
System.out.println(i);
}
}

INet Solv 172


Core Java

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

//Program to demonstrate Cloning – 1st Method

class Employee implements Cloneable


{
int id;
String name;

Employee(int i, String n)
{
id = i;
name = n;
}

void display( )
{

INet Solv 173


Core Java

System.out.println(“ID =” + id);
System.out.println(“Name = “ + name);
}

//Programmer’s own method


Employee myClone( ) throws CloneNotSupportedException
{
return (Employee)super.clone( );
}
}

class CloneDemo
{
public static void main(String args[ ]) throws
CloneNotSupportedException
{
System.out.println(“Before Cloning”);
Employee e1 = new Employee (10, “Satish”);
e1.display( );

//To clone e1 and produce e2


System.out.println(“After Cloning”);
Employee e2 = e1.myClone( );
}
}

Output :

Before Cloning
id = 10
Name = Satish

After Cloning
id = 10
Name = Satish

Ø Clone method of object class is used in cloning.


Ø Why the below statement is return

class Employee implements cloneable

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.

INet Solv 174


Core Java

An Interface without any methods or members is called Tagging or Marking


Interface.

Tagging Interface specifies a special purpose for the class objects.

Example : Cloneable, Serializable

Ø Why the below statement is return

Employee myClone( ) throws CloneNotSupportedException


{
return (Employee)super.clone( );
}

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”.

Ø The above program can be written as below :

//Program to demonstrate Cloning – 2nd Method

class Employee implements Cloneable


{
int id;
String name;

Employee(int i, String n)
{
id = i;
name = n;
}

void display( )
{
System.out.println(“ID =” + id);
System.out.println(“Name = “ + name);
}

//Overriding super class clone method


protected Object Clone( ) throws CloneNotSupportedException
{
return super.clone( );
}
}

INet Solv 175


Core Java

class CloneDemo
{
public static void main(String args[ ]) throws
CloneNotSupportedException
{
System.out.println(“Before Cloning”);
Employee e1 = new Employee (10, “Satish”);
e1.display( );

//Convert object class as Employee class


System.out.println(“After Cloning”);
Employee e2 = (Employee)e1.Clone( );
e2.display( );
}
}

Output :

Before Cloning
id = 10
Name = Satish

After Cloning
id = 10
Name = Satish

INet Solv 176


Core Java

50. Important Interview Questions (IIQ’s)

1Q: What is Hand Shaking Mechanism?


R: Two computers establishing a connection, communication with each other and finally disconnecting
from each other. (Decides when to send or receive data )

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

2) .exe file is System Dependent


.class file is System Independent

4Q: Why pointers are not available in JAVA ?


R: 1) Pointers leads to confusion for a programmers, even both beginners and experience persons face
problems.
2) Pointers can easily crash the program. Crashing means terminating the program abnormally.
3) By suing pointers virus and hacking programs can be developed. i.e there is no security. Because
by using pointers we can change the data in memoy.

5Q: What is the difference between a Function and a Method ?


R: Method
1) In java we have no functions
2) A method is a function written inside a class i.e in java we write functions only within a class and
called as member function
Function
A function can be written anywhere in the program.

6Q: What is an API (Application Programming Interface) document ?


R: API document is a HTML file that contains description of all the features of a software, a product or a
technology.

7Q: What is the difference between #include and import ?


R:
#include :

#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.

INet Solv 177


Core Java

8Q: What is JRE ?


R: JRE = JVM + Java library

9Q: What happens if we do not write string args[ ] after main ?


R: JVM will compile the main( ) but it will not run.

10Q: 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.

11Q: 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.

12Q: What is the result of the following if a=7

++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:

15Q: DO WHILE or WHILE which is efficient?


R: While loop provides better control for programs right from the beginning of execution so it is more
efficient than do… while.

16Q: Go to statements are not available in java. why?


R: 1. GO TO stmts lead to confusion for a programmer.
2. GO TO stmts form infinite loops.
3. GO TO stmts make documentation difficult.
4. GO TO ‘S are not part of structural programming.bcoz of above reasons GO TO has been
eliminated.

17Q: Difference between System.exit(0) and System.exit(1)


R: System.exit(0) represents normal termination of a program.
System.exit(1) represents termination due o errors in program.

18Q: What is the difference b/w System.out and System.err?


R: System.out : It is used to display general messages on the monitor.

INet Solv 178


Core Java

System.out.println(“Hello”);
System.err : It is used to display the error message on the monitor.
System.out.println(“Error Message”);

19Q: What is Hash Code?


R: Hash Code is a unique id number allotted by JVM to an object. Hash code is also called
as Hash code.

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.

21Q: What is String Constant Pool?


R: When JVM creates string object it stores the string object into a separate memory block which is
called String Constant pool.

22Q: What is the difference between the following 2 statements:


1. String s = “Hello”;
2. String s = new string(“Hello”);

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.

23Q: Difference between String and StringBuffer?


R: 1. String class objects are immutable(i.e cannot be changed)
StringBuffer objects are mutable.
2. Data manipulation methods(delete( ), reverse( ) ) are not available in strings. They
are available in StringBuffer.

24Q: What is an SRS (Software Requirement Specification)?


R: SRS is a document that contains client requirements along with the strategies(plans) to full fill those
requirements. SRS is prepared by PROJECT LEADER.

25Q: What is an SDS (Software Design Specification)?


R: SDS is a document that contains IO Screens, Pseudo code (algorithms), Data Flow Diagrams(DFS’s),
Backend Database Description etc., It contains the logic part that contains how to solve a particular
problem. SDS is written by MODULE LEADER.

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.

INet Solv 179


Core Java

OBPL follow all the features of OOPs except Inheritance. Example Javascript and
VBScript.

27Q: Is class is a data type or not ?


R: Yes, class is a user defined data type.

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.

30Q: In how many ways we can create an object in JAVA?


R:
1. Using new operator

Syntax : classname obj = new classname( );


Example : Employee obj = new Employee( );

2. Using Factory Method

Syntax : NumberFormat obj = NumberFormat.getNumberInstance( );

3. Using newInstance( )

Ex : class c = class.forName(“Employee”);
Employee obj = c.newInstance( );

In class.forName(“Employee”) statement class is a Class, forName is a Factory method and


Employee is a string.

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

Cloning is a mechanism to obtain exact copy of an existing object.


Example : Employee e1 = new Employee( );
Employee e2 = e1.clone( );
In above example, a new object e2 is created by cloning e1(existing object).

31Q: Is it possible to pass complete arrays to method and display it?


R: Yes it is possible.

INet Solv 180


Core Java

Example 1: Passing one dimensional arrays


int[ ] myMethod(int arr[ ]);
Example 2: Passing two dimensional arrays
int[ ][ ] myMethod(int arr[ ][ ]);

Latest IIQ : 32

Q: What is Object Graph ?


R: It is a graph showing relationship b/w different objects in memory.

33Q: What is the advantage of Inheritance?


R: Reusability of the code is the main advantage. Because of this reusability the overall productivity of a
programmer and also of the company will be increased.

34Q: What is a Method Signature?


R: Method name and its parameters combinedly are called Method Signatures.

35Q: Difference between Method Overloading and Method Over Riding?


R: Functional Difference :

Method Overloading is used to extend an already available features of the software.


Method Overloading is Code Refinement.

Method Over Riding is used to provide a different implementation for the same
feature. Method OverRiding is Code Replacement.

36Q: Difference between Primitive and Advanced data types?


R: Primitive data types
These data types represents single values.
Methods are not available to handle primitive data types.
Ex : char, byte, short, int, long, float, double, Boolean.

Advanced data types


These data types can store several values.
Methods are also available to handle advanced data types.
Ex : any array, any class(String, employee…)

37Q: 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.

38Q: How can you make the programmer to implement only the method of your class ?
R: By writing an abstract class or an Interface

INet Solv 181


Core Java

39Q: What is the difference between abstract class and Interface ?


R: 1. A programmer creates an abstract class when there are some common features shared by all the
object.
A programmer writes an Interface when array feature is implemented differently for different
objects.
2. When abstract class is written it is the duty of a programmer to provide subclasses to it.
When Interface is written any 3rd party Vendor can provide implementation classes to it.

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).

41Q: Multiple Inheritance is not available in Java Why?


R: 1. Multiple Inheritance leads to confusion for a programmer.
2. Multiple Inheritance can be achieved by suing Interfaces.
Ex: class Z implements A, B (Here A, B are interfaceses but not super classes.)
3. Multiple Inheritance can be achieved by repeated use of Single Inheritance.

Ex : The above statement can be written as


class B extends A //valid , Single inheritance 1
class Z extends B //valid, Single inheritance 2

42Q: What is java archive file or .jar file ?


R: .jar file is a compressed version of several .java or .class files. To create a .jar file “jar” command
should be used.

43Q: What are Checked and Unchecked Exception?


R: The exception which are detected by the compiler at compilation Time are called Checked Exception.
The exception which are detected at run time by the JVM are called unchecked exceptions.

44Q: All exceptions of Sub classes of which Java?


R: Exception Class.

45Q: What is throwable?


R: Throwable is a class that represents all exceptions and errors in java.

INet Solv 182


Core Java

46Q: Which of the wrapper classes contains only one Constructor ?


Or
Which of the wrapper classes does not contain a string parameterized constructor.
R: Character Wrapper Class.

47Q: What is Collection Frame Work?


R: It is a class library to handle groups of objects. Collection frame work is implemented in java.util
package.

48Q: Which of the collections do not allow duplicate elements?


R: Sets

INet Solv 183

S-ar putea să vă placă și