Você está na página 1de 191

COREJAVA

JAVA
Object Oriented Program is a programming approach in which a problem domain is characterized
as a set of objects that have a specific attributes and behavior. The objects are manipulated with a
collection of functions called methods or services. The objects are classified into classes and subclasses.
(or)
An Object Oriented Programming organizes a program around its data, i.e., objects and a set of
well-defined interfaces to that data. An object-oriented program can be characterized as data controlling
access to code.
Java is an Object Oriented Programming (OOP) language used to design an application, which will
run securely over the network1 and work on wide range of platforms.
J2SE: - J2SE stands for Java 2 Standard Edition, it is a specification used to develop fundamental java
application they may be standard or network.
J2SE= Core Java + Advanced Java
J2SE:- Java2 StandardEdition
J2EE:- Java2 EnterpriseEdition
J2EE: - J2EE stands for Java 2 Enterprise Edition, it is a specification used to develop business solutions
for network (or) J2EE is a specification that provides an environment to run the web components and the
enterprise components.
J2ME:- Java2 MicroEdition
J2ME: - J2ME stands for Java 2 Micro Edition, it is a specification used for developing wireless and
Embedded System. Embedded System is software, which directly installed into hardware.
Difference between Java1.4.1. and Java1.5
[www.sunjava.com,www.javasoft.com]
Core Java Desktop Java
NIC Network Interface Card
NovelNetwork:- Net based softwaress
Ex: - Windows NT, UNIX.
Protocol: - This is also a program; it is a specification of set of rules to be followed by a computer in
network.
When to send/receive data
How to send/receive data
Hand Shaking: - This means two Computers establishing a connection
communicating with each other and finally disconnecting is called
Frame
Hand shaking.
A Packet represents a group of bytes. IP means Internet Protocol
Packet
address this is unique address this is given to Computers.
TCP/IP:- Transmission Control Protocol/Internet Protocol.
Client: - A Client is a machine that sends a request for some services to other Computer.
Server: - Server is a machine that receives requests from the Clients and provides services to the Client
requests.
The main advantage of a network is resources sharing.
Web application:- A web application is a collection of Servlets, HTML pages, Classes and other resources
that can bundle and run on the multiple Containers from multiple Vendors.
ResourcesSharing: Sharing memory
1

1 Network: - Complete network is interconnection & Autonomous systems that are used for communication or

exchange of information between the two systems in the network, the systems, which are connected in the network,
are called as hosts.
Page 1 of 191

COREJAVA

Sharing data
Sharing software
Sharing hardware
Sharing Processor

1969 Department of Defence (DOD), USA, Ken Thompsonis introduced network. This network is
called ARPANET.

AT&T Advanced Telephone Communication & Technology USA based Telephone Company.
Hyundai, British Telecom are also Telephone companies, these three companies are giant of the
Telephone.

AT & T

Satellite

Hyundai

50GBPS

Server
ISP

British Telecom

Another Computer
ISP: - It stands for Internet Service Provider. ISP is a person or an organization, who provides connection
into internet. ISP should take direct connection to internet. (www.internic.com).
Bandwidthis a group of frequency.
American Congress Library is a biggest Library in the World; the second biggest Library is Lenin
Glad Library in Masco, (Russia).
Q) Whatis an Interface?*****
Ans: - An Interface defines a protocol of behavior that can be implemented by any class anywhere in the
class hierarchy. An interface defines a set of methods but doesnt implement them. A class that
implements the interface agrees to implement all the methods defined in the interface, thereby agreeing
to certain behavior.
An interface is a named collection of method definitions (without implementations). An interface
can also declare constants.
Internet: - Internet is a network of Computers existing on the earth. Internet is a global network of all
networks existing on the earth.
ConnectingInternettypes:DialupConnection: Dialup connection main advantage is affordable to any one.
Disadvantage of Dialup connection is slow.
There is no security for data.
2. Leasedline Connection:- It is a direct connection to internet.
Page 2 of 191

COREJAVA
Advantages: High Security for data
Lightening Speed (i.e. high speed)
Disadvantages: Highly expensive.
The web browser2 software is installed on Internet Client.
Ex: - Internet Explorer, Mozilla, Fire fox, Netscape Navigator etc
The software that should be installed on Internet Server is Web Server.
WebServer:- A web server is a server that provides the implementation of HTTP protocol.
Ex: - Internet information Server (IIS), Apache Web Server, etc
Application Server: - An Application Server is a product that provides the facilities like taking care of
transactions, taking care of security and simplifies the development of business logic (or) Application
servers provides you with common middleware services, such as resource pooling, networking and
more. Application server allows you to focus on your application and not worry about the middleware you
need for a robust server side deployment.
Ex: - Microsoft Transactions Server (MT Server) from Microsoft, EJB containers like WebLogic,
WebSphere, JBoss etc
Hypertext Transfer Protocol (HTTP) is widely used protocol on internet.
File Transfer Protocol (FTP), when we download a file from Internet.
Simple Mail Transfer Protocol (SMTP) is used to send mails on the internet.
Post Office Protocol (POP) is used to receive mails.
Programmerhas: 1. To develop a web browser
2. To increase the capabilities of web browser
3. To develop a web server
4. To increase the capabilities of the web server
5. To develop protocol
Translator is a program that converts a computer program into machine language (Electric Pulses).
There are 3 types of translators 1. Interpreter
Interpreter translates line by line of computer program
2. Compiler
Compiler translates all lines of program at a single time
3. Assembler
Assembler translates assembly language into machine language

x.c

x.obj

x.exe

Machine code
Convert the
Header file

Full pledged
machine code
language
instructions

C, C++, are not portable3 programs, they are system dependent because they can be executed
only on that system where they are developed.
The first microprocessor is - 4 0 0 4
The next microprocessors are follows as below
8008
8085
8086
80286
2

Web browser: - The web browser is a GUI based software is installed on Internet Client that allows the user to

navigate www and web pages on Computer screen.


3

Portability: - Yielding on any Computer


Page 3 of 191

COREJAVA
80386
80486
8 0 5 8 6x, PI, PII, Celeron, PIII, AMD, PIV, PIV Pro

WhyJavais suitablefor Internet

x.java

x.class

PIV

JVM

It consists
byte code
format

JVM

Cyrix

JVM
The size of eachinstructionis 1 byte or 8 bits.
There are around 210 byte codeinstructionsare available

Byte code instruction is understand by JVM4 (JavaVirtualMachine).


Componentsof JVM
JVM

Class
Execution
Engine

Byte code
verifier

Security
Manager

Garbage
Collector

Sun Microsystems is developed the JVM program.


JVM convert byte codeinstructioninto machinecode.
JVM understand every byte code instructions.

Celeron

JVM:- Java Virtual Machine is a program. It is not a machine.


Page 4 of 191

COREJAVA
JVM will understand the byte code instruction & it will convert the byte code instructions into PIV
processor understandable machine language instructions.
JVM will convert the byte code instructions into any type of processor understandable machine language
instructions.
Javaprogramssystemindependent.
JVMis systemdependent.
Depending on operating system we have to download the operating system related JVM
program.
.classfile is systemindependent.
JVM is making as Java system independent.
Portability means giving same results on any type of system or machine.
SecurityProblemson Internet:1. Evesdropping:- Reading others data illegally on Internet, is called Eves dropping.
2. Tampering:- Not only reading others data but also modifying it on Internet, is called Tampering.
3. Impersonation:- A person acting as another person on Internet is called impersonation.
4. Virus:- Virus is a harmful program that can damage data, software & hardware of a system.
Virus was first developed by Pakistanis. Virus will spread to *.exe, *.sys, *.doc. but *.txt files
cannotcarryvirus.
Solution for eves dropping & tampering encryption/decryption. Encryption means converting data
into understandable data. Decryption means converting data back to readable form.
For impersonation, solution is digital signature file, containing personal information for identify
the person in encrypted form. Digital signatures are developed in java.
Solution for virus is .class file. Security manager is program that identifies illegal code and
information security polices. A .classis a text file viruscant be affected.
WhyJavais suitablefor Internet: Security problems on Internet are eliminated through java.
Java is a system independent; Java is executable on any platform.
In 1990, Sun Microsystems inc., USA is developed software for remotes. (James Gosling).
In 1993, Oak language is developed, by that time some company is registered Oak name, for
this reason they named as Java.
In 1995, Sun world conference has given entire details of Java.
Featuresof Java: 1. Simple: - Java is a simple programming language, learning and practicing java is easy because of its
resemblance (Similarity) with C, C++.
2. ObjectOriented:- Unlike C++, Java is a purely object oriented programming language.
Java= C++- Complexity
An object is existing of everything in the world is an Object. An object has properties & performs
actions.
Objectinitializationprocess:Default values initialization expressions initialization blocks constructors
Defaultvalues:float, double
0.0F,0.0
boolean
false
Reference variable
null (not referring any object)
Char
\u000 (or) a space
String
Null
My class
Null
3. Distributed: - Java is designed for use on networks. It has extensive libraries, which work in agreement
with TCP/IP5. Java uses protocols like HTTP6 & FTP.

5
6

TCP/IP:- Transmission Control Protocol/Internet Protocol.


HTTP:- Hypertext transfer Protocol.
Page 5 of 191

COREJAVA
4. Robust: - Java programs will not crash because of its exception handling and its memory management
feature.
Pointersare eliminatedfromJavadueto: 1. These are lead to complex programs
2. Using pointers harmful programs are written.
3. Pointers may crash a program.
Method is a function; Function represents set of instructions to perform the results. A method
must be starts with lowercase. A method will returns a void or any valid return type. A method can be
inheritedandit canbe overloadedor overridden.A methodhas calledexplicitly.
Functioncanbe writteninside& outsideof the class, but a method is a function, it is writtenonly insideof
a class. A functioncan be called& executeditself.
Q) Whatis the differencebetweenmethodand function?*****
Ans: - A method is a function written only inside of a class but functions can be written any where in class
i.e. inside or outside of the class. In java we will write only methods. Writing a function outside the class
is not possible in java.
Methods or functions can store only some temporary variables or local variables, but not permanent
variables.
A class is a model or idea or plan to create objects or Class is a group of objects. Class doesnt
exist really becauseit is only an idea but objectsexist really.
A class will also contain variables & methods.
An object will also contain variables & methods.
In every java program we must create a single class.
C++ is not purely Object oriented programming
Internet is a distributed technology.
Java is suitable for distributed technology.
Robust means strong, in java we can write strong programs.
Exception means runtime error
JVM will allot memory to what ever we required memory.
Unused memory released or free it by JVM
Garbage Collector will delocate or removes memory for unreferenced or unused objects and
variables.
Garbage Collector can be called explicitly but there no gurantee that the garbage collector
executes or not at that point.
Q) Whatalgorithmis usedby garbagecollectorto removevariablesor objectsfrommemory?*****
Ans:- Mark & Sweep algorithm.

Q) Whatis the differencebetween.exe and.classfile? *****


Ans: - .exe file contains machine language instructions for the microprocessor. It is system dependent.
.class file contains byte instructions for JVM. It is system independent.
In JVM class loader sub system will allot the memory required for program.
Garbage memory delocates the memory.
5. Secure: - Java is designed for use on internet. Java enables the construction of virus-free, tamper free
systems.
6. Architecture Neutral: - Javas byte code is not machine dependent. It can be run any machine with any
processor and any operating system.
7. Portable: - Java does not have implement-dependent aspects. So the results will be same on all
machines. Portable means yielding same results on different machines.
8. Interpreted:- Java programs are compiled to generate bye code. This byte code can be downloaded and
interpreted by the interpreter. JVM contain interpreter.

Page 6 of 191

COREJAVA
9. High performance:- Along with interpreter there will JIT (Just in time compiler), which enhances the speed
of execution.
Variable: - An item of data named by identifier. Each variable has a type, such as int or object and a
scope.
ReferenceVariable:- A data element whose value is in an address.
LocalVariable:- A data item known within a block, but inaccessible to the code outside the block.
For example, any variable defined within a method is a local variable and cant be used outside
the method.
A local variable life cycle ends when the execution of method completed. A local variable should
declared within a method body and it must be initialized when we are declaring in a method, because it
doesnttakesdefault values.
PathVariable:- It is exterenal command file. A pathvariableis usedto specifywherethe executablefiles are.
Ex: - javac.exe, java.exe, javap.exe etc.
Argument:- A data item specified in a method called an argument. An argument can be a literal value, a
variable or an expression (or) an argument is a value that is passed to the method when it is invoked.
Parameter:- While defining a method, variables passed in the method called as parameter (or) Parameters
are variables defined by method that receives values when a method is called.
Parameters are useful to pass the variables from objects to the constructor.
Method parameters are local variables to receive the data from out side for method.
Parametersare usefulto receivethe valuesfromoutsideto mainmethod.
Whatis the differencebetweenparameterandargument?*****
Ans: - While defining method, variables passed in the method called as parameter. While using those
methods, values passed to those variables called arguments.
Process: A virtual address space containing one or more threads (or) a program under execution is also
called as process.
Peer: - In networking, any functional unit in the same layer as another entity.
Expression:- An expression is a series of variables, operators, and methods calls, (constructed according
to the syntax of the language) that evaluates to single value.
Howwouldyou detectandminimisememoryleaksin Java:In Java memory leaks are caused by poor program design where object references are long
lived and the garbage collector is unable to reclaim those objects.
Detectingmemoryleaks:
Use tools like JProbe,OptimizeIt etc to detect memory leaks.
Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat,
netstat etc on UNIX systems.
Write your own utility class with the help of totalMemory() and freeMemory()methodsin the Java Runtimeclass.
Place these calls in your code strategically for pre and post memory recording where you suspect to be
causing memory leaks. An even better approach than a utility class is using dynamic proxies or Aspect
Oriented Programming(AOP) for pre and post memory recording where you have the control of activating
memory measurement only when needed.
Minimisingmemoryleaks:
In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to
objects of a short life cycle. This prevents the objects with short life cycle being garbage collected. The
developer must remember to remove the references to the short-lived objects from the long-lived objects.
Objects with the same life cycle do not cause any issues because the garbage collector is smart enough
to deal with the circular references.
JVMArchitecture:- JVM 1.4.1 version developed by Hotspot.

Page 7 of 191

COREJAVA
Class
Loader
Subsystem

Class files

Method
area

Heap

Java

PC

Stacks

registers

Native
method
stacks

runtime data areas

Native method
interface
Execution Engine

Native method
libraries

Classloadersubsystemdoesthe followingthings:1. It will load .class file into memory (RAM)


2. It will verify byte code of that .class file.
3. It will allot the required memory for the program.
This memory is divided into five parts; they are called runtime data areas.
1. Methodarea: - It stores classcode, staticvariables, staticblocks and methodcode.
2. Heaparea: - Objects are created on Heap. JVM creates objects on Heap.
3. Java Stacks:- Java stacks are used to executethe java methods. Java stackswill haveframes. On each frame
a separatemethodis executed.
4. PC Registers:- These registers contain the addressof that instructionto be executedby the processor.
5. Native method stacks: - It is a method written in a language other than java. Native method stacks places
when native methods are executed.
Note: - Native method interface linksheaderfiles to a nativemethodwhile it is being executing.
Execution engine contains interpreter & JIT compiler, which translates byte code into machine
language.
How JIT compiles converts byte codes.
Ex: print a; 2sec
For Interpreter
print b; 2sec
Repeat the loop 10times;
JIT Compiler Processor
print a; 2 + 2
memory

Hotspot is the block code of given to JIT compiler for execution.


10. Multithread:- Thread means an execution or processing group of statements. Executing different parts
of a program simultaneously at a time by using more than one thread is called Multithreading. This is an
essential feature of to design server side programs.
11. Dynamic: - It means at runtime, we can develop programs in java, which dynamically change on
Internet. (Ex: Applets).
In java entire memory will be dynamic memory.
JavaProgramming: Comments represent description of the features of a program.

The main advantages of comments are readability7 of the program is increased.

There are 3 types of comments in Java. They are


7

Readability = Understandability.
Page 8 of 191

COREJAVA
1. Singleline comments:- It represents only one line as comment. Single line comments start with //.
Ex: //Welcome INet Solv
//welcome to Java
2. Multi line Comments:- They represents a group of lines as comment. They starts with /* and end with */
Ex: - /*Welcome to India*/
3. JavadocumentationComments:- They starts with /** and end with */.
Ex: - /**Welcome to BTCE*/
These comments are useful to create .html documents from .java programs.
API Document: - API stands for Application programming Interface. It is a .html document that contains
description of all the features of a software or a product or a technology. API document does not contain
code. Javadoc complier is used for this.
Comments are non executable statements. These 3 types of comments are not executable by java
compiler or JVM compiler.
In Java we can define/write any number of classes in a single class. Out of n number of classes
we are writing in a single class only one can be defined as public class, because the name of the class
should be public class.
If we need all the classes as public we have to decalred/write sepeartely each class as public.
ExampleProgram:/*This is our first Java program.
To display a message
Author: INet Solv team
Version8: V 1.0
Project: Proxyz 1.11
*/
//Starting a program in Java
import java.lang.system;
import java.lang.string; or in the place of two steps directly we can write as below
import java.lang.*9;
class First
Java library
{
10
main ()
It contains group of packages
{
--------------Packages
--------------It is a sub directory & it contains
--------------group of class/interfaces
}
Class/Interfaces
}

It contains group of methods


Methods

Q) Whatis the differencebetween#includeandimportstatements?*****


Ans: - #include makes C/C++ compiler to copy the header file into a C/C++ program. Thus it wastes the
memory and processor time.
import will makes the JVM to go to a particular class, it executes the code there and then it
comeback to the program and substitute the results in the program.
JRE:- It stands for Java runtime environment.
JRE= JVM+ Javalibrary
If java programs have to run we required the JVM and java library. JVM will starts execution of
java program from main method only.
8

VersionV 1.0: - 1 represents major version and 0 represents minor version.


* means all the class/interfaces are java.lang are known available.
10
main() is a called as main method. It is a group of statements.
9

Page 9 of 191

COREJAVA
String represents group of characters.
Array represents group of elements. Array denotes with [ ]
The values passed to the main method are called command line arguments.
Void means no value (i.e. it returns no value).
import java.lang.*;
class First
{
main11()
{
------------------------------------}
}
To call methodthereare twosteps:1. To create on object to the class to which method belongs
Classname obj = new12 Classname();
Ex: - First f = new First();
(f = object)
2. Call the method using object name.methodname
Obj.methodName();
Ex: - f.main();
Objectsare createddynamically(runtime)by JVM
Staticmethod:- It is a method that can be called and executed without creating an object.
Public: - It means available outside the object. JVM will not run the public without writing String args[].
JVM could not executes the main method.
For single character in java we have to write in single quotations like as a and for integer dont
write in any quotations.
System13.out14: - Out is a variable of a system class. It is a static variable or filed.
Save the name with in double quotations to avoid the extension of .txt.
System.out.println(): System: - System is a predefined final class which is defined in java.lang package that provides the
access to the system resources like Keyboard, monitor etc and to get and set the properties
associated with java runtime system. All the methods in the System class are static methods.
SystemClass:- A System class will have static members, they are as follows below
PrintStream out, err
InputStream in;
arrayCopy(Object[ ], st, end, Object[ ], st)
exit(int)
loadLibrary(String)
get/setSecurityManager(SecurityManager)
String getProperty(String)
String getProperties(String str) (getProperties() method is usefull to get the JVM name,
version, properties of JVM and etc.).
Properties getProperties() (Property is a class in java.util package and getProperties()
method is usefull to set/get the property of a class, etc.).
gc()
out: - out is a static variable defined in a System class of the type PrintStream class, which provides all of
the formatting capabilities we have been using from the system file handler or out is the PrintStream
object.
println(): - println() is a built-in overloaded method in the out object or the PrintStream object supports the
print() or println() methods for all data types.
We canprovidea securityfor a classas below:
public static void main(String args[ ]){
11

mainis a method, that is a group of statements.


newis an operator.
13
Systemis a class.
14
Out is a variable.
12

Page 10 of 191

COREJAVA
System.setSecurityManager(new SecurityManager());
------------------------------------------}
To Compile:C:\rnr>javac First.java
C:\rnr>java First
Welcome to java
Class, interface contains methods.
Functionis writteninside& outsideof the class, but methodsare writtenonly insideof the class.
Command line arguments are passed some values to the main method.
Main method does not return any value. Void means no value.
JVM always starts execution of the statements inside of the main method.
Public is written to make available main method to the JVM.
Ex 2: //To find sum of two numbers
import java.lang.*;
(* is a String class)
class Sum
{
(
{ ----This is for starting of class)
public static void main(String args[ ]) (String args[ ] is a parameter)
{
//Variables
int a, b;
//Store data into variables
a = 10;
b = 15;
//Now find sum
int c = a + b;
//display the result
System.out.println(Sum = ,+c);
}
}
(} ----This is for ending of class)
(or)
//To find sum of two numbers
import java.lang.*;
class Sum
{
public static void main(String args[ ])
{
//Variables
int a, b;
//Store data into variables
a = 10;
b = 15;
//display the result
System.out.println(Sum = + (a+b));
}
}
Save the above file (withclassnamecompulsory) as Sum.java
C:\rnr>javac Sum.java
(This is for program compilation)
C:\rnr>java Sum.java
(This is to run the program)
Note: 1. print method displays the results and keeps the cursor in the same line.
2. println method displays the results and then throws the cursor to the next line.

S. No.

Backslashcodes
or escapesequence

Meaning
Page 11 of 191

COREJAVA
1.

\n

New line

2.

\r

Enter key

3.

\t

Horizontal tab

4.

\b

Backspace key

5.

\\

6.

7.

In java every statement must end with semi colon (;).


Java is case sensitive programming language.
NamingConventionsin Java:1. Each word of class names and interface names start with a capital letter.
Ex: - String, StringBuffer, DataInputStream, ActionListener etc
2. Packages names in java are written in all small letters.
Ex: - java.awt, java.io, java.swing etc
3. Method names start with a small letter, then each word start with a capital letter.
Ex: - println(), getChars, readLine(); getNumberInstance() etc
4. Variables names also follow the above rule.
Ex: age, empName, employee_Net_Sal etc
5. Constant variables should be written using all capital letters.
Ex: - PI, MAX_VALUE, FONT15.BOLD16
Note: - java.lang is a package that is by default imported into every java program. The other packages
must be imported in java program.
Importantpackagesof Java:1. java.lang: - This package got primary classes and interfaces essential for java language. It consists of
wrapper classes, strings, multithreading etc.
Wrapper classes are useful to create objects
String is a class in java
Multithreading means create several threads (processes executing) at a time.
2. java.util (util = utility): - This package contains useful classes and interfaces like stack, LinkedList,
Hashtable, Arrays etc.
3. java.io:- This package handles files and input/output related tasks.
4. java.awt (awt = abstract windowtoolkit): - This package helps to develop GUI (Graphical user interface). It
consists of 2 important sub packages, namely: java.awt.event and java.awt.image.
5. javax.swing:- x stands for extended package. The classes in this package have been derived from other
package. This package helps to develop GUI like java.awt.
6. java.net: - net stands for network17. Client/Server programming can be done using this package. It uses
TCP/IP internally.
7. java.applet: - Applets are small intelligent programs, which travel form one place to another place on
internet.
8. java.sql: - sql stands for structure query language. This package helps to connect to databases like
oracle and utilize them in java.
9. java.beans:- Beans are software reusable components. They can be developed using this package.
10. java.rmi: - rmi means remote method invocation18. The objects, which exist on one computer in the
network, can be invoked from another computer and can be used.
11. javax.servlet: - Servlets are server side programs which communicate several clients at a time. Servlets
are server side programs, which handle clients. This package is useful to develop servlets.
Class is model for creating objects. In case we have to write methods & variables.
Data types represent the type data stored into variable (i.e. into memory locations).

15

FONTis a class
BOLDis a constant
17
Network:- Interconnection of computers are called as network.
18
Invocation= Calling
16

Page 12 of 191

COREJAVA

Data typesandliterals:- A data type represents the type of data stores in memory (variable).
Integerdata type: - It represents integer numbers i.e. the numbers without decimal points.
Subtype:S. No.

Datatype

Memorysize

Min & Maxvalue

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 (or) -9.2 x
10-18 to 9.2 x 1018

Ex: - byte r.no = 10


(0 - literal)
Literal means the constant value being directly storing into variable.
long x = 150L;
L means take that number forcibly as long integer to allot the memory as user defined.
float data types:- They can handle numbers with decimal points. Such numbers called floating data type.
Subtype: S. No.

Datatype

Memorysize

Min & Maxvalue

1.

(Single precision ) float

4 bytes

-3.4e38 to + 3.4e38

2.

Double precision

8 bytes

-1.7e308 to + 1.7e308

Q.) Whatis the differencebetweenfloat anddouble?*****


Ans:- float can represents up to 7 digits after decimal point accurately.
Double can represents up to 15 digits after decimal point accurately.
Ex: - float PI = 3.142F;
F represents forcing the JVM to take the value as float because JVM defaultly takes any decimal
values as double.
Characterdata type: - It represents a single characters.
S. No.

Datatype

MemorySize

Min & Maxvalue

1.

Char

2 bytes

0 to 65535

Ex: - char ch = x;
ASCII American standard code for information interchange.
S. No.

Datatype

MemorySize

Min & Maxvalue

1.

char

2 bytes

0 to 65535

2.

byte

1 byte

-128 to 127

3.

short

2 bytes

-32768 to +32767

4.

int

4 bytes

-2147483648 to +2147483647

5.

long

8 bytes

-9223372036854775808 to
+9223372036854775807 (or) -9.2 x
10-18 to 9.2 x 1018

6.

float

4 bytes

-3.4e38 to + 3.4e38

7.

double

8 bytes

-1.7e308 to + 1.7e308

8.

boolean

1 bit

0 or 1

Keyboard consists 114keys. Keyboard consists up to 200 characters only.

Page 13 of 191

COREJAVA
Q) Whatis Unicode?*****
Ans:- Unicode is specification that includes the alphabetic of all international languages into java
character set. Unicode uses 2 bytes to represent single character.

4. Stringdata types:- String represents a group of characters. Strings are objects of string class in java.
Ex: - String name Inet solv;
String str = new String (A String);
Booleandata type: - They store either true or false. It can handle only two values.
Ex: - boolean response = true;
Completelist of Javakeywords:abstract

boolean

Break

byte

case

catch

char

class

Const

continue

default

do

double

else

Extends

final

finally

float

for

goto

If

implements

Import

instanceof

int

interface

Long

native

new

package

private

protected

Public

return

short

static

strictfp

super

Switch

synchronized

this

throw

throws

transient

Try

void

volatile

while

assert
Transient:- A value of an instance variable in a class will not persistent when the object is stored, such an
instance variable can be specified as transient variable, indicating that its value need not be saved when
objects of its classes are put in persistence storage or it prevents fields from ever being serialized.
Transient fields are always skipped when objects are serialized.
Transient variables arent appropriate for equals()and hashCode() methods.
Note: - That the transient modifier cannotbe specifiedfor static variables as these do not belong to objects.
Volatile: - In multithreading environment, threads might cache the values of member variable for efficiency
reason. Since threads can share a variable, it is then vital that reading & writing of the value in the copies
and the master variable do not result in any inconsistency. As these variables values could be changed
unexpectedly. The volatile modifier can be used to inform the compiler that it should not attempt to
perform optimization on the variable.
instanceOf: - The instanceof operator is used for object reference variables only, and you can use it to
check whether an object is of a particular type. By type, we mean class or interface-in other words, if the
object referred to by the variable on the left side of the operator passes the IS-A test for the class or
interface type on the rightside. Even if the object being tested is not an actual instantiation of the class
type on the right side of the operator, instanceof will still return true if the object being compared is
assignment compatible with the type on the right.
class A
{
public static void main (String [] args)
{
String s = new String("foo");
if (s instanceof String) {
System.out.print("s is a String");
}
}
Operator:- An operator is a symbol that represents an operation. `
a+b
( a, b are operands, + is the operator)
Operand:- An operand is a variable on which operator acts upon.
An operator may act upon a single operand. It is called unary operator. If an operator acts upon
two operands is called binary operand. If an operator acts on three operands is called ternary operand.
Operatorsin Java:1. ArithmeticOperators:+
*
/
%
Page 14 of 191

COREJAVA
2. UnaryOperators:- ++ -3. AssignmentOperators:=
+=
-=
*=
/=
%=
4. RelationalOperators:<
<=
>
>=
==
!=
5. LogicalOperators:&&
||
!
6. BooleanOperators:&
|
!
7. BitwiseOperator:a) Bitwise Compliment: ~
b) Bitwise and: &
c) Bitwise or: |
d) Bitwise xor: ^
e) Bitwise left shift
<<
f) Bitwise right shift
>>
8. TernaryOperator(ConditionalOperator):- ?:
9. Dot Operator(.): a) To refer a classin a package:- java.util.Date
b) To refer a methodin class:math.pow()
emp.getsal()
c) To refer a variablein a class:Employee.name, emp.name
10. InstanceofOperator:- To test whether an object belongs to a class.
Ex: - emp instanceof Employee.
Arithmetic Operators: - These operators perform basic arithmetic calculations like addition, subtraction,
etc
Ex: a = 13, b = 5
S. No.

Operator

Meaning

Example

Result

1.

Addition

a+b

18

2.

Subtraction

ab

3.

Multiplication

a*b

65

4.

Division

a/b

2.6

5.

Modulus operator (Remainder


of division)

a% b

UnaryOperatorsor Unaryminus(-) Operator:- This operator negates the value of a variable. (Negation means
converting value into + value vice versa).
Ex: int x = -5;
System.out.printlin(x);
-5
System.out.printlin(-x);
5
System.out.printlin(-(-x));
-5
System.out.printlin(-(-(-x)));
-5
IncrementOperator(++): - This operator increases the value of a variable by one.
Ex: int x = 1;
++x 2
x++ 3
x=x+14
Writing ++ before a variable name is called pre incrementation. Writing ++ after a variable name
is called post incrementation.
In pre incrementation, incrementation is done first any other task is done next.
In post incrementation any other task is done first, incrementation is done at the end.
Ex. 1: - int x = 1;
int x = 1;
S.o.println(x);
S.o.println(x)
S.o.println(++x);
S.0.println(x++);
S.o.println(x);
S.o.println(x);
Output
Output
1
1
2
1
2
2
Page 15 of 191

COREJAVA
Ex. 2: - a = 1;

a = 1;
b = 2;
b = 2;
a = ++b;
a = b++;
a=3
a=2
b=3
b=3
Ex 3: - What is the value of the following expression, if a = 7?
++a*a++;
[ b ]
a) 49
b) 64
c) 56
d) 72
e) None of these
DecrementOperator(--): - This operator decreases the value of a variable by one.
int x = 1;
--x 0
x-- -1
x=x1-2
Writing before a variable is called pre decrementation, writing after a variable is called post
decrementation.
AssignmentOperator(=): 1. It is used to store a value into a variable.
Ex: - int x = 15;
2. It can store the value of variable into another variable.
Ex: - int y = x;
3. It can store the value of an expression into a variable.
Ex: - int z = x + y 10;
Note: - At the left hand side of assignment we should use only one variable.
CompactNotation:a = a + 10

a +=10
b = b 100

b -=10
j=k*j
j *=k
i = i/10;
i/=10
p = p%10

p%=10
Relational Operators: - These operators are useful to compare two quantities. They are used to constant
conditions.
>
<
>=
<=
==
!=
Ex: if(a>b)..;
if(a==100);
if(x!=y)...;
Logical Operators:- These operators are useful to combine more than one condition. Combining more than
one condition called Compound condition.
&& - and
|| = or
! - not
Ex: if(a>b && b>c)...;
if(a==100||b=50)...;
if(!(x==1));
BooleanOperator:- These operators act upon Boolean variables and they return Boolean value.
&
Boolean and
|
Boolean or
boolean a = true;
boolean b = false;
a & b - false
a & a - true
b|b
- false
!a
- false
!b
- true
BitwiseOperators:- These operators act upon individual bits of a number.
Convert45 into binary:- Divide the number successively by 2 and table remainders from bottom to top.
45
0 0 1 0 1 1 0 1
22 1
11 0
51
Page 16 of 191

COREJAVA
21
10
01
Converting00101101into decimal:- Multiply the bits by the powers of 2 & take the sum of those products.
0
0
1
0
1
1
0
1
x
x
x
x
x
x
x
x
27 + 26 + 25 + 24 + 23 + 22 + 21 + 20
0 + 0 + 32 + 0 + 8 + 0 + 0 + 1
= 45
-1
-2
BitwiseCompliment(~): - This operator gives complement from of a number.
Ex: int x = 10;
-3
~x = -11;
Bitwiseand(&): - This operator performs anding operations on individual bits
-4
a
b
a & b This table is called truth table. It means, it shows
0
0
0
0
input and output bits
0
1
1
1
0
0
1
1
1

3
2
1

AND gate
Ex: - x = 10 y = 11, x & y =?
x
=
0
0
y
=
0
x&y
=
0

0
0

0
0

0
0

1
1

0
0

1
1

1
0

= 10

Bitwiseor (|): - This operator performs or-ing operations on individual bits


a
b
a|b
0
0
0
0
1
1
1
0
1
1
1
1
OR gate
Ex: - x = 10 y = 11, x | y =?
x
=
0
0
0
0
1
0
1
0
y
=
0
0
0
0
1
0
1
1
x | y=
0
0
0
0
1
0
1
1 = 11
Bitwise Xor (^): - ^ is called as Circum flex or Cap or caret. This operator performs exclusively oring
operations on individual bits
a
b
a|b
0
0
0
0
1
1
1
0
1
1
1
0
XOR gate
Ex: - x = 10 y = 11, x ^ y =?
x
=
0
0
0
0
1
0
1
0
y
=
0
0
0
0
1
0
1
1
x^y
=
0
0
0
0
0
0
0
1 =1
Bitwiseleft shift (<<): - This operator shifts the bits towards left a specified number of times.
Ex: - x = 10; x << 2 =?
x = 10
0
0
0
0
1
0
1
0
x<< 2 0

= 40

Bitwiseright shift (>>): - This operator performs shifting of bit towards right a specified number of times.
x = 10; x = 10
x >>2
x >> 2
x = 10

Page 17 of 191

COREJAVA

x >> 2 0

=2

Bitwisezero fill right shift (>>>): Q) Whatis the difference>> and>>>?*****


Ans:- >> shifts the bits towards right and also preserves the sign bit (0 for positive and 1 for negative
sign).
>>> also shifts the bits towards right but does not preserve the sign bit. It always fills the sign bit
with 0. For this reason it is called zero fill right shift.
Ex: -

//Bitwise operators
class Bits{
public static void main (String args[ ]){
byte x,y;
x = 10;
y = 11;
System.out.println(~x = +(~x));
System.out.println(x & y = +(x&y));
System.out.println(x | y = +(x|y));
System.out.println(x ^ y = +(x^y));
System.out.println(x << y = +(x<<y));
System.out.println(x >> y = +(x>>y));
}
}
TernaryOperator:- This operator acts on three variables i.e. it will takes three variables.
This operator works like a conditional if-else statement. So this operator is called as conditional
operator.
Syntax:var = exp1?exp2:exp;
max = (a>b)?a : b;
(or)
if(a>b)
max = a;
else
max = b;
dot (.) operator:1. packagename.classname (to refer classname)
java.io.BufferedReader
2. classname.var or objectname.var (to refer variable)
System.out emp.name
3. classname.method() or objectname.method() (to refer method)]
Math.sqrt()
br.read
instanceOfoperator: - It is denoted as instanceof. It is used to test whether the object belongs to that class
or not.
Syntax:- objectname instanceof classname
Ex: br instanceof BufferedReader
This operator returns true of false i.e Boolean values.
Executing the statements one by one by JVM is called sequential execution. In sequential
execution programmers does not have better control on the flow of execution.
In Random execution the programmer can executive any statement directly or repeatedly. This
gives better control for the programmer on the flow of execution.
Random execution is possible by using control statements.

Page 18 of 191

COREJAVA
Control Statements: - Control statements modify the flow of execution and give better control for the
programmer on the flow of execution. Without control statements programmers can not able to write
better programs.
1. ifelse statement
4. for loop
7. continue statement
2. do.while loop
5. switch statement
8. return statement
3. while loop
6. break statement
A loop can be executed repeatedly. A statement can be executed once only.
Ifelse statement: - This statement performs a task (one or more statement) depending upon whether a
condition is true or not.
Syntax1:if(condition)
statement1;
[else statement2;]
Ex: //Test if a given number is +ve or ve
class Demo
{
public static void main (String args[ ])
{
int x;
x = -15;
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 negative);
}
}
C:\rnr\javac Demo.java
C:\rnr\java Demo
Output:-15 is negative.
Syntax2: if(condition1)
if(condition2)
if(condition3)
statement1;
else statement2;
else statement3;
else statement4;
Dowhileloop: - This loop repeatedly executes a group of statements as long as a given condition is true.
Storing starting value into the variable is called initialization.
Syntax:-do
{
statements;
}while(condition);
Ex: //To display numbers from 1 to 10
Class Demo
{
public static void main(Static args[ ])
{
int n = 1;
do{
System.out.println(n+ );
n++;
}while(n<=10);
}
}
C:\rnr\javac Demo.java
Page 19 of 191

COREJAVA
C:\rnr\java Demo
Output:1

10

Whileloop:- This loop repeatedly executes a group of statements as long as a condition is true.
Syntax:while(condition)
{
(statements);
}
Ex: //To display even numbers up to 10
class Demo
{
public static void main(String args[ ])
{
int i = 2;
while(i<=10)
{
System.out.println(i);
i = i + 2; or i +=2; [
i += is called compact notation]
}
}
}
(or)
//To display even numbers up to 10
class Demo
{
public static void main(String args[ ])
{
int i = 2;
while(i<=10)
{
System.out.println(i +=2);
}
}
}

Q) Dowhileandwhile loops,whichloopis efficient?*****


Ans:- While loop is efficient. Right from beginning of the execution it provides control to the
programmers.
for loop: - This loop repeatedly executes a group of statements as long as a condition is true.
Syntax:for(exp1; exp2; exp3)
{
statements;
}
exp1 is initialization expression,
exp2 is checking condition expression as long as the condition is true.
exp3 is modifying the value of variable.
Ex: for(int i = 1; i<=10; i++)
{
System.out.println(i);
}
Note: - We can write for loop without exp1 or exp2 or exp3 or any two expressions or all three
expressions.
Ex: //Demo of for loop
class Demo
{
public static void main(String args[ ])
Page 20 of 191

COREJAVA
{
for(int i = 1; i<=10; i++)
{
System.out.println(i);
}
}
}
(or)
int i = 1;
for( ; ; )
{
System.out.println(i);
i++;
if(i>10)break;
}
Infinite loop[for( ; ; )]: - Infinite loop is a loop, which executes forever. These are drawback of programs. It
is a bad programming.
for( ; ; )
do{
while(true)
{
statements;
{
statement;
}while(true);
statements;
}
}
Note: - We can write a for loop inside another for loop. This type for loop is called Nested for loop.
Ex: for(int i = 1; i<=3; i++)
{
for(int j = 1; i<=4; j++)
{
statements;
}
}
SwitchStatement:- This statement is useful to selectively execute a task from a group of available tasks.
Syntax:switch(var)
{
case value1: statement1;
case value2: statement2;
case value3: statement3;
----------------------case valuen: statementn;
[default: default statement;]
}
Ex: //Using Switch
class Demo
{
public static void main(String args[ ])
{
char color = g;
switch(color)
{
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;
Page 21 of 191

COREJAVA
default: System,out.println(No Color);
}
}
}
Switchstatementmoresuitablefor menudrivenprograms.
Break:- Break is a statement, which is useful to come out from the loop. Break is useful to the come out of
the switch statement. It is used in three ways.
1. To come out of a loop.
2. It is used to come out of a switch block.
3. Break is used to goto end of a block19.
Syntax:- break blockname;
Q) gotostatementsare not availablein java why?*****
Ans:- 1. goto statements are decreases the readability of a program.
2. goto statements form infinite loops.
3. goto statements make documentation20 of program very difficult.
4. goto is not part of structured programming.
Factorial representation of all the steps of an algorithm is a flow chart. Algorithm consists step by
step to solve a program.
Ex: //break as goto
class Demo
{
public static void main(String args[ ])
{
boolean x = true;
bl1: {
bl2: {
bl3: {
System.out.println(Block 3);
if(x==true) break bl2;
}
System.out.println(Block 2);
}
Systen.out.println(Block 1);
}
System.out.println(Out of all);
}
}
Continue: - This statement continues the next repetition of a loop and sub sequent statements are not
executed.
Syntax:-continue;
Ex: //Continue
class Demo
{
public static void main(String args[ ])
{
for(int i = 10; i<=1; i--)
{
if(i>5)continue;
System.out.println(i);
}
}
}
19
20

Block:- Block represents a group of statements written in left and right braces.
Documentation:- Documentation is preserving a copy of a program for future use.
Page 22 of 191

COREJAVA
C:\rnr\javac Demo.java
C:\rnr\java Demo
Output:5
4
3
2
1
Ex: - //Continue
class Demo
{
public static void main(String args[ ])
{
for(int i = 10; i<=1; i--)
{
if(i<5)continue;
System.out.println(i);
}
}
}
C:\rnr\javac Demo.java
C:\rnr\java Demo
Output:10
9
8
7
6
5

returnstatement:1. It is used to come out of a method to the calling method.


Syntax:- return;
2. return statement can return a value to the calling method.
Syntax:return x;
return y;
return (x+y);
Ex: //return statement in main()
class Demo
{
public static void main(String args[ ]);
{
int x = 1;
System.ot.println(Before return);
if(x==1)return;
// or we can use as here System.exit(0); in the place of above statement return;
System.out.println(After return);
}
}
[
Where in System.exit(0), System is a class name and exit is a method.]

Whatis the differencebetweenSystem.exit(0)and System.exit(1)?*****


Ans:- System.exit(0) is represents normal termination.
System.exit(1) is represents termination with errors.
Homeworkprograms:Page 23 of 191

COREJAVA
1. To print odd no.s upto 100?
2. Test whether a no. is even or odd?
3. Test whether a no. is prime or not?
4. Display a multiplication table?
5. Calculate factorial of given no.?
6. Display the stars in this below form?
*
*
*
*
*
*
*
*
*
*
Acceptinginput fromKeyboard:Stream: - It represents flow of data from one place to another place. To move data we need stream. There are
two types of streams are available.
1. Input Stream:- It receives or reads data.
2. OutputStream:- It sends or writes data to some other place.
Streams are represented by classes in java.io.package.
Keyboard is represented by System.in [
System is a class]
System.in
InputStream obj Keyboard
System.out
PrintStream obj Monitor
System.err
PrintStream obj Monitor

Q) Whatis the differencebetweenSystem.out()andSystem.err()?*****


Ans:- System.out is used to display normal messages and results.
Ex: - System.out.println(A normal message);
System.err is used to display error messages.
Ex: - System.err.println(Error message);
Streams are represented by input/output devices.
By using streams we can handle hardware components even though Input/output are channel
we need not to change the stream in java program. Thus we are achieving system independent.
InputStreamReader:- InputStreamReader reads the data from keyboard.

BufferedReader
BufferedReader: - It is one type of InputStreamReader. It is connected to InputStreamReader. It accepts
the data form InputStreamReader.
1. Attach the keyboard to InputStreamReader.
To create an object
InputStreamReader
Class obj = new Class()
System.in
InputStreamReader obj = new InputStreamReader(System.in);
2. Attach the InputStreamReader to BufferedReader
BufferedReader br = new BufferedReader(obj);
3. Read data from BufferedReader using read() or readLine() methods.
Ex: //Accepting a single char from Keyboard.
import java.io.*;
class Input
{
public static void main(String args[ ])
throws IOException21
{
//Attach the keyboard to InputStreamReader
InputStreamReader obj = new InputStreamReader(System.in);
//Attach the InputStreamReader to the BufferedReader
BufferedReader br = new BufferedReader(object);
//read data from BufferedReader
System.out.println(Enter a single char: );
Char ch = (char)br.read();
21

Exception:- It means runtime error.


Page 24 of 191

COREJAVA
System.out.println(You Entered: + ch);
}
}
br.read() returns int values so we have to use (char) before the br.read() to give in char value [
Char ch = (char)br.read();]
Converting one data type to another data type is called typecasting or casting.
( ) is called as casting operator.
When we are using read() method in rare conditions we will get runtime errors, so to eliminate
this error we have to use throws IOException.
read() method cannot read more than one character.
Acceptinga String:String ch = br.readLine();
readLine takes 255 characters.
Ex: //Accepting int value
import java.io.*;
class Input
{
public static void main(String args[ ])throws IOException
{
//create BufferedReader object to accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(Enter int No. );
String str = br.readLine();
int n = Integer.parseInt(str);
//parseInt(str) is a static method in Integer class
System.out.println(Number =+n);
}
}
parseInt(str) is a Static method in a integer class
Acceptinga float Numberfromkeyboard:Same as above but in the place of int n = Integer.parseInt(str);
We have to write float n = Float.parseFloat(str);
(or)
float n = Float.parseFloat(br.readLine());
Acceptinga doublefloat Number:Same as above
double n= Double.parseDouble(br.readLine());
Ex: //Accept & display Employee Details
import java.io.*;
class Input
{
public static void main(String args[ ]) throws IOException
{
// To accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Accept Employee Data
System.out.print(Employee ID: );
int id = Integer.parseInt(br.readLine));
System.out.print(Employee sex: );
Char sex = (char)br.read();
br.skip(2);
System.out.print(Employee Name: );
String Name = br.readLine();
//Display Employee Data
System.out.println(Employee Data: );
System.out.println(ID :+id);
System.out.print(Sex :+sex);
System.out.print(Employee Name :+Name);
}

Page 25 of 191

COREJAVA
}
br.skip(2) is used to eliminate the enter key = \r. Because when we are using br.read () &
br.readLine() it will get.
Programs:
1) Accept 2 numbers from keyboard & find the result of their addition, subtraction, multiplication, division.
2) Print even nos between m & n
3) Print Fibonacci series (0,1,1,2,3,5,8,13,21,)
4) Print prime no series (2, 3, 5, 7, 11, 13, 17,...)

ARRAY:An Array represents a group of elements of same data type. We can represent several elements in
a single array. There are 3 types of arrays
1. One dimensional array (1D)
2. Two dimensional array (2D)
3) Multidimensional array (3D, 4D, 5D,.)
Onedimensionalarray: - A One dimensional array represents a single row or a single column of elements.
Ex: - Marks obtained by a student in 5 subjects are: 55 64 66 74 24
CreatingOnedimensionalarray:- There are 2 ways
1. We can create 1D array by declaring & initializing it directly.
Ex: int marks[ ] = {55,23,87,34,56};
Memory allocated by JVM is
55
57
68
70
69
[0]
[1]
[2]
[3]
[4]
Marks 55 = marks[0]
or Marks[ i ] where i is an integer number that indicates position of the element in the array. i is also
called as index. Index represents the position of an element in the array. One dimensional array consists
only one index.
float x[ ] = {1.5f, 2.of,3f};
char ch[ ] = {a, b, c} ;
String name[ ] = {raj, kamal, sita};
2) WeScan create a 1D array by using new operator and later we can store the elements in that array.
Ex: int marks[ ] = new int[10];
marks[0] = 50;
marks[1] = 60;
marks[2] = 80;
Double sal[ ] = new Double[100];
String s[ ] = new String[50];
NOTE:- arrayname.lengthgivessize of array;
Ex: // Find total & percentage of marks
import java.io.*;
class Arr1
{
public static void main(String args[ ]) throws IOException
{
//To accept data from keyboard
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
System.out.println(How many subjects? );
int n = Integer.parseInt(br.readLine());
//Create array with size n
int marks[ ] = new int[n];
//Store marks into array
for(int i=0; i<n; i++);
{
System.out.print(Enter marks: );
marks[ i ] = Integer,parseInt[br.readLine();
}
//Find Total
int tot = 0;
Page 26 of 191

COREJAVA
System.out.println(The array elements are: );
for(int i = 0; i<n; i++)
{
System.out.println(marks[ i ]);
tot = tot + marks[ i
}
//Display the total marks
System.out.println(Total marks = + tot);
//Calculate percentage
float percent = (float) tot/n; //(float) is a cast operator
System.out.println(Percentage = + percent);
}
}
By default arrays are created in C,C++ on static memory, but in java every thing is created on
dynamic memory
Only one for is enough to handle One dimensional array.
TwoDimensionalArray(2D Array):- 2D array represents several rows & columns of elements.
Ex: - A class students are obtained marks in 5 subjects.
Student1 50, 51, 52, 53, 54
Student2 60, 61, 62, 63, 64
Student3 70, 71, 72, 73, 74
Creating2D array:1. We can declare and initialize directly.
Ex: int marks[ ] [ ] = {{ 50, 51, 52, 53, 54}, {60, 61, 62, 63, 64}, {70, 71, 72, 73, 74}};
JVM allot memory for the above array like below.

r1
r2
r3
C0
C1
C2
C4
1D array is a combinations of several 1D array marks[ i ] [ j ]
In this i and j are indexes. i represents as row position and j represents as column position. 2D
array consists 2 indexes.
Ex: float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f},
{2.1f, 2.2f, 2.3f, 2.4f, 2.5f},
{3.1f, 3.2f, 3.3f, 3.4f, 3.5f}};
2. We create 2D array using new operator and we can store elements in to it.
int marks [ ] = new int[3] [5];
char ch[ ] = new char[100] [100];
Ex: // To display a 2D array in a matrix
Class Arr1
{
public static void main(String args[ ])
{
float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f},
{2.1f, 2.2f, 2.3f, 2.4f, 2.5f},
{3.1f, 3.2f, 3.3f, 3.4f, 3.5f}};
System.out.printl(In matrix form: );
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
{
System.out.println(x[ i ] [ j ] + \t);
}
System.out.println();
}
}
Page 27 of 191

COREJAVA
}
The outer most for loop represents row of matrix and inner most for loop represents column of
matrix.
for this matrix to find total of matrix same as above and then add below program
float tot = 0;
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
{
tot = tot + [ i ] + [ j ];
}
( Parameter is useful to receive values from outside to the main method.)
C:\>java prog 10 11 12
Command line
10
args[0]
10
Command line argument
11
args[1]
12
arg[s2]
Command line arguments are stored in args[0], args[1], args[2].
Command line arguments are the values passed to the main method at the time of running a
program.
Ex: //Program finds args length
class Args
{
public static void main(String args[ ])
{
//find no. of args.
int n = args.length;
System.out.println(No. of args = +n);
//Displays args
for(int i = 0; i<n; i++)
System.out.println([args[ i ]);
}
}
13. Add two matrices (or 2D arrays) and display their sum of matrix. Also display the total of their
elements.
14. Find the transpose of given matrix.

Whatare differencesbetweenArrayandVector:Array

Vector

1. The size of the array needs to be declared in an


advance. An array is denoted as [ ]

1. No need to declare the size of vector. We may


give its size or you may not.

2. Once declared array cant grow in size.

2. Vector can always grow in size if we start adding


more elements to it then its size will grow.

3. Array can store primitive data types like int,


char, float, double .

3. Storing the primitive data types is not possible in


case of Vector. It can store only object references.

4. Array is not synchronized.

4. Vector is synchronized.

Whydo youwantto converta collectioninto an Array:1. To obtain faster processing time for certain operation.
2. To pass an array to a method that is not overloaded to accept a collection.
3. To integrate your newer, collection based code with legacy code that doesnt understand collection.

Page 28 of 191

COREJAVA
String: - A string represents a group of characters. A string means character array in C-Language, but a
string doesnt means character array. A string represents an object of string class. String class is created
in java.lang package. Stringclassis declaredas final class. Stringclasscan not extendanotherclass.
Stringclassprovidesthe followingfunctionalityfor handlingStrings:1. Creating and initializing String.
2. Reading individual characters in a String.
3. Comparing Strings.
4. Changing the case of characters in a string (toUpperCase/toLowerCase)
5. Concatenating String.
6. Searching for characters and sub Strings
7. Extracting sub strings
8. Conversion of objects to Strings.
CreatingStringclassobject:1. We can create a string by directly storing a string into string class object.
Stringstr = Hello;
Where as String is a class name
str is object name (referring the memory)
2. We can create a string object using new operator.
Stringstr = newString(Hello);
3. We can create a string from a character array
char arr[ ] = {H, e, l, l, o};
Stringstr = newString(arr);
String str = new String(arr, 1, 3);
Here 1 represents the 1st character
3 represents No. of characters.
All will be displayed writing string like above.
java.lang.String: - In String class methods available as below.
1. Stringconcat(Stringstr): Concatenates22 the calling string with str.
Note: - + will also do the same
String s1 = Hydera;
String s2 = bad;
String x = s1.contact(s2);
+ is called as concatenation operator.
2. int length:- returns the length of a string.
int n = s1.length();
3. char charAt(int index):- It receives the integer number and returns the character at the specified.
s1.charAt(2)
4. int compareTo(String str): - returns a negative value if the string comes before str. in dictionary order. A
positive value if the string comes after str, or 0 if the strings are equal.
Ex: String s1 = Boy;
String s2 = Box;
Here ASCII value of B = 66, o = 109, x = 118, y = 119
s1 = Boy
=
66 109 119
s2 = Box
=
66 109 118
0 0 1
HereOutputis 1
int n = s1. compareTo(s2);
When s1< s2 it will gives negative
s1> s2 it will gives positive
s1= s2 it will gives 0
It compare with dictionary form, i.e. which strings comes first & next.
22

Concatenation:- It means joining.


Page 29 of 191

COREJAVA
Whatis the differencebetweencompareTo()methodandequals()method?*****
Ans:- compareTo() method returns the int data type, where are equals() method returns the booleandata
type.

Capital
Alphabates

ASCII Code

Small
Alphabates

ASCII Code

Numeric
Numbers

ASCII Code

1.

65

95

48

2.

66

96

49

3.

67

97

50

4.

68

98

51

5.

69

99

52

6.

70

100

53

7.

71

101

54

8.

72

102

55

9.

73

103

56

10.

74

104

57

11.

75

105

10

58

12.

76

106

11

59

13.

77

107

12

60

14.

78

108

13

61

15.

79

109

14

62

16.

80

110

15

63

17.

81

111

16

64

18.

82

112

17

65

19.

83

113

18

66

20.

84

114

19

67

21.

85

115

20

68

22.

86

116

21

69

23.

87

117

22

70

24.

88

118

23

71

25.

89

119

24

72

26.

90

120

25

73

S. No.

5. int compareToIgnoreCase(Stringstr): - returns a negative value if the string comes before str. in dictionary
order. A positive value if the string comes after str, or 0 if the strings are equal. It ignores the uppercase
or lowercase.
6. booleanequals(Stringstr): - returns true if the string equals str. It is a case sensitive comparison.
7. boolean equalsIgnoreCase(String str): - returns true if the string equals str. This case insensitive
comparison.
8. booleanstartsWith(Stringprefix): - returns true if the string starts with prefix.
9. booleanendsWith(Stringsuffix): - returns true if the string starts with suffix.
Note: - Above two methods use case sensitive comparison.
str.startsWith(This); ------- true
str.endsWith(book); ------- true
10. int indexOf(Stringstr): - return the first occurrence of str in the string.
Page 30 of 191

COREJAVA
String str. = This is book;
int n = str.indexOf(is);
11. int lastIndexOf(Stringstr): - returns the last occurrence of str in the string.
int n = str.lastIndexOf(is);
Note: - Both the above methodsreturn negativevalues, if str not found in the calling string. Count starts from
0.
12. String replace(char oldChar, char newChar): - returns a new string that is obtained by replacing all
characters oldChar in the string with newChar.
13. String substring(int beginIndex): - returns a new string consisting of all characters from beginIndex until
the end of the string.
Ex: String str = INetSolv;
str.substring(4);
It returns solv
str.substring(0,4);
It returns INet
14. String substring(int beginIndex, int endIndex): - returns a new string consisting of all characters from
beginIndex until endIndex (exclusive).
15. StringtoLowerCase(): - Converts all characters into lowercase.
16. StringtoUpperCase(): - Converts all characters into uppercase.
17. String trim(): - Eliminates all leading and trailing spaces. The spaces found before the string are called
leading spaces and the spaces are found after the string are called trailing space.
18. Stringintern(): - A string that is created using the shorthand notation is known as a canonical string.
You can use the Strings intern method to return a canonical string, which is the same string that is
created using the shorthand notation.
19. toCharArray():- Returns character array (char[ ]).
Ex: //Understanding Strings
class Str
{
public static void main(String args[ ])
{
//Create 3 different 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);
//Displays the string
System.out.println(s1 = + s1);
System.out.println(s2 = + s2);
System.out.println(s3 = + s3);
//Find no. of chars in s1
System.out.println(Length of s1 = + s1.length());
//Attach s1 and s2
System.out.println(s1 joined with s2 = + s1.concat(s2));
//Join 3 strings using + (concatenation operator)
System.out.println(s1+ at + s3);
//Check 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 starts with This);
//Extraxt sub string 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(Uppercase s1 = + s1.toUpperCase);
Page 31 of 191

COREJAVA
System.out.println(Uppercase s1 = + s1.toLowerCase);
}
}
//Comparing the Strings
class Compare
{
public static void main(String args[ ])
{
String s1 = Hello;
String s2 = new String(Hello);
if(s1==s2)
System.out.println(Both are same);
else
System.out.println(Both are not same);
}
}
s1, s2 are reference variables but it is not content of objects.
To compare contents of objects we have to use as below statement
if(s1.equals(s2))
We can use the above statement in the place of if(s1==s2) in the above program
Usingequals()://Comparing the Strings
class Compare
{
public static void main(String args[ ])
{
String s1 = Hello;
String s2 = new String(Hello);
if(s1.equals(s2))
System.out.println(Both are same);
else
System.out.println(Both are not same);
}
}
Output:- Both are same.
Ex: public class TwoStrings {
public static void main(String[] args) {
String s1="anand";
System.out.println(Hashcode of s1 = + +s1.hashCode());
String s2=new String("anand");
System.out.println(Hashcode of s2 = + +s2.hashCode());
if(s1==s2){
System.out.println(1);
}
else{
System.out.println(2);
}
if(s1.equals(s2)){
System.out.println(3);
}
else{
System.out.println(4);
}
}
}
Output:Hashcodeof s1 = 92955274
Hashcodeof s2 = 92955274
Ex: -

Page 32 of 191

COREJAVA

Ex: -

2
3
public class StringTest1 {
public static void main(String[] args) {
String s="anand";
s="babu";
System.out.println(s);
String s1="anand";
s1=new String("babu");
System.out.println(s1);
String s2=new String("anand");
s2=new String("babu");
System.out.println(s2);
String s3=new String("anand");
s3="babu";
System.out.println(s3);
}
}

Output:-

Ex: -

Ex: -

babu
babu
babu
babu
//StringReverse
class Reverse{
public String reverseString(String s){
if(s.length()<=1){
return s;
}
else{
char c=s.charAt(0);
return reverseString(s.substring(1))+c;
}
}
}
class StringReverse{
public static void main(String args[]){
Reverse r=new Reverse();
String s1="anand";
System.out.println("Reversed String = "+r.reverseString(s1));
}
}
(or)
//StringReverse
class Reverse{
public String reverseString(String s){
String returnString=" ";
for(int i=s.length()-1;i>=0;--i){
returnString+=s.charAt(i);
}
return returnString;
}
}
class StringReverse
{
public static void main(String args[]){
Reverse r=new Reverse();
String s1="anand";
System.out.println("Reversed String = "+r.reverseString(s1));
Page 33 of 191

COREJAVA
}
} (or)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReverseString1 {
public static void main(String[ ] args) throws IOException{
System.out.println("Enter String value here = ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
char ch[ ]=s.toCharArray();
int n=s.length();
System.out.println(n);
for(int i=n-1, j=0; i>=0; i--, j++){
System.out.print(ch[i]);
}
}
}
Q) Whatis the (Hash)#code?*****
Ans:- The unique I.D. number allotted to an object by JVM is called (hash) #code.

Q) Whatis the differencebetween== and equals()methodin comparingtwo string?*****


Ans:- == compares the references, so it gives unreliable results.
equals() method compares the contents of string class objects. So we should use equals method
for comparing two strings.

Q) Whatis the result for the followingprogram?


String s1 = aaa;
String s2 = aaa;
a. s1==s2;
true (or) false
b. s1.equals(s2);
true (or) false
Ans:- a and b both are true.

String s1 = aaa;
String s2 = new String(aaa);
a. s1==s2;
true (or) false
b. s1.equals(s2);
true (or) false
Ans:- Here a is false and b is true.

If the two objects are equal, their hashcodes must be equal as well.
Typeof Objects:1. Immutable objects.
2. Mutable objects.
ImmutableObjects:- It is an object, whose contents of objects cant be modified. String class objects are
immutable.
Ex: //String class objects are immutable****
s1
Hello
class Test
{
Hai
public static void main(String args[ ])
s2
{
String s1 = Hello;
Hello
String s2 = new String(Hai);
Hai
s1= s1+s2;
System.out.println(s1);
}
}
When ever you want string modified here JVM will create another object and store Hello Hai
and assigns s1 to that s1 is disconnect with Hello. Garbage collector comes & delete (Hello)
unreferenced objects.
MutableObjects:- It is an object, whose contents of objects can be modified. StringBuffer class objects are
mutable. All the data manipulation methods are available in StringBuffer class only.
Page 34 of 191

COREJAVA

StringBuffer methods act on the nvoking object, but objects can change without an
explicit assignment in the statement.

StringBuffer can change without creating a new object.


StringBuffer class objects are mutable. StringBuffer class is also a final class. So StringBuffer
class also cannot extend another class.
Both String and StringBuffer classes are defined in java.lang. Thus they are available to all
programs automatically.
StringBuffer class implements dynamic character String.
StringBuffer equals() method is not overridden; it doesnt compares values.
StringBufferclassprovidesthe followingfunctionalityfor handlingStrings:1. Constructing StringBuffers.
2. Changing, deleting and reading characters in StringBuffer.
3. Construction Strings from StringBuffer.
4. Appending, inserting and deleting in StringBuffer.
5. Controlling StringBuffer Capacity.
CreatingStringBuffer: 1. StringBuffer sb = new StringBuffer(Hello);
2. StringBuffer sb = new StringBuffer(50);
//Empty StringBuffer
java.lang. StringBuffer
Methods:1. StringBuffer append(x): - Appending means adding at the end of StringBuffer. x may be int, float, double,
char, String or StringBuffer. It will be appended to the calling StringBuffer. It will be inserted into the
StringBuffer at offset (at the middle it will insert).
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 (at the middle it will insert).
3. StringBuffer delete(intstart, int end): - Removes the characters sequence in the StringBuffer.
4. StringBuffer reverse():- Reverses the character sequence in the StringBuffer.
5. StringtoString(): - Converts string buffer into a String and return the string object.
6. int length():- returns the length of the StringBuffer.
Q) Whystringobjectsare immutable?*****
Ans:JVM will takes more time to reallocate memory for the same object than creating new object. i.e.
JVM will takes more time to modify contents of objects in strings. JVM will take less time to create new
string class object so string objects are always immutable.

Q) Whatis the differencebetweenString& StringBuffer?*****


Ans:- String class objects are immutable. StringBuffer objects are mutable.
All the data manipulation methods are available in StringBuffer class only.
(or)
String

StringBuffer

1. String class objects are immutable.

1. StringBuffer class objects are mutable.

2. String class overrides equals() and hashcode()


methods of object class.

2. StringBuffer class doesnt overrides equals() and


hashCode() methods of object class.

3. String class can be used as key in the HashMap


or Hashtable.

3. StringBuffer class can not be used as key in the


HashMap or Hashtable.

4. It provides room for exact number of characters

4. It provides room for 16 more characters

5. There are no data manipulation methods in the


class.

5. All the data manipulation methods are available


in this class.

Q) Canyou extendthe Stringclass& StringBuffer class?*****

Page 35 of 191

COREJAVA
Ans: - No, we can not extend both classes because both classes are predefined final classes, which
means that neither of these classes may be subclassed. Both String and StringBuffer implement the
CharSequence interface.
Ex: -

//Full name of a person


Import java.io.*; class Full
{
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 Surname: );
String sur = br.readLine();
System.out.println(Enter Middle Name: );
String mid = br.readLine();
System.out.println(Enter last Name: );
String last = br.readLine();
//Create StringBuffer
StringBuffer sb = new StringBuffer();
//Append sur, last to sb
sb.append(sur);
sb.append(last);
//Insert mid after sur
int n = sur.length();
sb.insert(n, mid);
//Display the Full Name
System.out.println(Full Name = + sb);
System.out.println(In reverse = + sb.reverse());
System.out.println(sb);
}
}
StringsHomeWork:13. Sort a given group of strings into alphabetical order?
14. Test whether a given string in palindrome or not?
Palindrome is a string = reverse string. Ex: rnr = rnr
C, Pascal, COBOL, FORTRON, such types of languages are called procedural languages. We
will write function or procedures in these languages
C++, Java languages are called Object Oriented languages.
Q) Whatis SRS?*****
Ans:Software requirement specification is a document that contains requirements of the client and
strategies to fulfill these requirements. Project Leader will prepare SRS.

Q) Whatis SDS?*****
Ans:SDS means Software Design Specification. It is a document consisting of Input/Output screens,
pseudo codes, dataflow diagrams, software and hardware requirements and databases etc used to
develop the products.
Module is a part of developing software.
Procedural languages can not handle bigger projects.
1. In procedural approach the programmers concentration will be on the problem and its solution. We
need another approach where the entire system is studied and then only software is developed.
2. In procedural approach, when program size exceeds 10000 lines of code and before reading 100000
lines of code the programmers suddenly loosing control on the code. So we need another approach to
develop bigger and complex projects and still the programmer will loose his control.
Page 36 of 191

COREJAVA
3. Procedural approach doesnt reflect human beings life. We another approach, where programming
reflects human beings life.
Because of the above reasons, a new approach object oriented programming system (OOPS)
has been developed. OOPS is a methodology that uses objects & classes in writing programs. OOPS
concept has been developed on human beings life.
Q) Whatis OOPS?*****
Ans:An Object Oriented Programming organizes a program around its data, i.e., objects and a set of
well defined interfaces to that data. An object-oriented program can be characterized as data controlling
access to code.

Featuresof OOPS:1. Object: - An object is any thing that exists in the world. An object will have properties and actions.
Variables and methods are available in object.
Objects are two types
1. MutableObjects: - Whose contents of objects can be modified.
2. ImmutableObjects:- Whose contents of objects can not be modified.
An object is super class for all the classes. The methods in the object class are as follows:
Method

Purpose

object clone()

Creates a new object that is the same as the object being cloned.

boolean equals(Object object)

Determines whether one object is equal to another.

void finalize()

Called before an unused object is recycled.

final Class getClass()

Obtains the class of an object at run time.

int hashCode()

Returns the hash code associated with the invoking object.

String toString()

Returns a string that describes the object.

final void notify()

Resumes execution of a thread waiting on the invoking object.

final void notifyAll()

Resumes execution of all threads waiting on the invoking object.

final void wait()


final void wait(long milliseconds)

Waits on another thread of execution

final void wait(long milliseconds,


int nanoseconds)
equals(), hashCode() and toString() methods are public.
finalize() method is protected.
The critical methods in class Object are equals(), finalize(), hashCode() and toString() methods.
We can not override getClass(), notify(), notifyAll() and wait() methods because they are
declared as final, but we can override remaining methods in the object class.
Examplesof getClass(): String getName()
Class getSuperClass()
Class[ ] getInterfaces()
Method[ ] getMethods()
Constuctor[ ] getConstuctors()
java.lang.reflect
Field[ ] getFields()
Method[ ] getDeclaredMethods()
Constuctor[ ] getDeclaredConstructors()
Field[ ] getDeclaredFields()
Object newInstance()
Q) Whatwill storein oblectsandwhatwill storein the stacks?*****
Ans:- Instance means object. Instance variables are loaded in the objects, but objects are dynamically
created by JVM on the heap area of class loader subsystem.
Page 37 of 191

COREJAVA
The Stack space will used to store parameters of the methods and local variables of a method.
The JVM is responsible for allocating some amount of memory space called as stack space for every
thread. (If there are 10 threads in JVM, then there will be 10 different stack spaces, but there will be only
one Heap space.
Ex: -

class TestAcc
{
int i;
void me()
{
System.out.println(i);
}
public static void main(String[ ] args) {
TestAcc a=new TestAcc();
a.me();
System.out.println(a.i);

}
} (or)
Ex: class TestAcc
{
static int i;
public static void main(String[ ] args)
{
System.out.println(i);
}
}
Class:- A class is a model to creating an object. Class will not exit physically.
Without a class we cannot create objects.
But a class can exist without objects.
Class also will have variables (data) and methods (code).
There are three class access modifiers: public, protected, private.
There are four access levels: public, protected, default, private.
Classes can also be modified with final, abstract or strictfp.
A class cannot be both final and abstract.
A final class prevents inheritance i.e a final class cannot extends the other class.
2. Encapsulation:- Bundling up of data & methods as a single unit is called Encapsulation.
Class is an example for encapsulation. The main advantage of encapsulation is programmers
can use same names in the two different classes, still there will not be any problem.
3. Abstraction:- Showing necessary data and hiding unnecessary data from the user is called abstraction.
4. Inheritance: - Producing new classes from an existing class is called inheritance. The newly produced
class will have all the qualities of the existing class plus it can have its own qualities. The reusability is
the main advantage of Inheritance.
5. Polymorphism: - This word is comes out from the two words of Greek Words. Poly means many and
morphism means forms. Polymorphism means many forms. If something exists in different form it is
called Polymorphism. If same method performs various tasks it is called as polymorphism.
6. Messagepassing:- Calling a method is called as message passing.
Q) Whyjava is objectorientedlanguage?*****
Ans:- Java obeys all the features of OOPS. (The above 6 features)

Q) Whatis the differencebetweenobjectorientedlanguages& objectbasedlanguages?*****


Ans:- Object oriented languages follow all the features of OOPS.
Ex: - C++, Java
Page 38 of 191

COREJAVA
Object based programming languages contain all the features of oops except inheritance.
Ex: - Smalltalk, Simula67 etc
Object is an instance of a class.
Ex: //A class and object
class Person
{
//Properties vars
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());
}
}
new operator (new person()) will create the object, objects are created JVM on dynamic memory.
HCGA Hash code generation Algorithm
memory address HCGA hash code
Hash code is produced or generated from memory address. Hash code & memory address are
not same. Hash code is the reference of the object.
A class is called user defined datatype.
The variables which are stored in objects are called instance variables.
Method codes are stored in method area.
The unique code or ID of every objects which is allotted by JVM.
When the instance variables are not initialized java compiler uses some default values to
initialize them. It gives initial values on the data type.
S. No.

Datatype

DefaultValue

1.

Int

2.

Float

0.0

3.

Double

0.0

4.

Char

A space

5.

String

Null

6.

Any class

Null

(Anyclassnull meansemptyobjects)

Initializingthe instancevariables:1. We can initialize the instance variables of a class in another class.
another class
{
p1. name = Subba Rao;
p1.age = 22;
p1.talk();
Page 39 of 191

COREJAVA
}
}
There is no security of data will be across by other class. To give security for instance variables
we give there instance is private. This offers full security. This private is also call as access specifier.
AccessSpecifier: - An access specifier is a keyword that represents, how to access (read) the members of
a class. There are four types of access specifiers.
1. Private: - A private member of a class is not available any where outside the class or makes a method
or a variable accessible only from within its own class.
2. Public: - A public members of a class are accessible any where outside the class or makes a class,
method or variable accessible from any other class.
3. Protected:- A protected members are available outside the class. It is like as public members or makes
a method or a variable accessible only to classes in the same package or subclasses of the class.
4. Default Specifier: - If no specifier is used java compiler uses a default specifier. Default members are
available outside the class.
1. The instance variables may not available if they are declared as private.
2. We can initialize the instance variables by directly storing values at the time of their declaration.
This way of initialization will store same data in all the objects.
This way of initialization is suitable for constant. A constant is a variable which will have a fixed
value.
Ex: - final Double pi = 3.14159
3. To initialize the instance variable we can use the constructor.
Constructor: - A constructor is similar to a method, which is used to initialize the variables or objects.
There are two types of constructors.
Parameters, which passes the variables from objects to the constructor.
A constructor will have same name of that of its class.
A constructor will not return any value, not even void.
The default return value of constructor is class.
Constructors cannot be overridden, because constructors are not inherited into classes.
The main purpose of constructor is to set the initial state of an object when the object is creating
using new operator.
A constructor can be directly invoked by another constructor (using a call to super() or this()).
this() and super() methods cannot be in the same constructor. We can have one or the other, but
never both.
Interfaces do not have constructors. Interface is not part of an objects inheritance tree.
Abstract classes can have constructors that are called when concrete sub class is instantiated.
Only static variables and methods can be accessed of the call to super() or this().
Constructors can be overloaded, writing two or more constructors with same name but with
difference in the parameters is called as constructor overloading.
When you create an object to sub class the super class constructor is also available to sub class.
Super class default constructor is also available to sub class.
Super class parameterized constructor is not available to sub class.
Constructor can use any access modifier even private also. If a constructor is declared
Constructor as private in a class then it will creates only one object to its class, that type of classes are
called as Singleton classes.
SingleTonClassCode:
class SingleTon
{
private static SingleTon st=null;
private SingleTon()
{
System.out.println(\nIn constructor);
}
public static SingleTon stfactory()
{
if(st==null)
st=new SingleTon();
return st;
Page 40 of 191

COREJAVA
}
}
(or)
public class OnlyOne {
private static OnlyOne one = new OnlyOne();
private OnlyOne(){ }
//Private constructor. This class cannot be instantiated from outside.
public static OnlyOne getInstance() {
return one;
}
}
To use it:
//No matter how many times you call, you get the same instance of the object.
OnlyOne myOne = OnlyOne.getInstance();
Restrictions:1. Modifiers other than the accessibility are not permitted (Ex: - abstract, static and final etc..).
2. Constructors cannot specify exception in the header.
Constructorexecutionoccursas follows: The constructor calls its superclass constructor, which calls its superclass constructor, and so on
all the way up to the Object constructor.
The object constructor executes and then returns to the calling constructor, which runs to
completion and then returns to its calling constructor, and so on back down to the completion of the
constructor of the actual instance being created.
Typesof Constructors:1. Default constructor:- It is a constructor without parameters.
2. ParameterizedConstructor:- This will have one or more parameters.
Note: - A constructor is called and executed only once at the time of creating an object to the class.
DifferencebetweenConstructorand Method:
Constructor

Method

1. Constructor is a special kind of method used to


instance of a class.

1. A method is a function, it represents group of


statements to perform tasks.

2. Constructor doesnt return any type, not even


void also.

2. Method can return void or valid return type.

3. Constructor will have the same name of that its


class.

3. As a name except the class method name, begin


with lower case.

4. Constructor prevents the inheritance.

4. Method can be inherited.

5. We can over load but we cannot overridden.

5. We can over load and overridden.

6. This refers to another constructor in the


present/same class.

6. This refers to instance of class.

7. Super refers to invoke the super class


constructor.

7. Execute an overridden method in the super


class.

8. Constructor will automatically invoke when an


instance of class is created.

8. Method has called explicitly.

Ex: -

//default constructor
person()
{
name = Vishnu;
age = 30;
}
//action-methods
//parameterized constructor
person(String s, int a)
{
name = s; (or) this.name = name;
Page 41 of 191

COREJAVA

age = a; (or) this.age = age;


}
//action-methods
public void talk();
System.out.println(Hello I am +name);
Where String s & int a are local variables to receive data from outside.

Q) Whatis the functionaldifferencebetweendefault constructorandparameterizedconstructor?*


Ans:- Default constructor is used to initialize every object with same data.
Parameterized constructor is used to initialize each object with different data.
(or)
Default Constructor

ParametrizedConstructor

1. A constructor without any parameters is called


as default constructor.

1. A Constructor with one or more parameters is


called parametrized constructor.

2. Default constructor is used to initialize every


object with same data.

2. Parameterized constructor is used to initialize


each object with different data.

3. Super Class default constructor is available to


its subclass.

3. Super Class parametrized constructor is not


available to its subclass.

4. Java compiler creates a default constructor,


when the programmer did not provide any type of
constructor in a class.

4. Java compiler did not provide the paramerized


constructor to the class. The programmer has to
provide the parametrized constructor in a class.

Note1:- Java compiler creates a default constructor or with default values when no constructor is provided
by the programmer, then the java compiler provides default constructor.
Note2: - Writing two or more constructors with the same name but with difference in the parameters is
called as constructor overloading.
this is a keyword, that refers to present class object. i.e. this can refer present class instance
variables, present class constructors and present class methods.
this represents present class object that means it refers the instance variables, constructors,
methods.
Ex1: - //this refers to present class variables, methods and constructors.
//Constructors
class Sample
{
int i
Sample()
{
this(); //calls para constructror)
(
this() left & right simple braces will call present class default constructor)
this.display();
}
Sample(int i)
{
this.i = i; //refers to instance variable
}
void this.display(int i) ( (int i) local variable)
{
System.out.println(i = +i); (
i it is a local variable)
}
}
class Demo
{
public static void main(String args[ ])
{
//Create an object to Sample class
Sample s = new Sample(); //Here default constructor is called & executed.
s.display();

Page 42 of 191

COREJAVA
}
}
(or)
//Constructors
class Sample
{
int i
Sample()
{
this(); //calls para constructror)
this.display();
}
Sample()
{
this.i = i; //refers to instance variable
}
void this.display(int i) ( (int i) local variable)
{
System.out.println(i = +i); (
i it is a instance variable)
}
}
class Demo
{
public static void main(String args[ ])
{
//Create an object to Sample class
Sample s = new Sample(200);
//Here parameter constructor is called & executed.
s.display();
}
}
To get instance variable use this.i
This always refers to present class object.
Ex2: - //Where
class One
{
int x;
(
x is instance variable)
Two t; ( Two is class and t is instance variable)
One()
{
x = 10;
t = new Two();
t.show();
}
void show()
{
x
10
System.out.println(x = +x);
o

}
}
class Two
{
void show()/Two()/show()
{
System.out.println(This is Two);
}
}
class Demo
{

Hash Code

Class One object


class Two object
Object graph

Page 43 of 191

COREJAVA
public static void main(String args[ ]);
{
One o = new One();
o.show();
}
}
this() can call present class parameterized constructor.
this() can call present class instance variable.
this() can refer present class method.

Q) Whatis objectgraph?*****
Ans:- The graph showing the relationship between different objects is called Object graph.
We can establish a relationship between objects by using three methods they are reference
variables/inner classes/inheritance.
Methods:- A method consists of a set of statements to perform a task. A method will have two parts.
1. Method header (or) Method Prototype: - This part contains method name, parameters and method return
type.
returntype methodname(parameter1, parameter2, )
method parameters are local variables to receive the data from outside for the method.
Ex: void sum(double d1, double d2)
double sqrt(double x)
long fact(int n)
double power(double x, int n)
2. Methodbody: - It contains statements representing the logic to solve the problem. It starts with begin {
and ends with }. In between these curlew braces we have to write statements.
Ex: {
statements;
}
Note: - A method can return some value only if return statement is used in the method body. Method can
return only variable/objects/value.
Ex: return 1;
return x;
return obj;
return x+y;
return x,y; It is not possible.
Ex: //Understanding methods
class Sample
{
double d1, d2;
sample(double d1, double d2) //parameterized constructor
//double d1, double d2 are local variables.
{
this.d1 = d1;
this.d2 = d2;
}
void sum()
{
System.out.println(Sum = +(d1+d2));
}
}
class Demo1
{
public static void main(String args[ ])
{
Sample s = new Sample(10, 15.5);
Page 44 of 191

COREJAVA
s.sum();
}

}
double d1, double d2 are local variables.
d1, d2 are instance variables.

(or)
//Understanding methods
class Sample
{
double d1, d2;
sample(double d1, double d2) //parameterized constructor
//double d1, double d2 are local variables.
{
this.d1 = d1;
this.d2 = d2;
}
static void sum(double d1, double d2)
{
return d1+d2; //
d1, d2 are local variable
}
}
class Demo1
{
public static void main(String args[ ])
{
Sample s = new Sample(10, 15.5);
double x = s.sum();
System.out.println(Result = +x);
}
}
Java compiler will construct default constructor when there is not any constructor.
Instancemethod:- It is a method that acts upon instance variables.
To call instance methods we have to use objname.methodname();
Static method: - A static method is a method that does not act upon instance variables of a class. Static
methods are declared with static keyword.
A static method is called using objectname.methodname();
Ex: static double(double d1, double d2)
{
return d1+d2;
}
Sample s = new Sample();
double x = s.sum(10, 15.5);
System.out.println(Result = +x);
A static method is also called directly using classname.methodname();
double x = Sample.sum(10, 15.5);
1. A static method is a method it cannot act on instance variables.
2. A static method is called class.methodname();
3. Static methods are loaded on the Method area of the Class loader sub system in the JVM architecture.
4. Static method cannot access instance variable but they can access static variables.
5. A static method should be declared as static.
6. A static method is a method that can be called and executed without creating an object.
7. Static methods cant be overridden. But it can be redefined in a subclass.
8. Static methods are overloaded.

Q) Whatis differencebetweenstatic variableand instancevariable?*****


Ans:A static variable is a variable whose single copy in memory is shared by all the objects of class.
Any modification of one object will affect other objects. Static variable is also known/called as Class
Variable.
Page 45 of 191

COREJAVA
An instance variable will have a separate copy available in each object. Any modification of one
object will not affect other objects.
(or)
StaticVariable

InstanceVariable

1. A static variable is a variable whose single copy


in memory is shared by all the objects of class.

1. An instance variable will have a separate copy


available in each object.

2. If any modification of one object will affect other


objects.

2. If any modification of one object will not affect


other objects.

3. Static variables are executed at compilation


time.

3. Instance variables are executed at runtime.

4. Static variables are loaded on the method area


of class loader sub system in the JVM
architecture.

4. Instance means objects. Objects are


dynamically created by JVM on the heap area of
class loader sub system in the JVM architecture.
Instance variables are loaded in the objects, so
ultimately instance variables are loaded on the
heap area of class loader sub system.

5. Only static variables and methods can be


accessed of the call to super() or this().

5. Only instance variables and methods can be


accessed after super constructor runs.

Instance variables are created in objects. Objects are in the memory of heap. So instance
variable are stored in heap.
Static variables, Static blocks and static methods are stored on method area of JVM.
Static variable must be declared with static keyword.
Instance variable can be decalred any where in the class and no need of initializing it. It will
takes default values.
Typesof methodsin Java:1. Static methods.
2. Instance methods
a) Accessor method
b) Mutator methods.
3. Factory methods.
A static method does not act on instance variables.
block is a group of statements with ()
Ex: - //A Static block
class Sample
{
static{
System.out.println(This is inside static);
}
public static void main(String args[ ])
{
System.out.println(Inside main);
}
}
Staticblocks:- Static blocks are group of statements written inside a block declared as static.
Static blocks are executed before any method is executed.
It means static blocks are executed at the time of compilation only.
Static blocks are stored on the method area of Class loader sub system.
Ex: //A Static block
class Sample
{
static{
System.out.println(This is inside static block);
System.exit(0);
}
Page 46 of 191

COREJAVA
}
In general without main method we can not run the java program.
2. Instance method: - Instance means objects. An object contains instance variables. Instance methods
these are methods, which act upon instance variables of a class. Instance variables are created in object
in the heap memory. This means instance methods acts upon class objects.

An instance method is called using objectname.methodname.

Only instance variables and methods can acess after super constructor runs.

An instance method can access instance variables.

Instance methods can be overloaded or overridden.


a) Accessormethod:- These methods access or read instance variables.
b) Mutator method: - These methods not only read the instance variables but also modify them. Mutator
methods modify the contents of the objects.
Ex: //Accessor and mutator methods
class Person
{
String name;
int age;
char sex;
Person(String name, int age, char sex);
{
this.name = name;
this.age = age;
this.sex = sex;
void display ()//this is an accessor method
{
System.out.println(Name = +name);
System.out.println(Age = +age);
System.out.println(Sex = +sex);
}
}
class Demo
{
public static void main(String args[ ])
{
Person p1 = new Person(Srinivas, 20, M);
p1.display();
}
}
In a class:
Static blocks
These are executed initially
Static variables
Instance Variables
Then these are executed secondly
Instance method
Constructor
---- Constructor will be executed finally
When instance variable & local variable names are same then only we have to use this.
A class is also called user defined data type.
Class variables means static variables.
Ex: //Accessor and mutator methods
class Person
{
String name;
int age;
char sex;
Person(String name, int age, char sex);
{
name = n;
age = a;
sex = s;
Page 47 of 191

COREJAVA
void display ()//this is an accessor method
{
System.out.println(Name = +n);
System.out.println(Age = +a);
System.out.println(Sex = +s);
}
Person modify (Person obj) //Mutator method
{
obj.name = Laxmi;
--obj.age;
obj.sex = F;
return obj;
(
obj is Person class object)
}

}
class Demo
{
public static void main(String args[ ])
{
Person p1 = new Person(Srinivas, 20, M);
p1.display();
Person p2 = p1.modify(p1); (or)
Person p2 = p1.modify(new Person(Vankat, 30, M));
p2.display();
p1.display(); (Now it will displays Laxmis details)
}
}

reference variable
p1

Object
Srinivas

reference variable
p1

20
Copy of
another
obj

reference
We are
storing as

Object
Srinivas
20

M
Lakxmi
19

obj

M
Object
Venkat
30

M
Laxmi

p2
p2

30
M

Referenced variables are passed to methods by value.


Objects are passed to the methods byvalue.
Any thing passed to method by value.
There is no concept pass byvalue & pass byreference.
Pass by reference means passed the address of variable to methods, then pointers receives the
address of variable then we can do modification.
JVM/JVM compiler is developed in C-Language.
Pointers are used internally by JVM, but pointers are not used by the programmers.
The primitive java types (boolean, byte, char, short, int, long, float and double) and the keyword
void are also represented as class objects.
methods also receives arrays as parameters and returns array as result.
Ex: /*Finding sum of given two matrices using methods to accept and return arrays*/
import java.io.*;
class Arr
Page 48 of 191

COREJAVA
{
int arr[ ][ ];
int r, c;
Arr(int r, int c)
{
this.r = r;
this.c = c;
arr = new int[r][c];
}
//To accept elements of an array and return
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.print(Enter element: );
arr[ i ][ j ] = Integer.parseInt(br.readLine());
}
}
//method to display the array after receiving it
void putArray(int res[ ] [ ])
{
for(int i = 0; i<r; i++)
{
for(int j = 0; j<c; j++)
{
System.out.print(res[ i ][ j ] + \t);
}
System.out.println();
}
}
//To accept two arrays and find sum array and return it
{
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[ i ][ j ] = a[ i ][ j ] + b[ i ][ j ];
return temp;
}
}
class ArraySum
{
public static void main(String args[ ])
throws IOException
{
//Vars
int x[ ][ ], y[ ][ ], z[ ][ ];
Arr obj1 = new Arr(3,3);
Arr obj2 = new Arr(3,3);
System.out.println(Enter elements of first array: );
x = obj1.getArray();
obj1.putArray(x);
System.out.println(Enter elements of second array: );
y = obj2.getArray();
obj2.putArray(y);
Page 49 of 191

COREJAVA
z = obj1.findSum(x,y);
System.out.println(The sum array: );
Obj1.putArray[z];
}
}
Factory methods: - A factory method is a method that returns object of the class to which it belongs. All
factory methods are static methods.
Ex: NumberFormat obj = NumberFormat.getNumberInstance();
NumberFormat obj1= NumberFormat.getCurrencyInstance();
NumberFormat obj1= NumberFormat.getPercentInstance();
getNumberInstance(),getCurrencyInstance(),getPercentInstance() are factory methods.
In some classes we cannot use new operator to create an object. In that situation this factory
methods are used.
Objectsare constructed:
We cannot create a new object without invoking a constructor.
Each superclass in an objects inheritance tree will have a constructor called.
Q) In howmanyyoucan createan objectusingnewoperator?*****
Ans:- In 4 ways we can create an object:
1) Using new operator: Ex: - Employee obj = new Employee();
2) Using factory method
Ex: - NumberFormat obj = NumberFormat.getNumberInstance();
3) Using newInstance() method: Ex: - Class c = Class.forName(Employee);
Employee obj = c.newInstance();
4) Using Cloning: - Cloning means creating another copy same as like original copy.
Ex: - Employee e2 = e1.clone();
Whatis the differencebetweenusingnewoperatorandclass.forName()to createan object.
Usingnewoperator:1.
Classes are statically loaded with Javas new operator.
Ex: class MyClass {
public static void main(String args[]){
Car c = newCar();
}
}
2. A NoClassDefFoundException is thrown if a class is referenced with Javas new operator (i.e. static
loading) but the runtime system cannot find the referenced class.
UsingClass.forName():1. Dynamic loading is a technique for programmatically invoking the functions of a class loader at run
time. Let us look at how to load classes dynamically. Class.forName (String className); //static method
which returns a Class.
The above static method returns the class object associated with the class name. The string
className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will
decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other
runtime conditions. Once the class is dynamically loaded the following method returns an instance of the
loaded class. Its just like creating a class object with no arguments. class.newInstance (); //A non-static
method, which creates an instance of a class (i.e. creates an object).
Jeep myJeep = null;
//myClassName should be read from a properties file or Constants interface.
//stay away from hard coding values in your program.
String myClassName = "au.com.Jeep";
Class vehicleClass = Class.forName(myClassName);
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

Page 50 of 191

COREJAVA
2. A ClassNotFoundException is thrown when an application tries to load in a class through its string name
using the following methods but no definition for the class with the specified name could be found:
The forName(..) method in class - Class.
The findSystemClass(..) method in class - ClassLoader.
The loadClass(..) method in class - ClassLoader.
When we call a newInstance() method, it always calls for the default constructor. So in such a
case we must have a default consturctor for a class. Otherwise we get an error.
Ex: //Area of a circle
import java.text.*;
class Circle
{
public static void main(String args[ ])
{
final double PI = 3.14159;
// final double PI = (double)22/7;
double r = 15.5;
double area = PI * r * r ;
System.out.println(Area = +area);
}
}
(or)
//Area of a circle
import java.text.*;
class Circle
{
public static void main(String args[ ])
{
final double PI = 3.14159;
// final double PI = (double)22/7;
double r = 15.5;
double area = PI * r * r ;
System.out.println(Area = +area);
//Format the are value
NumberFormat obj = NumberFormat.getNumberInstance();
obj.setMinimumIntegerDigit(6);
obj.setMaximumIntegerDigit(2);
String s = obj.format(area);
String.out.println(Formatted area = +s);
}
}
15. Create a class with student details and create 2 objects to it and display the details using methods?

Inner Class:- A class within another class is called inner class.


Whereshouldwe use inner classes:
Code without inner classes is more maintainable and readable. When you access private data
members of the outer class, the JDK compiler creates package-access member functions in the outer
class for the inner class to access the private members. This leaves a security hole. In general we should
avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the
outer class and/or inner class can be made private so that only outer class can access it. Inner classes
are used primarily to implement helper classes like Iterators, Comparators etc which are used in the
context of an outer class.

You can use public access specifier before a class.


You cannot use private access specifier before a class.
Only inner classes can be declared as the private.
Directly you cannot create objects to the inner class.
We can create objects to the outer classes.
Page 51 of 191

COREJAVA
Inner class objects can be created only its outer class.
Outer class is acting as a firewall.
Ex: //Inner class
class BankAcct
Outer Class
{
Inner class
private double bal;
BankAcct(double b)
{
bal = b;
}
void start(double r)
{
One Person class
//Create an object to inner class
Interest in = new Interest(r);
in . calculateInterest();
}
private class Interset
{
private double rate;
Interest(double r)
{
rate = r;
}
valid calculateInterset()
{
double interest = bal * rate/100;
System.out.println(Interest = +interest);
bal += interest;
// bal = bal + interest;
System.out.println(Balance = +bal);
}
}
}
class InnerDemo
{
public static void main(String args[ ])
{
BankAcct obj = new BankAcct(10000);
Obj.start(4.5);
//Rate of interest = 4.5
}
}
(or)
//Inner class
class BankAcct
{
private double bal;
BankAcct(double b)
{
bal = b;
}
void start(double r)
{
//Create an object to inner class
Interest in = new Interest(r);
in . calculateInterest();
}
private class Interset
{
private double rate;
Interest(double r)
Page 52 of 191

Another Class

COREJAVA
{
rate = r;
}
valid calculateInterset()
{
double interest = BankAcct.this.bal*this.bal/100;
System.out.println(Interest = +interest);
BankAcct.this.bal += interest;
// bal = bal + interest;
System.out.println(Balance = + BankAcct.this.bal);
}
}
}
class InnerDemo
{
public static void main(String args[ ])
{
BankAcct obj = new BankAcct(10000);
obj.start(4.5);
//Rate of interest = 4.5
}
}
Summaryof Inner Class:1.
An inner class is a class within another class
2.
Inner class is a safety mechanism.
3.
Inner class is hidden from other classes in its outer
BankAcct
class.
4.
An object to inner class can be created only in
bal
outer class.
5.
An object to inner class cannot be created in other
classes.
6.
Inner class features are accessible through outer
class only.
7.
Outer class object and inner class objects are
created separately in memory.
8.
Outer class members are available to inner class.
9.
Inner class object contains an invisible field
this$0 that stores outer class reference.
10.
Only inner classes can be declared as private.
11.
Outer class members can be referred as: outerclass.this.member;
12.
Inner class & outer class are separated by $ symbol.

Interest
bal
this&0

Typesof Inner Classes:


1. Annonymous Classes
2. Static Inner Classes
3. Non-Static Inner Classes
4. Method- local Inner Classes
Anonymousclass: - Anonymous classes combine the process of definition and instantiation into a single
step. These are defined at a location where they are instantiated.
Anonymous classes can be defined and instantiated in contexts, where a reference can be used
i.e. as expression that executes to a reference denoting an object.
Anonymous classes are typically used for creating objects on the fly contexts such as return
value of a method, as an argument in a method call, in initialization of variables. Anonymous class
cannot have constructors. Instance initializer can be used to achieve the same effect as a constructor.
Ex: interface IDrawable{
void draw();
}
class Shape implements IDrawable{
void draw(){ }
Page 53 of 191

COREJAVA
}
class Pointer{
public Shape createShape(){
return new shape(){
public void draw(){
System.out.println( );
}
}
}
}
To define and instantiate an anonymous class that extends an existing class can be specified by
new SuperClassName(optional arguments){class declaration}
A reference to an anonymous class cannot be declared the functionality of the class is only
available through super class reference implementing an interface.
Anonymous class provides a single interface implementation and no arguments are passed. The
anonymous class implicitly extends the object class.
Note: - No implementation clause is used in the constructor.
Anonymousclass
1. Cannot declare a reference and constructor.
2. Declaration and instantiation combined in the same process.
3. No arguments are passed.
4. It can implement a single interface.
5. We cannot use either extends or implement keywords with anonymous classes.
protected void finalize() throws Throwable{
}
Ex. 1: //Exampleof AnonymousClass
class Hai
{
void show()
{
System.out.println(I am show);
}
}
class Hello
{
Hai obj = new Hai()
//Dont put semicolon in above because here we are creating anonymous class.
{
//Anonymous class starts here without name
void show()
{
System.out.println(I am show);
}
void disp()
{
System.out.println(I am display);
}
}; //We writing semicolon here at the end of annonymous class
void m1()
{
obj.show();
//obj.disp(); It is not a method of Hai class
}
} //end of Hello class
class Test
{
public static void main(String args[ ])
{
Page 54 of 191

COREJAVA
Hai obj1=new Hai();
obj1.show();
Hello obj2-new Hello();
obj2.m1(); //To access annonymous class overriding show in m1() method
}
}
Ex. 2: //Exampleof AnnonymousClass
interface Hai
{
void show();
void disp();
}
class Hello
{
Hai obj = new Hai()
{
public void show()
{
System.out.println(I am new show);
}
public void disp()
{
System.out.println(I am disp);
}
}; //end of Annonymous class
void m1()
{
obj.show();
obj.disp();
}
}
class Test
{
public static void main(String args[ ])
{
Hello obj2 = new Hello();
Obj2.m1();
}
}
Ex 3: class MethodInner {
void disp(){
System.out.println("I am in Disp");
class Hai{
void show(){
System.out.println("I am in Show");
}
}
Hai h=new Hai();
h.show();
}
}
class MethodLocalInner{
public static void main(String a[]){
MethodInner m=new MethodInner();
m.disp();
}
}
Page 55 of 191

COREJAVA
Inner classExercise:
16. Create a student class with student details like, rno, name. In this class create an inner class DOB
that contains date of birth of student (dd, mm, yy). Now create two objects and store two students
details. Display the different number of days in their dates of birth?
Ex: //Teacher class
class Teacher
{
int id;
String bal;
String address;
float sal;
void setId(int id)
//mutator() method
{
this.id = id;
}
int getId()
//accessor() method
{
return id;
}
void setName(String name)
{
this.name = name;
Project Lead
}

PL

int getName()
{
return name;
}
void setAddress(String address)
{
this.address= address;
}
int getAddress()
{
return address;
}
void setSal(float sal)
{
this.sal= sal;
}
float getSal()
{
return sal;
}
Ex: -

Programmer 1
P1
Programmer 2
P2

}
//Student class
class Student
{
int id;
String bal;
String address;
int marks;
void setId(int id)
{
this.id = id;
}
int getId()
Page 56 of 191

Project
Database

COREJAVA
{
return id;
}
void setName(String name)
{
this.name = name;
}
int getName()
{
return name;
}
void setAddress(String address)
{
this.address= address;
}
int getAddress()
{
return address;
}
void setMarks(int marks)
{
this.marks = marks;
}
int getMarks()
{
return marks;
}
}
//use Student class
class Use
{
public static void main(String args[ ])
{
//Create an object to student class
Student s = new Stuent();
//Store data into s
s.setId(10);
s.setName(Vijay);
S1
s.setAddress(MIG-44, KPHB Colony,
Hyderabad);
s.setMarks(77);
//retrieve data from s and display
System.out.println(Id = +s.getId());
System.out.println(Name = +s.getName());
System.out.println(Address = +s.getAddress());
System.out.println(Marks = +s.getMarks());
}
}
//Student class extends Teacher class]
class Student extends Teacher
{
int marks;
void setMarks(int marks)
{
this.marks = marks;
}
int getMarks()
Page 57 of 191

ID
Name
Address
Marks

COREJAVA
{
return marks;
}
Inheritance:- Producing new classes from an existing class is called as inheritance.
The newly produced class is called sub class. The original class is called Super class.
Extends is the keyword use in inheritance.
Syntax:class Subclass extends Super class
Reusability is the main advantage of inheritance.
Because of reusability developing of software/program becomes easy.
Sub class contains a copy of super class object.
In inheritance, we create object to only sub class. Because in Sub class it contains all the
methods & objects of class are available to sub class.
Case1: //If Super class has a default constructor
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();
}
}
When you create an object to sub class to super class constructor is also available to sub class.
Super class default constructor is also available to sub class.
Super class parameterized constructor is not available to sub class.
Case2: //If Super class has parameterized constructor
class One
{
int i;
One(int i)
{
this.i = i;
}
void show()
{
System.out.println(Super class method = +i);
}
}
class Two extends One
{
int i;
Two(int x, int y)
{
Page 58 of 191

COREJAVA
super(x);
i = y;

//super() means calling super class default constructor

}
void show()
{
System.out.println(Sub class method = +i);
System.out.println(super.i);
super.show();
}
}
class Const
{
public static void main(String args[ ])
{
Two t = new Two(100,200);
t.show();
}
}
Super keyword refers to super class from sub class.
Using super key word we can refers to super class instance variables constructors, methods
also.
super.show() in sub class. It shows super class method.
We have to initialize first super class constructor.
super(x);
Polymorphism:- Polymorphism came from two Greek words. Poly means many and morphs means forms. If
something exists in many forms, it is called Polymorphism. If the same method performs many tasks it is
called Polymorphism. There are two types of Polymorphisms.
1. Static Polymorphism
2. Dynamic Polymorphism
DynamicPolymorphism:- This is the Polymorphism exhibited at runtime. Dynamic
means runtime. This is also known as runtime polymorphism (or) late binding.
Method consists two parts
1. Method header It doesnt change
2. Method body But body will change/different
In Dynamic Polymorphism a method called is linked with method code at runtime. So it is also
called late binding.
Ex: //Method Overloading
class Sample
{
void add(int a, int b)
{
System.out.println(Sum of two = +(a+b));
}
void add(int a, int b, int c)
{
int d = a+b+c;
System.out.println(Sum of three = +d);
Class Poly
{
public static void main(String args[ ])
{
Sample s = new Sample();
s.add(10,20);
s.add(10,20,30);
}
}
Ex: class Shape{
Page 59 of 191

COREJAVA
int i;
void m1(){
System.out.println("It is shape");
}
}
class Box extends Shape{
int p;
void m2(){
System.out.println("It is box");
}
}
public class TestSuper {
public static void main(String[] args) {
Shape s=new Shape();
System.out.println(s.i);
s.m1();
//s.m2(); It is invalid
//System.out.println(s.p); It is invalid
/*From above we can say that Superclass cannot access the members of subclass, but
Superclasscan accessonly overriddenmethods*/
Box b=new Box();
System.out.println(b.p);
System.out.println(b.i);
b.m1();
b.m2();
Shape s1=new Box();
/*From above we can say that Subclass can refer the Superclass reference and Subclass
canaccessall the membersof Superclass.
System.out.println(s1.i);
s1.m1();
//s1.m2(); It is invalid
//System.out.println(s1.p); It is invalid
Box b1=(Box)new Shape(); //If we run the wholecodenowruntimeexceptionoccurs
System.out.println(b1.i);
System.out.println(b1.p);
b1.m1();
b1.m2();
}
}
Output:0
It is shape
0
0
It is shape
It is box
0
It is shape
Exception in thread "main" java.lang.ClassCastException: com.marlabs.vara.Shape
at com.marlabs.vara.TestSuper.main(TestSuper.java:31)
Ex: class Shape{
int i;
void m1(){
System.out.println("It is shape");
}
}
class Box extends Shape{
int p;
Page 60 of 191

COREJAVA
void m2(){
System.out.println("It is box");
}
}
public class TestSuper {
public static void main(String[] args) {
Shape s=new Shape();
System.out.println(s.i);
s.m1();
//s.m2(); It is invalid
//System.out.println(s.p); It is invalid
Box b=new Box();
System.out.println(b.p);
System.out.println(b.i);
b.m1();
b.m2();
Shape s1=new Box();
System.out.println(s1.i);
s1.m1();
//s1.m2(); It is invalid
//System.out.println(s1.p); It is invalid
Box b1=(Box)s1;
System.out.println(b1.i);
System.out.println(b1.p);
b1.m1();
b1.m2();
}
}
Output:0
It is shape
0
0
It is shape
It is box
0
It is shape
0
0
It is shape
It is box
Method Signature: - A method signature represents method name and its parameter. This part is called
method signature. It is useful to uniquely identify method from signature.
JVM identifies a method separately when any one of the following differences is found.
1. There may be different number of parameters in the both methods.
Ex: void add(int a, int b)
void add(int a, int b, int c)
2. There is a difference in the data types of parameters (or) number of parameters
Ex: void add(float a, int b)
void add(double a, double b)
3. There is a difference in the sequence of parameters (or) order of parameters
Ex: int swap(char a, int b)
int add(int a, char b)
4. There must be difference in return type
Ex: int add(int a, int b)
int add(int a, int b)
Any one of the above differences will make method signature to be different, then JVM can
recognized that method differently.
Page 61 of 191

COREJAVA
Overloading method: - Writing two or more methods with the same name but with different method
signatures is called method over loading. Method overloading is an example for Dynamic Polymorphism.
If you write same methods and same parameters in one class it is called as duplicate method,
but compiler doesnt execute this type of method. There
must be some difference in the method in one class.
Overlaoded methods can change return type.
double calculate
Methods can be overridden and overloaded.
(double x)
Constructors are overloaded but not overridden.
t
Polymorphism is not applied to overloading.
Reference type determines which overloaded
double calculate
method will be used at compile time.
(double x)
Methods from a superclass can be overloaded in a
subclass.
Overloading means reusing the same method name, but with different arguments.
Methods can be overloaded in the same class or in a subclass.
Overloadedmethods:
Must have different argument lists.
May have different return types, as long as the argument lists are also different.
May have different access modifiers.
May throw different exceptions.
Ex: //Example for Overriding
class One
{
double calculate(double x)
{
return x * x;
}
}
class Two extends One
{
double calculate(double x)
{
return Math.sqrt(x);
}
}
class Poly
{
public static void main(String args[ ])
{
Two t = new Two();
double res = t.calculate(16);
System.out.println(Result = +res);
}
}
O/P: - 4
Ex: //Method Overriding
class One
{
double calculate(double x)
{
return x * x;
}
}
class Two extends One
{
double calculate(double x)
{
Page 62 of 191

COREJAVA
return Math.sqrt(x);
}
}
class Poly
{
public static void main(String args[ ])
{
One t = new One();
double res = t.calculate(16);
System.out.println(Result = +res);
}
}
O/P: - 256
Ex: class Test{
double calculate(double x){
return x*x;
}
}
class B extends Test{
double calculate(double x){
return Math.sqrt(x);
}
}
public class MethodOverride {
public static void main(String[] args) {
Test t=new Test();
double res=t.calculate(4);
System.out.println("---Result---"+res);
//This above code calls Superclass method
B b =new B();
double res1=b.calculate(4);
System.out.println("---Result---"+res1);
//This above code calls Subclass method
Test t1=new B();
double res2=t1.calculate(4);
System.out.println("---Result---"+res2);
//This above code calls Subclass overridden method
B b2=(B)t1;
//In the above line if we keep t reference also it throws ClassCastException
double res3=b2.calculate(4);
System.out.println("---Result---"+res3);
//This above code calls Subclass Overriden method
B b1=(B)new Test();
double res4=b1.calculate(4);
System.out.println("---Result---"+res4);
//The above code throws ClassCastException
}
}
Output:---Result---16.0
---Result---2.0
---Result---2.0
---Result---2.0
Exception in thread "main" java.lang.ClassCastException: com.marlabs.vara.Test
Page 63 of 191

COREJAVA
Ex: -

at com.marlabs.vara.MethodOverride.main(MethodOverride.java:31)
class A1{
int i=50;
}
class B1 extends A1{
int i=60;
}
public class TestSuperInt {
public static void main(String[] args){
A1 a=new A1();
System.out.println(a.i);
B1 b=new B1();
System.out.println(b.i);
A1 a1=new B1();
System.out.println(a1.i);
B1 b1=(B1)a1;
System.out.println(b1.i);
}
}

Output:50
60
50
60
Methodoverriding:- Writing two or more methods in super and sub classes with the same name and same
signature is called method overriding.
The sub class method overrides the super class method. This means only sub class method is
executed. In method overriding JVM executes a method depending upon the type of the reference used
to call the method.
Method overriding is an example for Dynamic Polymorphism.
Writing body for method is called implementation.
The argument list must exactly match that of the overridden method.
The return type must exactly match that of the overridden method.
The access level must not be more restrictive than that of the overridden method.
If a method cant be inherited we cannot override it.
The overriding method must not throw new broader checked exceptions than those declared by
the overridden method.
Polymorphism applies to overriding, not to overloading.
Object type determines which overridden method is used at runtime.
The key benefit of overriding is the ability to define behavior that's specific to a particular
subclass type.
When a method is declared certain exceptions and you want to override that method you can cut
of all your runtime exceptions while overriding and any general level exceptions like the parent
exceptions can be replaced with its subclass exceptions list, this is the rule for overriding a method. (or)
you can specify the same set of the exceptions or you can leave out of all of the exceptions.
When we are overriding the methods superclass methods must throws superclass exception and
in subclass method should throws subclass exception. If superclass method is throws superclass
exception and it should be hanlded by try & catch block.
If superclass method is throws superclass exception and the subclass method can be without
throwing an exception (or) subclass method can throws runtime exceptions.
Only overrided methods are accessible by Superclass from the Subclass.
Q) Whatis the functionaldifferencebetweenmethodoverloadingandmethodoverriding?*****
Ans:A programmer uses method overloading when he wants to extend an already available feature.
A method overloading is code refinement.
Overlaoding lets you define the same operation in
different ways for different data.
Page 64 of 191

COREJAVA
A programmer uses method overriding when he wants to provide different implementation for the
same feature. Method overriding is code replacement. A method overriding depends on return type of a
method.
Overriding lets you define the same operation in different ways for different object types.
(or)
Whatare the functionaldifferencebetweenmethodoverloadingand methodoverriding:MethodOverloading

MethodOverriding

1. A programmer uses method overloading when


he wants to extend an already available feature.

1. A programmer uses method overriding when he


wants to provide different implementation for the
same feature.

2. A method overloading is code refinement.

2. Method overriding is code replacement.

3. A method overloading doesnt depends on


return type of a method and exception.

3. A method overriding depends on return type of a


method and exception.

4. Overlaoding lets you define the same operation


in different ways for different data.

4. Overriding lets you define the same operation in


different ways for different object types.

In C++ method over loading is example for Static Polymorphism and method over riding is an
example for Dynamic Polymorphism.
Static Polymorphism: - This is the Polymorphism exhibited at compile time. So, this is also called Compile
time Polymorphism. Here the compiler knows which method is called and the method call is linked with
method code at compile time. This is also called Early binding.
Ex: - Achieving Polymorphism using private methods or static methods or final methods is Static
Polymorphism.
final methods:- final methods are the methods in final class.
A class declared as final is called final class.
Ex: final class A
Note: 1. It is also use for declare the values
Ex: final class A
class B extends A
(Invalid)
2. final keyword before a class name prevents the inheritance and overriding.
Casting:- Converting one data type into another (data) type is called casting.
Data type: - It represents the type of data stored into a variable is called Data type. There are two types of
data types.
1. Primitive data types: - These data types represent a single value methods are not available to directly
handle Primitive data types.
Ex: - char, byte, int, long, float, double, boolean.
Primitive data types will store only single value.
2. Advanced data types (or) Referenced data types: - These data types represent groups of values. Methods
are available to handle them.
Ex: - Any array, String any class.
Q) Whatis the differencebetweenprimitivedatatypesand referencetypes?*****
Ans:Primitive data types represent single value methods are not available to directly handle Primitive
data types. Primitive data types will store only single value.
Referenced data types represent groups of values. Methods are available to handle them.
Note: 1. Using casting we can covert a primitive data type into another primitive data type.
2. Using casting we can convert a referenced data type into another referenced data type.
3. We cannot use casting to covert a primitive type into a referenced type and vice versa. For this
purpose wrapper classes are available.
CastingPrimitivedata type: 1. Widening:- Converting a lower data type into a higher type is called widening.
Lower data type means occupies lower memory and contains less numbers of data and higher
data type means occupies higher memory and consists higher numbers of data.
Page 65 of 191

COREJAVA
char, byte, short, int, long, float, double
Lower --------------------------------------------------- higher
Ex: char ch = B;
int n = (int) ch; //Here (int) is cast operator.
Note: - We can convert char into int type only.
Ex: float f = (float)n;
Here it is temporary conversion of n only.
2. Narrowing: - Converting a higher data type a lower data type is called narrowing. In narrowing we may
loose some digits or precessions.
Ex: int n = 65;
char ch = (char)n;
Ex: double d = 12.123;
int n = (int)d;
Casting referenceddata types: - If the classes dont have any relationship then we cannot convert from one
class to another class.
There must be some relationship between classes to casting.
We can cast one class type into another class type only if there is a relation between those
classes by the way of inheritance.
Ex: //Casting referenced data types.
class One
{
void show1()
{
System.out.println(One);
}
}
class Two extends One
{
void show2()
//overriding void show1()
{
System.out.println(Two);
}
}
class Cast
{
public static void main(String args[ ])
{
//Super class reference to refer super class object
One o;
o = new One();
o.show1();
o.show2();
}
}
Reference variable always use to refer to an object One o. Here o is reference variable.
The rulesfor overridinga methodare as follows:
The argument list must exactly match that of the overridden method. If they don't match, you can
end up with an overloaded method you didn't intend.
The return type must be the same as, or a subtype of, the return type declared in the original
overridden method in the superclass.
The access level can't be more restrictive than the overridden method's.
The access level can be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override any superclass
method that is not marked private or final. A subclass in a different package can override only those nonfinal methods marked public or protected (since protected methods are inherited by the subclass).
The overriding method can throw any unchecked (runtime) exception, regardless of whether the
overridden method declares the exception.
Page 66 of 191

COREJAVA
The overriding method must not throw checked exceptions that are new or broader than those
declared by the overridden method. For example, a method that declares a FileNotFoundException
cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.
The overriding method can throw narrower or fewer exceptions. Just because an overridden
method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom
line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of
what the overridden method declares.
You cannot override a method marked final.
You cannot override a method marked static. We'll look at an example in a few pages when we
discuss static methods in more detail.
If a method can't be inherited, you cannot override it. Remember that overriding implies that
you're reimplementing a method you inherited!
Note: - We can use Superclass reference to refer to superclass object. Here we can refers to all
superclass members.
Subclass reference to refer to subclass object.
2nd Combination:Ex: //Casting referenced data types.
class One
{
void show1()
{
System.out.println(One);
}
}
class Two extends One
{
void show2()
{
System.out.println(Two);
}
}
class Cast
{
public static void main(String args[ ])
{
//Subclass reference to refer superclass object
Two t;
t = new Two();
t.show2();
t.show1();
}
}
Here subclass can access to superclass (inheritance).
When we create an object to the subclass then it contains a copy of superclass.
Inheritance we create an object to subclass not to superclass.
3rd Combination:Ex: //Casting referenced data types.
class One
{
void show1()
{
System.out.println(One);
}
}
class Two extends One
{
void show2()
Page 67 of 191

COREJAVA
{
System.out.println(Two);
}
}
class Cast
{
public static void main(String args[ ])
{
//Super class reference to refer to sub class object
One o;
o = new One();
o.show1();
o.show2(); -- It is not required for overriding.
}
}

Ex: -

Fruits class

Citrous

Lemon

Non-Citrous

Orange

Apple

Banana

Q) Whatis generalization?*****
Ans:In inheritance hierarchy moving up from sub class to super class is called generalization or
upcasting or widening.

Q) Whatis specialization?*****
Ans:- Coming down from super class to sub class is called specialization or downcasting or narrowing.
In widening, the super class members/methods are accessible.
In widening sub class members are not available, unless they over ride super class method.
Abstract means a method without a body.
abstract class One
{
abstract void show();
}
Abstractclass:- It contains abstract methods then that class is called as abstract class.
Ex: //Casting referenced data types.
class One
{
void show1()
{
System.out.println(One);
}
}
class Two extends One
{
void show2()
{
System.out.println(Two);
}
}
class Cast
{
public static void main(String args[ ])
Page 68 of 191

COREJAVA
{
One o;
o = (One)new Two();
Two t = Two(o);
t.show1();
t.show2();
}
}
Here we created an object to sub class.
In narrowing we can refer to super class methods as well as sub class methods also.
4th Combination:Ex: //Casting referenced data types.
class One
{
void show1()
{
System.out.println(One);
}
}
class Two extends One
{
void show2()
{
System.out.println(Two);
}
}
class Cast
{
public static void main(String args[ ])
{
Two t;
t = (Two)new One();
Two t = Two(o);
t.show2();
}
}
Note: - We can not use sub class reference to refer to super class object.
Q) Whatis wideningand narrowing?*****
Ans:- See above all.
A method will have two parts
1. Methodheader/prototype:void calculate(double sal)
2. Methodbody:- It represents how to implement the body features.
Note: - When the same method has different implementations (different bodies) the programmer cannot
write any body for the method in the super class.
Abstractmethod:- Abstract method is a method without a body.
A class with abstract methods is called abstract class both the abstract method and abstract
class must be declared with abstract.
In case where you want to use implementation inheritance then it is usually provided by an
abstract base class. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some default behaviour and force subclasses to provide any
specific behaviour.
Ex: //
abstract class Car
{
//every car will have a regno
int regno;
Page 69 of 191

COREJAVA
//to store a regno value
Car(int r)
{
regno = r;
}
/*every car will have a fuel tank. The mechanism to fill the tank is same for all cars*/
void filltank()
{
System.out.println(Take the 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 brakes. But different cars will have different breaking mechanism*/
abstract void braking(int force);
}
Save it and compile it.
//This is a concrete sub class of car class
class Maruti extends Car
{
Maruti(int regno)
{
super(regno);
}
void steering(int direction)
{
System.out.println(Maruti uses manual steering);
System.out.println(Please drive the car);
}
void braking(int force)
{
System.out.println(Maruti uses hydraulic brakes);
System.out.println(Apply brakes to stop the car);
}
Save it & compile it.
//This is a concrete sub class of car class
class Santro extends Car
{
Santro(int regno)
{
super(regno);
}
void steering(int direction)
{
System.out.println(Santro uses power steering);
System.out.println(Start the car);
}
void braking(int force)
{
System.out.println(Santro uses gas brakes);
System.out.println(Apply brakes to stop the car);
}
}
Save it & compile it.
//Let us use a car
class UseCar
{
public static void main(String args[ ])
{
Page 70 of 191

COREJAVA
//take new Maruti an Santro cars
Maruti m = new Maruti(6666);
Santro s = new Santro(1111);
//Create a reference to Car class
Car ref;
//
ref reference variable to Car class
//Use Maruti
ref = m;
(or) ref = s;
//Now use it
ref.filTank();
ref.steering(2);
ref.braking(450);
}

}
Save this above code as UseCar.java then compile and run it.
AbstractClass:1. An abstract class is a class with 0 or more abstract methods.
2. An abstract class can have variables/vars, complete methods and abstract methods.
3. We cannot create an object to abstract class.
4. But we can create a reference variable to abstract class.
5. All the abstract methods of the abstract class should be implemented (body) in its sub class.
6. If abstract method is not implemented then that sub class should be declared abstract.
7. The reference of abstract super class can be used to refer to objects its sub class.
8. The reference of abstract super class cannot refer to the individual methods of the sub class.
9. An abstract class cannot be both abstract and final. abstract final class A (invalid).
10. An abstract class must be subclassed.
11. An abstract class will have constructors, and those constructors are always called when a concrete
sub class is intantiated.
Interface:- An Interface defines a protocol of behavior that can
Abstract
be implemented by any class anywhere in the class
------- methods
hierarchy. An interface defines a set of methods but doesnt
------- 4
implement them. An interface is a named collection of
method definitions (without implementations). An interface
------can also declare constants.
An interface is a specification of method proto types.
Prototypes will be in the interface. All the methods of the
interface are abstract.
For polymorphic interface inheritance, where the
4
4
client wants to only deal with a type and does not care about
the actual implementation use interfaces. If you need to
change your design frequently, you should prefer using
Implementation
class
interface to abstract. Coding to an interface reduces coupling
and interface inheritance can achieve code reuse with the
help of object composition. Another justification for using interfaces is that they solve the diamond
problem of traditional multiple inheritance as shown in the figure. Java does not support multiple
inheritances. Java only supports multiple interface inheritance. Interface will solve all the ambiguities
caused by this diamond problem.
All the methods are incomplete only.
We can create reference to the interface.
We cant create an object to interface.
In interface we have the abstract methods. Implementation class is a class, where all the
methods in a class.
We can provide several classes for the same interface.
In interface here all the abstract methods. So must implement all methods in a class (this can
also contain or within body to that methods) this class is called implemented class.
We can provide n number of implement to interface.
Page 71 of 191

COREJAVA
Interface contains only names.
Database is repository of data. To manage and to store the data, database is needed. Data is
stored in the form of tables.

Boy for the


method
remove it &
use interface.

void connect()
{
--------------------

API doc. Implementation Databases


class (I.C.)
Oracle
*

--------------------------------------}

*
I. C.
*
I. C.

main method

Sybase

Mysql

void method() this support all or any database in the world.


The database & to retrieve the data.
All the methods in interface are abstract.
Driver is an implementation class, where the methods are implemented.
Interface is more powerful than class.
API document is a .html file, that contains description of all the features of a software or a
product or a technology.
By default all the methods of interface are public & abstract.
Ex: //Interface example
interface MyInter
{
void connect();
//public abstract
}
class OracleDB implements MyInter
{
public void connect()
{
System.out.println(Connecting to Oracle database);
}
}
class SybaseDB implements MyInter
{
public void connect()
c
OracleDB
{
System.out.println(Connecting to Sybase database);
}
connect()
}
mi
method
class MysqlDB implements MyInter
{
c references that object
public void connect()
{
System.out.println(Connecting to Mysql database);
}
}
c
OracleDB
class Database
{
public static void main(String args[ ])
connect()
throws Exception

mi

Page 72 of 191

method

c references that object

COREJAVA
{
//Accept the database name and store it in object c.
Class c = Class forName(args[0]);
//Create an object to the class whose name is in c.
MyInter mi = (MyInter)c.newInstance();
//Call connect() method using mi
mi.connect();
}
}
Save it Database.java
C:\rnr>javac Database.java
C:\rnr>java Database.java OracleDB
C:\rnr>java Database.java SybaseDB
C:\rnr>java Database.java MysqlDB
Interface:1. An interface is a specification of method prototypes.
2. An interface contains o or more abstract methods.
3. All the methods of the interface are public and abstract by default.
4. An interface may have variables, which are public static and final by default. In another words,
interfaces can declare only constants, not instance variables.
5. We cannot create an object to an interface.
6. But we can create a reference of interface type.
7. All the abstract methods of the interface should be implemented in its implementation class.
8. Interface reference can be used to refer to the objects of implementation classes.
9. If any method is not implemented in an implementation class, it should be declared as abstract.
10. Once an interface is written, any third party vendor can implement it.
11. An interface cannot implement another interface.
12. An interface can extend another interface.
13. We can write a class inside an interface.
14. A class can implement multiple interfaces.
15. All the methods are incomplete only.
16. Interface methods must not be static. Because interface methods are abstract, they cannot be
marked final, strictfp, or native.
17. Interface dos not have constructors. Interfaces are not part of an objects inheritance tree.
Q) Whatis the functionaldifferencebetweenan abstractclassandan interface?*****
Ans:- A programmer uses abstract class when some common features are shared by all the objects.
A programmer writes an interface, when all features are implemented differently for different
objects.
(or)
AbstractClass

Interface

1. An abstract class is a class with 0 or more


abstract methods.

1. An Interface defines a protocol of behavior that


can be implemented by any class anywhere in the
class hierarchy. An interface defines a set of
methods but doesnt implement them.

2. A programmer uses abstract class when some


common features are shared by all the objects.

2. A programmer writes an interface, when all


features are implemented differently for different
objects..

3. An abstract class will have constructors, and


those constructors are always called when a
concrete sub class is intantiated.

3. Interface does not have constructors. Interfaces


are not part of an objects inheritance tree.

4. Absract class will have complete methods.

4. All the methods in the interface are incomplete


only.

5. All the methods of the abstract class are not


public and abstract by default.

5. All the methods of the interface are public and


abstract by default.

Page 73 of 191

COREJAVA
6. An abstract class will have instance variables in
its concrete sub class. .

6. An interface may have variables, which are


public static and final by default. In another words,
interfaces can declare only constants, not instance
variables.

7. An abstract class can extend only one another


class.

7. An interface can extends multiple interfaces (or)


a class can implements multiple interfaces.

8. An abstract class methods can be declared as


static in its sub class.

8. Interface methods must not be static. Because


interface methods are abstract, they cannot be
marked final, strictfp, or native.

Howmuchmemoryis occupiedby classtwoobjects?*****


Ans:- class One
class Object
{
{
int x;
object
}
}
class Two extends One
class One extends Object
{
{
int y;
int x;
}
}
class Two extends One
{
int y;
}
object It will occupies some memory. We can not say exact memory.
Howmuchmemoryis occupiedby classTwoobjects
[ c
]
a) 4 bytes
b) 8 bytes
c) >8 bytes
d) None of the above

Typesof inheritance:1. Singleinheritance:- Producing sub classes from a single super class is called single inheritance.

A
B

class B extends A

class B extends A

class c extends A

2. Multipleinheritance:- Producing sub classes from multiple super classes is called multiple inheritance.

class A
class A

class B

class B

class C extends A, B in valid in Java

class C extends A, B in valid in Java

class D extends A, B in valid in Java

Multiple inheritance does not support in java.


Q) Whymultipleinheritanceis not availablein java?*****
Ans:Multiple inheritance leads to confusion for programmer. This is against to the aim of java to be a
simple programming language.
Java = C++ - Complexity

Page 74 of 191

COREJAVA
There is no operator loading in java. There is no destructor. Destructor work is done by garbage
collector.
Q) Howcanyoucall garbagecollector?*****
Ans:By calling System.gc();. It will runs the garbage collector. Runtime and system classes of
java.lang package System.gc(); is available.

Q) Canyou createobjectto the systemclass?*****


Ans:- No, It is not possible. System class cannot be initiated because it contains static methods.
finalize() method belongs to class of java.lang package. finalized method destroy the memory. If
you call the finalize() method it may crash the program, so it is better to avoid calling finalize() method.
finalize() method helps in garbage collection. A method that is invoked before an object is
discarded by the garbage collector, allowing it to clean up its state. Should not be used to release nonmemory resources like file handles, sockets, database connections etc because Java has only a finite
number of these resources and you do not know when the garbage collection is going to kick in to
release these non-memory resources through the finalize() method.
Garbage collector will works automatically; we should not required to call it.
3. Multiple inheritance can be achieved by programmers by using interfaces.
class Z extends A, B (Invalid)
class Z implements A, B (Valid) It is indirect way achieving multiple inheritance. (Refer the
point of interfaces summary)
A class can implement more than one interfaces.
4. Multiple inheritance can be achieved by repeated use of single inheritance.

(1)

Multiple level inheritance

(3)

(2)

Hierarchical

Hybrid inheritance

From figure (3) above the line is multiple inheritance and below the line is single inheritance. So
it is the combinations of single & multiple inheritances.
Ex: //Multiple Interface example
interface Father
{
int PROP1 = 500000; //public static final, final means fixed values
float HT1 = 6.2f;
}
interface Mother
{
int PROP1 = 800000;
float HT1 = 5.0f;
}
class Child implements Father, Mother
{
void property()
{
System.out.println(Childs Property = +(PROP1 + PROP2));
}
class Multi
{
public static void main(String args[ ])
{
Page 75 of 191

COREJAVA
Child ch = new Child();
ch.property();
ch.height();

O/P: -

}
}
Childs property = 13, 00, 000
Childs height = 5.6

Packages:- A package represents a sub directory that contains a group of classes and interfaces.
import java.awt.*;
From the above statement * represents classes and interfaces of that package only but not
available in packages.
import java.awt.event.*;
From the above statement event is package which does not available to import java.awt.*;, so if
you want to use classes and interfaces of event package we must use import java.awt.event.*;
Advantages:1. Packages hide classes and interfaces in a directory, accidental deletion is not possible.
2. The classes and interfaces of one package are isolated from the classes and interfaces of another
package.
Ex: java.util.Date dd mm hh mi.ss
(1sec = 1000 milli seconds)
java.sql.Date dd mm hh mi.ss
3. Packages provide reusability.
Java is objective oriented language because it obeys all the object oriented methods.
Java increases the productivity by using reusability.
Packaging a Web Application: - The standard packaging format for a web application is a web archive file
(WAR). A WAR file is simply a JAR file with extension .war as opposed to .jar. You can create a WAR file
by using jar, javas archiving tool.
C:\BTCE\>jar cvf anand.war
C:\BTCE\>jar xvf anand.war
4. Packages can be extended a new packages can be created.
Disadvantageof Java: Disadvantage of java is, java programs execution is slower than C/C++ programs, because of
.exe file will be created after compiling the C or C++ program. Where as in java .class will be created first
after that this .class will converted into machine language by JVM after that processor execute this
machine language.
Page 76 of 191

COREJAVA
Java does not support pointers. Pointers are inherently insecure and troublesome. Since
pointers do not exist in Java.
Java does not support operator overloading. (iii) Java does not perform any automatic type
conversions that result in a loss of precision.
All the code in a Java program is encapsulated within one or more classes. Therefore, Java does
not have global variables or global functions.
Java does not support multiple inheritance. Java does not support destructors, but rather, add
the finalize() function.
Java does not have the delete operator.
The << and >> are not overloaded for I/O operations
Ex: //Creating our own package: pack
package pack;
public class Adition
{
double d1, 2;
public Addition(double d1, double d2)
{
this.d1 = d1;
this.d2 = d2;
}
void sum()
{
System.out.println(Sum = +(d1+d2));
}
}
Save it as Adition.java
C:\rnr>javac d . Addition.java
In the above -d means to create a directory or a package and . means current directory.
In the above code if you dont declare public you can not able to create object for addition for out
side package to available.
After compiling the above code now it will creates pack sub directory to the rnr and
Addition.class file will stored in pack sub directory and Addition.java file will stored in the rnr root
directory.
//Using the package after creating: pack
class Use
{
public static void main(String args[ ])
{
pack.Adition obj = new pack.Adition();
obj = sum();
}
}
BufferReader is available from JK 1.1. It is not available in JDK 1.0.
From API document we will understand now many values to pass in parameterized constructor
and sum() method does not return anything.
pack.Adition obj = new pack.Addition(10, 15.6);
In the above statement pack contains .class file of (previous program) Addition.class. So we
have to keep .pack infront of Addition. Use.java and Use.class are available in rnr directory.
//Adding another class to package: pack
public class Subtraction
{
public static void sub(double a, double b)
{
return(a b);
}
}
Save it as Subtraction.java
Static method means this method does not acts upon instance variable.
Page 77 of 191

COREJAVA
C:\rnr>javac d . Subtraction.java
//Using the package after creating: pack
class Use
{
public static void main(String args[ ])
{
pack.Adition obj = new pack.Adition(10, 15.5);
obj = sum();
double x = pack.Subtraction sub(10, 15.5);
System.out.println(Result = +x);
}
}
To avoid pack.Addition and pack.Substraction in creating objects we have to import
pack.Addition as below.
//Using the package after creating: pack
import pack.Addition;
import pack.Substraction;
class Use
(or)
//Using the package after creating: pack
import pack.*;
import pack.*;
class Use
badclassfile: .\Addition.java
1. Java compiler searches for a package in .jar format in C:\j2sdk1.4.1_01\jre\lib\ext
2. Java compiler takes the current directory as package and searches for .class files in the current
directory.
3. Java compiler searches for the package in the current directory and sub directories (after cutting those
Addition.java and Subtraction.java files and paste in another new folder (pool to available others).
4. Java compiler searches for the package in the current class path. Class path is a system variable (it is
provide by operating system) that stores active directory path.
C:\rnr>echo %classppath%
%classpath%
Howto set CLASSPATH:C:\rnr>set CLASSPATH = d:\;.%CLASSPATH%
In the above CLASSPATH keep old class path without disturbing.
Ex: //An interface in a package: pack
package pack;
public interface MyInter
public class Adition
{
void showDate();//public abstract
//In the above showData() will be default public abstract
C:\rnr>javac d . MyInter.java
//this is implementation class for MyInter
package pack;
import pack.MyInter;
import java.util.Date;
public class MyDateImpl implements MyInter
{
public void showDate()
{
Date d = new Date();
System.out.println(d);
}
}
C:\rnr>javac d . MyDateImpl.java
(GMT means Green witch mean time)
(1)
//Using the interface
Page 78 of 191

COREJAVA
import pack.MyDateImpl;
class Use
{
public static void main(String args[ ])
{
MyDateImpl mi = new MyDateImpl();
mi.showDate();
}
}
(2)
//Using the interface
import pack.MyDateImpl;
class Use extends MyDateImpl
{
public static void main(String args[ ])
{
Use u = new Use();
u.showDate();
}
}
From the above 2nd is efficient. In (1) we are calling only MyDateImpl methods but in (2) we are calling
MyDateImpl methods on well as class use methods.
Ex: //An interface in a package: pack
package pack;
public class Sample
{
public void display()
{
System.out.println(Hello Students);
}
}
C:\rnr>javac d . Sample.java
//Using the sub package
import inet.solv.Sample;
class Use
{
public static void main(String args[ ])
{
Sample s = new Sample();
s.display();
}
}
Note: - If the package in other sub directory (not in current) you will set class path.
Set classpath = C:\rnr\inner; . ; %classpath%

Access specifier is a keyword that represents how to access or retrieve the members of class.
There are four access specifiers in java.
1. public
2. private
3. protect
4. default
1. Private members of class are not accessible on other classes of the same package or another
package. The scope of private members is with in the class or class scope or (or) makes a method or a
variable accessible only from within its own class.
2. Public members of a class available in the other classes of the same package or another package
scope of public members is global scope or makes a class, method or variable accessible from any other
class.

Page 79 of 191

COREJAVA
B

A
private

public

protected

default

another

same

3. Protected members are an accessible in the sub classes of same package, but not in another package
or makes a method or a variable accessible only to classes in the same package or subclasses of the
class.
4. Default members are available in other classes of same package but not in another package default
members scope is package scope.
Q) Differencebetweenprotectedanddefault?*****
Ans:- Protected members always available in sub class in the same package or another package.
Default members are available in other classes of same package but not in another package
default members scope is package scope.

Visibility

Public

Protected

Default

Private

From the same class

Yes

Yes

Yes

Yes

From any class in the same package

Yes

Yes

Yes

No

From any non-subclass class outside the package

Yes

No

No

No

From a subclass in the same package

Yes

Yes

Yes

No

From a subclass outside the same package

Yes

Yes

No

No

Ex: -

Ex: -

package p1;
class A{
int i;
private char ch;
public float F;
protected double d;
void disp( ){
i, ch, F, d;
}
package p1;
class B extends A{
F, d;
}
package p1;
class C {
F, a1. d;
a1.i;
}
package p2;
class D extends A{
F,d;
}
Class E {
a1.F;
}
package same;
Page 80 of 191

COREJAVA
public class A
{
private int a = 1;
private int b = 2;
protected int c =3;
int d = 4;
}
package same;
import same.A;
public class B
{
public static void main(String args[ ])
{
A obj = new A();
System.ot.println(obj.a);
System.ot.println(obj.b);
System.ot.println(obj.c);
System.ot.println(obj.d);
}
}
package another;
import same.A;
public class C
{
public static void main(String args[ ])
{
A obj = new A();
System.ot.println(obj.a);
System.ot.println(obj.b);
System.ot.println(obj.c);
System.ot.println(obj.d);
}
}
If C will extend
public class C extends A
{
public static void main(String args[ ])
{
C obj = new C();
}
}
Note: - A method, which is not approved to used programs that are deprecated method.
CreatingAPI document:1. Copy all source code files into a directory.
2. Convert the comments into java documentation comments.
Note: - Static variables another name is class variables, these variables only display on the API document
not any other variable.
C:\rnr>javadoc *.java
We compile some .html files will be created with index .html file. This index .html is very
important this is our files.
H.W.
20. Create a figure class with 2 instance variables x, y in a package called gco path. Then import that
package into rectangle class and the area of the rectangle (your rectangle class extends figure). Similarly
derive triangle class and circle classes and display their areas.
21. 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 the values.
double value = math.pow(x, y);
double value = math.sqrt(x);
Page 81 of 191

COREJAVA
Exception:- An exception is runtime error.
Q) Whatare checkedexceptions?*****
Ans:- These are the exceptions, which are detected by the compiler at the time of compilation.

Q) Whatare uncheckedexceptions?*****
Ans:- All runtimeexeptionsare called as unchecked exceptions which are dectedby JVM.
Q) Whatis differencebetweenexceptionand error?*****
Ans:- An exception is an error that can be handled.
An error cannot be handled it.
Exception is an abnormal event in the program. If it occurs, the program is terminated
abnormally in the middle.
Exceptions are represented by classes in java.
Every exception is a sub class to Exception class.
An Error in a program or software is called bug.
Removing the errors is called debugging.
DeskCheckingis the solution for compile-timeerrors.
Logical errors are the errors commited in the logic. These errors canot be detected by compiler
or JVM. These errors can be detected by comparing the programme output with manually calculated
results.
Ex: //An Exception example
class Ex
{
java.lang
public static void main(String args[ ])
{
Object
try{ int n = avgs.length;
Throwable
System.out.println(n = +n);
int a = 45/n;
System.out.println(a = +a);
Error
Exception
}
catch (Arithmetic ac)
{
System.out.println(ac);
}
System.out.println(Class all);
}
}
When there is an exception, abnormal termination will happen. This may spoil the user
data. So the programmer should handle to exception by performing the following tasks.
List of classesandExceptionclassesin java.langpackage:
S. No.

Classes

ExceptionClasses

1.

Boolean

Throwable

2.

Byte

Exception

3.

Character

ArithematicException

4.

Class

ArrayIndexOutOfBoundsException

5.

ClassLoader

ClassCastException

6.

Double

ClassNotFoundException

7.

Float

CloneNotSupportedException

8.

Integer

IllegalAccesException

9.

Long

IllegalArgumentException

10.

Math

IllegalStateException

11.

Object

IllegalThreadStateException
Page 82 of 191

COREJAVA
12.

Runtime

IndexOutOfBoundsException

13.

Short

InstantiationException

14.

String

InterputtedException

15.

StringBuffer

NegativeArraySizeException

16.

System

NosuchFieldException

17.

Thread

NoSuchMethodException

18.

ThreadGroup

NullPointerException

19.

NumberFormatException

20.

RunTimeException

21.

StringIndexOutOfBoundsException

List interfacesin java.langpackage:S. No.

Interfaces

1.

Cloneable

2.

Runnable

3.

Comparable

List Error classesin java.langpackage:S. No.

Error Classes

1.

Error

2.

AbstractMethodError

3.

AssertionError

4.

ClassFormatError

5.

IllegalAccessError

6.

InstantiationError

7.

NoClassDefFoundError

8.

NoSuchFieldError

9.

NoSuchMethodError

10.

OutOfMemoryError

11.

StackOverFlowError

1. The programmer should write all the statements, which may cause exceptions inside try block.
try
{
statements;
}
JVM examines the statements inside try blocks for any exceptions, if there is an exception. It will
jump into catch block. After storing exception details in a stack.
try
{
statements;
Exception Stack
}
catch(Exception class obj)
{
statements;
}
The JVM will jump before catch block. It will store exception
details in stack.

Page 83 of 191

COREJAVA
2. The programmer should write any messages to the user and also he should display exception details
to the user in catch block.
Note: - catchblockis executedonly if thereis an exception.
3. The programmer should close all the files and databases by using finally block. So that the data in the
files and database is not lost.
finally Block: - If any code in the try block is executed, then finally block is guaranteed to be executed
regardless of whether any catch block is executed. finally block can be used to specify any clean up
code.
finally bock will not executed if we put System.exit(0); in the try block.
Note: - finally statement or block is executed always whether there is an exception or not.
try{
statements;
}
catch(Exception class obj){
statements;
}
finally{
statements;
}
Performing the above three steps is called exception handling.
A try block must have atleast catch block or finally blcok.
In the try block or in the catch block we can providebreak or return statements.
finally block is optional. finally block must use when we write break or return statements in try or
catch blocks.
We can write try & catch blocks anywhere it means we can write try & catch blocks within a try &
catch blocks, we can write try & catch blocks within a catch block and we can write try & catch blocks
within a finally block also. In otherwords we write nested try & catch blocks.
Ex: try{
try{
statements;
}
catch(Exception class obj){
statements;
}
finally{
statements;
}
}catch(Exception class obj){
statements;
}
A try block and catch block can be written either in a method or in a loop.
When we are handling the multiple exceptions using try & catch blocks in first catch block we
have to catch/write the subclass exception and in the second catch block we have to write superclass
exception. Otherwise it throws UnreachableException.
Ex: try{
statements;
}
catch(FileNotFoundException fofe)
//FileNotFoundEception is a subclass of IOException{
statements;
}
catch(IOException ioe){
statements;
}
catch(Exception e){
statements;
}
finally{
Page 84 of 191

COREJAVA
close the resources;
}
A try block can haveany numberof catchblocks.
try{
statements;
}
catch(Exception class obj){
statements;
}
catch(Exception class obj1){
statements;
}
catch(Exception class obj2){
statements;
}
But a try block can have only one finally block.
try{
statements;
}
finally{
statements;
statements;
}
DisplayError Message:
try{
open_the_file
}
catch(<exceptionType obj>){
//appropriate exception handler
obj.printStackTrace();
System.out.println(obj.getMessage());
}
Using the capatured exception type object you can findout where the error is occured and what
is the error messages.
printStackTrace() will display the error message, the line where was the error occurred and the
exception type at the console.
getMessage() returns the error message alone. It doesnt tell us where the error was occurred
and what type of exexption it is.
Ex: class Ex{
public static void main(String args[ ]){
try{
System.out.println(n = +n);
int a = 45/n;
System.out.println(a = +a);
}
}
catch (ArithmeticException ae){
System.out.println(ae);
System.out.println(Please enter the values: );
}
finally{
System.out.println(Class all);
}
}
By handling exception that programs are called Robust programs.
catch(ArrayIndexOutOfBoundsException aie)
{
aie.printStateTrace()
Page 85 of 191

COREJAVA
System.out.println(Array index is not within the range);
}
1. We can write a try block followed by multiple catch blocks. We cant write a catch block without a try
block.
2. But we can write a try block without a catch block.
Ex: //Not handles the exception
import java.io.*;
class Sample
{
void accept()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter your name: );
String name = br.readLine();
System.out.println(Hello+name);
}
}
class Demo
{
public static void main(String args[ ])
{
Sample s = new Sample();
s.accept();
}
}
Ex: //NullPointerException
public class NPE
{
static String s;
public static void main(String[] args)
{
System.out.println(s.length());
}
}
O/P: - It will throw NullPointerException
Throwsclause:- This is used to throw out an exception without handling it.
void accept() throws IOException
throws clause is always specified against a method.
Using throws clause you can specified multiple exceptions.
throws cluase is used to propagate an exception.
Whenever throws clause is used against a method, the caller of the method must handle that
particular exception by writing try & catch blocks.
Note: - throws exception represents any type of exception because exception is the superclass of all
exceptions.
Throw: - This is used to create an exception object and throw it out of a try block. Throw is used in try
block.
If we are not storing the instance of any exception into an object variable of that exception type, if
we are directly throwing the exception of the created object, when we don't associated any instance with
the object variable of itself it is called as Annonymous object or Annonymous instance. So throw is the
example of an annonymous class.
Ex: //throw
import java.io.*;
class Demo
{
static void Demo()
{
try
{
Page 86 of 191

COREJAVA
System.out.println(Inside Demo);
throw new NullPointerException(My Data)
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
public static void main(String args[ ])
{
Demo()
//Demo is static method.
}
}
Q) Whatis the differencebetweenthrowsand throw?*****
Ans:Throws clause is used not to handle an exception. Throw clause is used to forcibly to create an
exception and handle it using throw.
1. Throw clause is used in between testing.
2. This is used to create user-defined exceptions and throw them out.
a) Inbuilt Exceptions:- These are the exceptions available in java.
Ex: ArithmeticException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
IOException
RuntimeException
Any type of Runtime Exception
FileNotFoundException
NoSuchMethodException
ClassNotFoundException
NumberFormatException
InterruptedException
NullPointerException
CheckedExceptions

UncheckedExceptions

FileNotFoundException

IndexOutOfBoundsException

ClassNotFoundException

StringIndexOutOfBoundsException

CloneNotSupportedException

ArrayIndexOutOfBoundsException

NoSuchMethodException

ArrayStoreException

NoSuchFieldException

ArithmeticException

IllegalAccessException

ClassCastException

InstantiationException

UnsupportedOperationException

InteruptedException

NegativeArraySizeException

IOException

NullPointerException

SQLException

NumberFormatException

SocketException

ObjectNotFoundException

EndOfFileException

IllegalArgumentException
IllegalStateException
IllegalThreadStateException
IllegalMonitorStateException
SecurityException
TypeNotPresentException (Addedby J2se5.)

Checked exceptions are compiletime exceptionssubclasses java.lang.Exception.


Unchecked exceptions are run timeexceptionssubclasses are java.lang.RuntimeExcetion.
Page 87 of 191

COREJAVA
b) User definedExceptions:- These are exceptions create by user.
CreatingUser definedException:1. Write your own Exception class that extends Exception class,Throwable,RuntimeException(Simply the
super class of corresponding type).
2. Write a default constructor in your own Exception class.
3. Write a parameterized constructor with a String as a parameter.
4. When ever needed create an object to your Exception class and throw it and clause.
Ex: class MyException extends Exception
{
private static int accno[ ] = {1001, 1002, 1003};
private static String name[ ] = {Raju, Rani, Sita, Vinay};
private static double bal[ ] = {5000, 12000, 50,7007.77, 1990.99, 1200.75};
MyException()
{
state;
}
MyException(String str)
{
super(str);
}
public static void main(String args[ ])
{
try
{
System.out.println(Account+\t + Name+\t + Balance+\t);
for(int i = 0; i<5; i++)
{
System.out.println(accno[ i ] + \t + name[ i ] + \t + bal[ i ]);
//If bal<2000 then paid No Exception
MyException me = new MyException();
throw me;
}
}
catch (MyException me)
{
me.printStateTrace();
}
}
}
Ex 2: - class InvalidCCExcep extends Exception{
String ccn="";
public InvalidCCExcep(){ }
public InvalidCCExcep(String cc){
this.ccn=cc;
}
public String toString(){
return "Credit Card Number " +ccn +" is invalid. Try Again";
}
}
public class UserDefineExcep{
public static void main(String as[]){
String ccn=as[0];
try{
m1(ccn);
}catch(InvalidCCExcep e){
System.out.println(e);
}
}
Page 88 of 191

COREJAVA
public static void m1(String ccn) throws InvalidCCExcep{
if(ccn.length()==16){
System.out.println("OK..OK");
}
else{
throw new InvalidCCExcep(ccn);
//If we are not storing the instance of InvalidCCException into an object variable of that
InvalidCCException type, if we are directly throwing the InvalidCCException of the created object, when we don't
associatedany instancewiththe objectvariableof itself it is calledas Annonymousobjector Annonymousinstance.
}
}
}
WrapperClasses:We should convert primitive data types into objects because of the following reasons.
1. Different applications on internet send or receive data in the form of objects.
2. All the classesin java.util packageact upononly objects.
To convert primitive data type in to objects we need wrapper class.
A wrapper class is a class, whose object wraps or contains primitive data type.
Wrappingmeanscontainingor storing.
All wrapper classes are defined in java.langpackage.
Wrapper classes overridden the equals() and hashCode() of object class.
A wrapper class is a final class that prevents the inheritance i.e. it cannot extends other classes.
S. No.

Primitivedata type

Wrapperclass

1.

char

Charcter

2.

byte

Byte

3.

int

Integer

4.

float

Float

5.

double

Double

6.

long

Long

Characterclass:Constructor:1.
Character (char ch)
char ch = A;
Character obj = new Character(ch);
Methods:1. char charvalue()
returns the char value of the invoking (calling) object.
char ch = obj.charValue();
2. static boolean isDigit(char ch)
returns true if ch is a digit (0 to 9) otherwise returns false.
char ch = 1;
Character.isDigit(ch);
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)
returns true if ch is an uppercase letter (A to Z)
5. static boolean isLowerCase(char ch)
returns true if ch is a lowercase letter (a to z)
6. static boolean isSpaceChar(char ch)
returns true if ch is coming from SPACEBAR.
7. static boolean isWhiteSpace(char ch)
returns true if ch is coming from TAB, ENTER, BACKSPACE.
8. static char toUpperCase(char ch)
converts ch into uppercase
9. static char toLowerCase(char ch)
Page 89 of 191

COREJAVA
Ex: -

converts ch into lowercase


//Testing a char
import java.io.*;
class CharTest
{
public static void main(String args[ ])
throws IOException
{
//to accept a char from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter a char: );
Char ch = (char)br.read();
//test ch
if(Character.isDigit(ch))
System.out.println(It is a digit);
else if(Character.isUpperCase(ch))
System.out.println(It is uppercase letter);
else if(Character.isLowerCase(ch))
System.out.println(It is lowercase letter);
else if(Character.isSpaceChar(ch))
System.out.println(It is from Spacebar);
else if(Character.isWhiteSpace(ch))
System.out.println(It is whitespace letter);
else System.out.println(Sorry, I dont know that char);
}
}

Byte class:Constructor:- Byte is the wrapper class of primitive byte.


1. Byte(byte num) ------------------ (1)
2. Byte(String str) ------------------ (2)
byte n = 120;
from (1) Byte b1 = new Byte();
from(2) String s = 120;
Byte b1 = new Byte(s);
Methods:1. byte byteValue()
returns the value of invoking object as a byte.
2. int compareTo(Byte b)
Compares the numerical value of 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.
int n = b1.compareTo(b2);
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.
4. String toString()
returns a string that contains the decimal equivalent of the invoking object.
5. static Byte valueOf(String str)
throws NumberFormatException
returns a byte object that contains the value specified by the string str.
Ex: //Creating and comparing Byte objects
import java.io.*;
class Byte
{
Page 90 of 191

COREJAVA
public static void main(String args[ ])
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter a byte no: );
String str = br.readLine();
Byte b1 = new Byte(str);
System.out.println(Enter another byte no: );
str = br.readLine();
Byte b2 = new Byte(str);
//Compare b1 and b2 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);
else System.out.println(b1+ is lesser);
}
}
Integerclass:Constructor:- It is wrapper class for int data type.
1. Integer(int num) ------------------ (1)
2. Integer(String str) ------------------ (2)
Q) Which of the wrapper classes have only one constructor (or) which of the wrapper classes does not have a
constructorwith stringparameter?*****
Ans:- Character.

Methods:1. int intValue()


returns the value of the invoking object as a int.
2. int compareTo(Integer obj)
Compares the numerical value of invoking object with that of obj. Returns 0, -ve value or +ve
value.
3. static int parseInt(String str)
throws NumberFormatException
returns the int equivalent of the number contained in the string specified by str.
4. String toString()
returns a string form of the invoking object.
5. static Integer valueOf(String str)
throws NumberFormatException
returns a Integer object that contains the value shown by the string 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.
8. static String toOctalString(int i)
returns a String representation of the integer argument in base 8.
Ex: //Converting int into other systems
import java.io.*;
class Convert
{
public static void main(String args[ ])
throws IOException
Page 91 of 191

COREJAVA
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter int value: );
String str = br.readLine();
//Converting str into int.
int n = Integer.parseInt(str);
System.out.println(In decimal = +n);
//Convert n into other systems
str = Integer.toBinaryString(n);
System.out.println(In binary = +str);
str = Integer.toHexString(n);
System.out.println(In Hexadecimal = +str);
str = Integer.toOctalString(n);
System.out.println(In Octal = +str);
}
}
Float class:Constructor:- It is wrapper class for float data type.
1. Float(float num) ------------------ (1)
2. Float(String str) ------------------ (2)
Methods:1. float floatValue()
returns 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.
4. static float parseFloat(String str)
throws NumberFormatException
returns the float equivalent of the string contained in the string specified by str. Returns 0,
negative or positive value.
5. String toString()
returns a string form of the invoking object.
6. static Integer valueOf(String str)
throws NumberFormatException
returns a Float object that contains the value shown by the string str.
Doubleclass:Constructor:- It is wrapper class for double data type.
1. Double(double num) ------------------ (1)
2. Double(String str) ------------------ (2)
Methods:1. double doubleValue()
returns 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.
4. static float parseFloat(String str)
throws NumberFormatException
returns the float equivalent of the string contained in the string specified by str. Returns 0,
negative or positive value.
5. String toString()
returns a string form of the invoking object.
6. static Double valueOf(String str)
throws NumberFormatException
returns a Double object that contains the value shown by the string str.
Page 92 of 191

COREJAVA
Math class:- The class Math contains methods for performing basic numeric 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)
returns the natural logarithm value of the arg.
5. static double pow(double arg)
returns x to the power n value.
6. static double sqrt(double arg)
returns the square root value of the arg.
7. static double abs(double arg)
returns the absolute value of the 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.ceil(4.5) is 4.0
10. static double min(arg1, arg2)
returns the minimum of arg1 and arg2.
11. static double max(arg1, arg2)
returns the maximum of arg1 and arg2.
12. static long round(arg)
returns the rounded value of arg.
Ex: Math.round(4.6) is 5
13. static double random()
returns the random number between 0 to 1.
14. static double toRadius(double angle)
converts angle in degrees into radius.
15. static double toDegrees(double angle)
converts angle in radians into degrees.
Ex: //Creating ranom number between 0 to 10
class Rand
{
public static void main(String args[ ])
throws Exception
{
while(true)
{
double d = 10 * Math.random();
int i = (int)d;
System.out.println(i);
String str = br.readLine();
if(i ==0)
System.exit(0);
Thread.sleep(3000);
}
}
}
H.W.
23. Create a class calculate with static methods to find:
factorial value,
power value,
square root value and
Page 93 of 191

COREJAVA
sine value.
Collectionsclasses(or) Containerclass:
A Collections class or Container class whose object can store a group of other objects. A
Container object stores references of other objects.
Collection classes or Container the classes whose
Objects can handle a group of other objects.
Stack: - A stack represents arrangement of elements in LIFO order.
To insert elements
(Elements means objects).
Insertion and deletion of elements will take place only from
outside called stack of the top.
Inserting elements into the stack is called push stack.
6
Removing elements from the stack is called pop operations.
5
4
Ex: 3
1: - A pile pf plates in a cafeteria is an example for stack.
2
Elements
2. Shunting of coaches to railway engine is an example for stack.
1
Creationof Stack:1. To createa stack:
Stack st = new Stack();
2. To knowwhethera stackis emptyor not, use empty():
Boolean b = st.empty();
If the stack is empty it returns true, if the stack is not empty it returns the false.
3. To pushan elementfroma stack:
st.push(element);
4. To popan elementfroma stack:
object element =st.pop();
5. To searchfor an elementin the stack:
int i = st.search();
This method returns -1, if the element is not found. i represents the position of element in the
stack from the top.
Ex: //Stack operations
import java.io.*;
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 void stsearch(Stack st, int a)
{
int i = st.search(new Integer(a));
return i;
}
public static void main(String args[ ])
throws IOException, EmptyStackException
{
//vars
Stack st = new Stack();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int element, pos;
int choice = 0;
Page 94 of 191

COREJAVA
//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 search for element);
System.out.println(4 Exit);
System.out.println(Enter your Choice: );
choice = Integer.parseInt(br.readLine());
swith(choice)
case 1:
System.out.println(Enter element: );
element.Integer.parseInt(br.readLine());
stpush(st, element);
braek;
case 2:
stpop(st);
braek;
case 3:
System.out.println(Enter element: );
element.Integer.parseInt(br.readLine());
pos = stsearch(st, element);
if(pos == -1)
System.out.println(Element is not found);
else
System.out.println(Element found at position: +pos);
braek;
default:
return;
}
System.out.println(Stack = +st);
}
}
}
To retrieve elements we have to use the interfaces.
1. Iterator
2. ListIterator
3. Enumeration.
LinkedList:- A linked list is a set of nodes. Each node contains two fields data and link to the next node.

node

data

link

Linked list is more flexible way of arranged elements than the stack. Retrieving nodes one by
one done use links.
1. To createa LinkedList:
LinkedList ll = new LinkedList();
2. To addelements(objects)to a linkedlist
ll.add(element);
To add element in 2nd position
ll.add(2, element);
3. To removefirst elementfromthe linkedlist
ll.removeFirst(element);
To remove last element from the linked list
Page 95 of 191

COREJAVA
ll.removeLast(element);
To remove 2nd element from the linked list
ll.remove(2);
4. To changethe 2nd elementwith a newelement
ll.set(2, Newelement);
Ex: //Linked list with strings
import java.io.*;
import java.util.*;
class LLDemo
{
public static void main(String args[ ])
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList ll = new LinkedList();
ll.add(America);
ll.add(India);
ll.add(Japan);
ll.add(China);
System.out.println(Linked List = +ll);
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());
swith(choice)
case 1:
System.out.println(Enter element: );
element = br.readLine();
System.out.println(Enter position: );
pos = Integer.parseInt(br.readLine());
ll.add(pos,element);
braek;
case 2:
System.out.println(Enter position: );
pos = Integer.parseInt(br.readLine());
ll.remove(pos);
braek;
case 3:
System.out.println(Enter new element: );
element = br.readLine();
System.out.println(Enter position: );
pos = Integer.parseInt(br.readLine());
ll.set(pos,element);
braek;
default:
return;
}
System.out.println(LinkedList = +ll);
}
}
Page 96 of 191

COREJAVA
}
Arrays:- Arrays is class, which contain methods to handle array
1. To sort the elementsof an arrayinto ascendingorder
Arrays.sort(arr);
2. To sort only a rangeof elementsof the array
Array.sort(arr, start, end);
This sorts the elements of arr starting from start till end -1 element.
3. To search for element n array
Arrays.binarySearch(arr, element);
This search for element in the array arr and returns its position. If the element is not found, it
returns a negative value.
Note: - binarySearch()methodwill act only on a sortedarray.
4. To compare two arrays, to know if they are same or not.
Arrays.equal(arr1, arr2);
This returns true, if arr1 and arr2 are same else if returns false.
Ex: //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 in array with size n
int arr[ ] = new int[ n ];
for(int i = 0; i<n; i++)
{
System.out.println(Enter Element: );
Arr[ i ] = Integer.parseInt(br.readLine());
}
//Sort the array in ascending order
Array.sort(arr);
System.out.println(The sorted array: );
display(arr);
//Search for an element
System.out.println(Enter element to search: );
int x = Integer.parseInt(br.readLine());
int pos = Array.binarySearch(arr, x);
if(pos<0)
System.out.println(Element not found);
else
System.out.println(Element found at position: +(pos+1));
}
static void display(int arr[ ])
for(int i = 0; i<arr.length; i++)
System.out.println(arr[ i ]);
}
}
H.W.
24. Create an array with string. Accept a string from the keyboard and find its position in the array.
25. Build a linked list of double values.
26. Create a stack with a group of strings.

Page 97 of 191

COREJAVA
Cloning:- Cloning is a technology to obtain exact copy of a plant, a bird,an animal or a human being. This
cloning technology is available now.
Cloningin java: - Obtaining bitwise exact copy of an existing object is called as cloning.
There are two types of cloning
1. Shallow Cloning: - In this type of cloning any modifications to the original object will also modify the
cloned object.
2. DeepCloning:- In this type of modification to original objects will not affect the cloned object.
Deep cloning or copy can be achieved through serialization. This may be fast to code but will
have performance implications.
Ex: //Cloning
class Employee implements Cloneable
{
int id;
String name;
Employee(int i, String s)
{
id = i;
name = s;
}
void display()
{
System.out.println(id = +id);
System.out.println(name = +name);
}
Employee myClone()
throws CloneNotSupportedException
{
return (Employee)super.clone();
}
}
class CloneDemo
{
public static void main(String args[ ])
throws CloneNotSupportedException
{
//Create an obj naturally
Employee e1 = new Employee(10, Sagar);
e1.display();
//Create another obj by cloning
Employee e2 = e1.myClone();
E2.display();
}
}
(or)
Ex: //Cloning
class Employee implements Cloneable
{
int id;
String name;
Employee(int i, String s)
{
id = i;
name = s;
}
void display()
{
System.out.println(id = +id);
System.out.println(name = +name);
}
Page 98 of 191

COREJAVA
public object clone()
throws CloneNotSupportedException
{
return super.clone();
}
}
class CloneDemo
{
public static void main(String args[ ])
throws CloneNotSupportedException
{
//Create an obj naturally
Employee e1 = new Employee(10, Sagar);
e1.display();
//Create another obj by cloning
Employee e2 = (Employee)e1.clone();
e2.display();
}
}
Q) Whichmethodis usedin cloning?*****
Ans:- By using clone() method of java.lang.Object class.
Interface Cloneable will not have any methods.
clone() method is object class. Object is super class.
By writing implements Cloneable the programmer is indicating that classs objects are cloneable.
An interface without any methods is called marking interface or tagging interface. It specifies or
indicates a special purpose for the class objects.
The interfaces with no defined methods act like markers. They just tell the compiler that the
objects of the classes implementing the interfaces with no defined methods need to be treated differently.
Ex: - cloneable.Serializable.
Do not use serialization if you do not have to. A common use of serialization is to use it to send
an object over the network or if the state of an object needs to be persisted to a flat file or a database.
The objects stored in an HTTP session should be serializable to support in-memory replication of
sessions to achieve scalability. Objects are passed in RMI (Remote Method Invocation) across network
using serialization.

Collections
A group of elements are handled by representing with an array.
A group of objects are also handled with array.
To store objects in Array
Employee arr[ ] = new Employee[100];
for(int i = 0; i<100; i++)
{
arr[ i ] = new Employee();
}

Java.util Package

Collections class

Collections obj
Page 99 of 191

COREJAVA

Collectionsobject(or) ContainerObject:- It is an object that stores a group other objects.


Collectionsclass(or) Containerclass:- It is a class whose object can store other objects.
All collection classes have defined in java.util package.
Frame work means group of classes.
Q) Whatis collectionsframework?*****
Ans:Collections frame work is a class library to handle groups of objects. Collection frame work is
defined in java.util package.

Q) Whatis the differencebetweencollectionand Collections?*****


Ans:- Collection is an interface.
Collections is a class.
Collections objects will not act upon primitive datatypes. (or)
collections objects will not store primitive datatypes.
Collections objects stores references of other objects. All
collection classes are defined into 3 types.
1. Sets: - A set represents a group of objects is called as Set.
Ex: - HashSet, LinkedHashSet, TreeSet, etc
2. Lists: - A list represents the group of elements or objects. List is also
similar to set. It will also store elements or objects. Sets will not allow
the duplicate values but Lists will duplicate values. This is the
difference between Lists and Sets.
Ex: - ArrayList, Vector, LinkedList etc

Collection objects

Q) Whichof the collectionclasswill not allowduplicatevalues?*****


Ans:- Sets of the collection class will not allow the duplicate values. Set will not stores the object in
ordered/sorted order.
Lists of the collection class will allow the duplicate values. List will stores the object in ordered/sorted
order.
Sorted means iterating through a collection in a natural sorted order.
3. Maps:- A map stores elements in the form of the keys and value pairs.
Ex: - Hashmap, Hashtable etc
List of interfacesandclassesin java.util package(or) Collectionframework:
S. No.

Interfaces

CollectionClasses

1.

Set

ArrayList

2.

List

Vector

3.

Map

LinedList

4.

SortedSet

HashSet

5.

SortedMap

TreeSet

6.

Iterator

Collections

7.

ListIterator

LinkedHashSet

8.

Enumeration

HashMap

9.

TreeMap

10.

HashTable

Page 100 of 191

COREJAVA
LinkedHashMap

11.

ArrayList:- It is dynamically growing array that stores objects. It is not synchronized 23.
1. To create an ArrayList
ArrayList arl = new ArrayList();
ArrayList arl = new ArrayList(100);
2. To add objects use add() method.
arl.add(Apple);
arl.add(2, Apple);
3. To remove objects use remove() method.
arl.remove(Apple);
arl.remove(2);
4. To know number of objects use size() method.
int n = arl.size();
5. To covert ArrayList into an array use toArray() method.
object x[ ] = arl.toArray();
Object is the super class of other classes including user defined classes also.
When we are retreiveing the elements from ArrayList, it will maintains and gives the same order
what we have added the elements to the ArrayList.
ArrayList doesnt supports the null values.
ArrayList supports sort method by using the below code
Collections.sort(al);
//al is ArrayList Class object reference.
Ex: //ArrayList creation with string objects
import java.util.*;
class ArrayListDemo
{
public static void main(String args[ ])
{
//Create an ArrayList
ArrayList arl = new ArrayList();
//Add elements to arl
arl.add(Apple);
//
Apple, Grapes, Guava, Banana are objects
arl.add(Grapes);
arl.add(Guava);
arl.add(Banana);
arl.add(Mango);
//Display the content of ArrayList (or) in arl
System.out.println(Array list = +arl);
//Remove elements
arl.remove(Apple);
arl.remove(2);
//Display the content of ArrayList (or) in arl
System.out.println(Array list = +arl);
//Find number of elements in arl
System.out.println(Size of Array list = +arl.size());
//Use Terator to retrieve elements
Iterator it = arl.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}

There are three types of interfaces are available, which are useful to retrieve the objects or elements one
by one from array list. They are
1. Iterator
2. ListIterator
3. Enumeration
23

Synchronized:- It means only one process will allow to act on one object.
Page 101 of 191

COREJAVA
Whatare the differencebetweenIteratorandListIterator:Iterator

ListIterator

1. Iterator supports only hasNext(), next() and


remove() methods.

1. Iterator supports add(), set(), next(), hasNext(),


previous(),
hasPrevious(),
nextIndex(),
previousIndex() and remove() methods.

2. Access the collections in the forward direction


only.

2. Access the collections in forward and backward


directions.

3. Iterator is a super interface

3. ListIterator is the sub interface of Iterator super


interface.

Whatare the differencebetweenIteratorandEnumeration:Iterator

Enumeration

1. Iterator supports a remove() method.

1. Enumeration doesnt supports a remove()


method.

2. It is not synchronized.

2. It is synchronized.

3. Iterator supports ArrayList, LinkedList,Vector,


HashMap, HashTable.

3.
Enumeration
doesnt
ArrayList,LinkedList, HashMap.

supports

4. It doesnt supports legacy methods.

4. It supports legacy methods


hasMoreElements(), nextElement().

like

as

Vector:- It is a dynamically growing array that stores objects. But it is synchronized.


When the object is synchronized then we will get reliable results or values. Vectors are suitable
objects.
1. To create a vector
Vector v = new Vector();
Vector v = new Vector (100);
2. To know the size of Vector, use size() method.
int n = v.size();
3. To add elements use add() method.
v.add(obj);
v.add(2, obj);
4. To retrieve elements use get() method
v.get(2);
5. To remove elements use remove() method
v.remove(2);
To remove all elements
v.clear();
6. To know the current capacity, use capacity() method
int n = v.capacity();
7. To search for last occurrence of an element use indexOf() method
int n = v . intdexOf(obj);
8. To search for last occurrence of an element use lastIndexOf() method
int n = v . lastIndexOf(obj);
9. Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of
components specified by the minimum capacity argument.
void ensureCapacity(int minCapacity);
ArrayList is not synchronized by default, but by using some methods we can synchronized the
ArrayList.
List myList = Collections.synchronizedList(myList);
Vector is synchronized default.
When we are retreiveing the elements from Vector, it maintains and gives the same order what
we have added the elements to the Vector.
Vector doesnt supports the null values.
Page 102 of 191

COREJAVA
Ex: -

//A Vector of int values


import java.util.*;
class VectorDemo
{
public static void main(String args[ ])
{
//Create an empty Vector
Vector v = new Vector ();
//Take (an one dimensional) int type array
int x [ ] = {10, 22, 33, 44, 60, 100};
//Read int values from x and store into v
for(int i = 0; i< x.lenght(); i++)
v.add(new Integer(x[ i ]));
//Retrieve and display the elements
for(int i = 0; i< v.size(); i++)
System.out.println(v.get(i));
//Retrieve elements using ListIterator
ListIterator lit = v. listIterator();
//In the above statement ListIterator is an Interface, listIterator() is a method
System.out.println(In forward direction: );
while(lit.hasNext())
System.out.print (lit.next() +\t);
System.out.println (\n In reverse direction: );
while(lit.previous())
System.out.print(lit.previous() + \t);
}
}

Whatare differencesbetweenArrayListandVector:ArrayList

Vector

1. An ArrayList is dynamically growing array that


stores objects.

1. Vector is dynamically growing array that stores


objects.

2. It is not synchronized.

2. It is synchronized.

3. It is efficient than Vector, due to ArrayList is fast


iterartion and fast random access.

3. It is not efficient than ArrayList, it is slower than


ArrayList due to its synchronized methods.

4. ArrayList supports only Iterator interface.

4. Vector supports Iterator and enumeration


interfaces.

5. ArrayList doesnt supports the legacy methods.

5. Vector supports the legacy methods like


hasMoreElements(), nextElement().

6. ArrayList doesnt supports the capacity(). Its


default capacity is 10.

6. Vector supports the capacity(). The default


capacity of vector is 10.

Maps: - A map represents storage of elements in the form of the key and value pairs. Keys must be
unique and keys cannot allow duplicate values.
HashTable:- Hashtable stores object in the form of keys and value pairs. It is synchronized.
1. To create a HashTable
HashTable ht = new HashTable();
//Initial
Capacity = 11, load factor = 0.75
HashTable ht = new HashTable(100);
2. To store key-Value pair the HashTable
ht.put(Sachin, Cricket Player);
3. To get the value when is given
ht.get(Sachin);
4. To remove the key (and its corresponding value)
ht.remove(Sachin);
5. To know the number of keys in the HashTable.
int n = ht.size();
Page 103 of 191

COREJAVA
6. To clear all the keys.
ht.clear();
Q) Whatis loadfactor?*****
Ans:- Load factor determines the point at which the capacity of HashTable or HashMap will be
automatically doubled.
Ex: - For HashTable initial capacity (11) X load factor (0.75) = 8
i.e. After storing 8th pair the capacity of the HashTable will be doubled i.e. becomes 22 (11 x 2).
Initial capacity = 11, this value depends on the version.
Ex: //HashTable with Cricket Scores
import java.util.*;
import java.io.*;
class HashtableDemo
{
public static void main(String args[ ])
throws IOException
{
//Create an empty hash table
HashTable ht = new HashTable();
//Store Player Name, Score
// Here Player Name is Key and Score is a Value
ht.put(Amarnadh, new Integer(50));
ht.put(Sachin, new Integer(150));
ht.put(Dhoni, new Integer(125));
ht.put(Kapil, new Integer(175));
ht.put(Ganguly, new Integer(86));
//Retrieve all keys
Enumeration e = ht.keys();
System.out.println(Player Name: );
While(e.hasMoreElements())
System.out.println(e.nextElement());
//Ask for Player Name from Keyboard
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
//
In the above statement (System.in) represents Keyboard
System.out.println(Enter Player Name: );
String name = br.readLine();
//Find number of runs of this player
Integer score = (Integer) ht.get(name);
if(score!=null)
{
int runs = score.intValue();
System.out.println(Name+Scored runs = +runs);
}
else
System.out.println(Player not found);
}
}
Ex 2: import java.util.*;
public class DemoHashTable {
public static void main(String[] args) {
Hashtable ht=new Hashtable();
ht.put("1", "Babu");
ht.put("2", "Anand");
ht.put("3", "Mogili");
ht.put("0", "@Marlabs");
System.out.println("---Retreiveing the elements--- = "+ht);
System.out.println(ht.get("1"));

Page 104 of 191

COREJAVA
System.out.println(ht.get("2"));
System.out.println(ht.get("3"));
System.out.println(ht.get("0"));
Enumeration e=ht.elements();
while(e.hasMoreElements()){
System.out.println("---Retreving the elements using enumeration from HashTable = "+e.nextElement());
}
Enumeration e1=ht.keys();
while(e1.hasMoreElements()){
System.out.println("---Retreving the keys using enumeration from HashTable =
"+e1.nextElement());
}
}
}
O/P: ---Retreiveing the elements--- = {3=Mogili, 2=Anand, 1=Babu, 0=@Marlabs}
Babu
Anand
Mogili
@Marlabs
---Retreving the elements using enumeration from HashTable = Mogili
---Retreving the elements using enumeration from HashTable = Anand
---Retreving the elements using enumeration from HashTable = Babu
---Retreving the elements using enumeration from HashTable = @Marlabs
---Retreving the keys using enumeration from HashTable = 3
---Retreving the keys using enumeration from HashTable = 2
---Retreving the keys using enumeration from HashTable = 1
---Retreving the keys using enumeration from HashTable = 0
Ex 3: import java.util.*;
public class DemoHashTable {
public static void main(String[] args) {
Hashtable ht=new Hashtable();
ht.put("1", "Babu");
ht.put(null, "Anand"); (or) ht.put(2, null);
ht.put("3", "Mogili");
ht.put("0", "@Marlabs");
System.out.println("---Retreiveing the elements--- = "+ht);
System.out.println(ht.get("1"));
System.out.println(ht.get("2"));
System.out.println(ht.get("3"));
System.out.println(ht.get("0"));
Enumeration e=ht.elements();
while(e.hasMoreElements()){
System.out.println("---Retreving the elements using enumeration from HashTable =
"+e.nextElement());
}
Enumeration e1=ht.keys();
while(e1.hasMoreElements()){
System.out.println("---Retreving the keys using enumeration from HashTable =
"+e1.nextElement());
}
}
}
O/P: Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Unknown Source)
at com.marlabs.vara.DemoHashTable.main(DemoHashTable.java:7
Page 105 of 191

COREJAVA
Enumeration will not maintain objects in the same order.
IOException may caused by readLine() method. IO stands for input/output.
Playernames are all keys and scores are all values.
When we retreving the elements or keys using HashTable it will gives the elements or keys in
revrse order only.
In HashTable duplicate keys are not allowed but duplicate values are allowed.
HashMap:- HashMap stores objects in the form of keys and value pairs. It is not synchronized.
1. To create a HashMap
HashMap hm = new HashMap();
//Initial
Capacity = 16, load factor = 0.75
HashMap hm = new HashMap(101);
2. To store key-Value pair the HashMap
hm.put(Sachin, Cricket Player);
3. To get the value when is given
hm.get(Sachin);
4. To remove the key (and its corresponding value)
hm.remove(Sachin);
5. To know the number of key-value pairs in the HashMap.
int n = hm.size();
6. To clear all the keys.
hm.clear();
HashMap is similar to HashTable but the difference between these two is HashTable is
synchronized but HashMap is not synchronized
When we retreving the elements or keys using HashMap it will gives the elements or keys
irregular order, not even the same order that we have added keys and elements.
In HashMap duplicate keys are not allowed but duplicate values are allowed.
Map myMap = Collections.synchronizedMap(myMap);
Ex: //Telephone entry book
import java.util.*;
import java.io.*;
class Tele
{
public static void main(String args[ ])
throws IOException
{
//Vars
HashMap hm = new HashMap();
String name, str;
Long phno;
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
//Menu
while(true)
//It is an infinite loop
{
System.out.println(1 Enter entries into Phone Book);
System.out.println(2 Lookup for a Phone Number);
System.out.println(3 Exit);
int n = Integer.parseInt(br.readLine());
//Depending on n value, perform a task
switch(n)
{
case 1:
System.out.print(Enter Person Name: );
Name = br.readLine();
System.out.print(Enter Phone No. );
str = br.readLine();
//Convert str into Long obj
phno = new Long(str);
Page 106 of 191

COREJAVA
//Store name, phone in hm
break;
case 2:
System.out.print(Enter Person Name);
name = br.readLine();
//Pass name to hm and get the Phone No.
phno = (Long)hm.get(name);
System.out.println(Phone No: +phno);
break;
default:
return;
}
}
}
}
Ex 1: import java.util.*;
public class DemoHashmap {
public static void main(String args[]){
HashMap hm=new HashMap();
System.out.println("---HasMap initial size---"+hm.size());
hm.put("1", "Vara");
hm.put("2", "anji");
hm.put("3", "anand");
hm.put("4", "bujji");
System.out.println("---HasMap size---"+hm.size());
System.out.println("---Retrieving the elements HasMap---"+hm);
System.out.println(hm.get("4"));
System.out.println(hm.get("1"));
System.out.println(hm.get("3"));
System.out.println(hm.get("2"));
Set s=hm.keySet();
Iterator it=s.iterator();
while(it.hasNext())
System.out.println("Retreiveing the Keys = "+it.next());
}
}
O/P: ---HasMap initial size---0
---HasMap size---4
---Retrieving the elements HasMap---{3=anand, 2=anji, 4=bujji, 1=Vara}
bujji
Vara
anand
anji
Retreiveing the Keys = 3
Retreiveing the Keys = 2
Retreiveing the Keys = 4
Retreiveing the Keys = 1
Ex 2: import java.util.*;
public class DemoHashmap {
public static void main(String args[]){
HashMap hm=new HashMap();
System.out.println("---HasMap initial size---"+hm.size());
hm.put("1", "Vara");
hm.put(null, null);
hm.put("3", null);
Page 107 of 191

COREJAVA
hm.put("4", "bujji");
System.out.println("---HasMap size---"+hm.size());
System.out.println("---Retrieving the elements HasMap---"+hm);
System.out.println(hm.get("4"));
System.out.println(hm.get("1"));
System.out.println(hm.get("3"));
System.out.println(hm.get("2"));
Set s=hm.keySet();
Iterator it=s.iterator();
while(it.hasNext())
System.out.println("Retreiveing the Keys = "+it.next());
}
}
O/P: ---HasMap initial size---0
---HasMap size---4
---Retrieving the elements HasMap---{null=null, 3=null, 4=bujji, 1=Vara}
bujji
Vara
null
null
Retreiveing the Keys = null
Retreiveing the Keys = 3
Retreiveing the Keys = 4
Retreiveing the Keys = 1
Whatare differencesbetweenHashMapand HashTable:HashMap

HashTable

1. It stores the objects in the form of key and value


pairs.

1. It stores the objects in the form of key and value


pairs.

2. It is not synchronized.

2. It is synchronized.

3. It will makes fastest updates (key/value pairs)


so it is efficient than HashTable.

3. It is not efficient than HashMap due to its


synchronized methods.

4. It supports only Iterator interface.

4. HashTable supports Iterator and enumeration


interfaces.

5. It doesnt supports legacy methods.

5.
It
supports
legacy
methods
hasMoreElement(), nextElement().

6. HashMap initial capacity is 16 and the capacity


of HashMap depends on version of Java.

6. HashTable initial capacity is 11 and the capacity


of HashTable depends on version of Java.

7. HashMap doesnt maintained the orderd of


elements, not even the keys and the elements
added to it.

7. HashTable maintained the orderd of elements in


reverse.

8. HapMap takes only one null key and many null


values.

8. HashTable doesnt takes null keys and null


values.

like

StringTokenizer:- The StringTokenizer class is useful to break a string into small pieces, called tokens.
1. To create an object to StringTokenizer
StringTokenizer st = new StringTokenizer(str, delimiter);
(or)
StringTokenizer st = new StringTokenizer(str, ,);
(or)
StringTokenizer st = new StringTokenizer(str, , :);
Here , : are called as delimiters
2. To find the next piece in the string.
String piece = st.nextToken();
3. To know if more pieces are remaining.
booleab x = st.hasMoreTokens();
4. To know how many number of pieces are there.
int no = st.countTokens();

Page 108 of 191

COREJAVA
Token means piece of string.
Ex: //Cutting the string into pieces
import java.util.*;
class STDemo
{
public static void main(String args[ ])
{
//Take a string
String str = It is our capital city called New Delhi;
//brake the string into species
StringTokenizer st = new StringTokenizer(str, );
//retrieve the pieces and display
System.out.println(The token are: );
while(st.hasMoreTokens())
{
String s1 = st.nextToken();
System.out.println(s1);
}
}
}
(or)
//Cutting the string into pieces
import java.util.*;
class STDemo
{
public static void main(String args[ ])
{
//Take a string
String str = It, is our: capital city, called New: Delhi;
//brake the string into species
StringTokenizer st = new StringTokenizer(str, , : );
//retrieve the pieces and display
System.out.println(The token are: );
while(st.hasMoreTokens())
{
String s1 = st.nextToken();
System.out.println(s1);
}
}
}

Form
Name

Server

Address

Section
Name
Ok
Calendar:- This class is useful to handle, date & time.
1. To create an object to calendar class:
Calendar cl = Calendar.getInstance();
2. Use get() method to retrieve date or time from calendar object. This method returns an integer.
cl.get(constant);
Page 109 of 191

COREJAVA
Note: Constants:Calendar.DATE
Calendar.MONTH
Calendar.YEAR
Calendar.HOUR
Calendar.MINUTE
Calendar.SECOND
3. Use set() to get the date or time in the calendar object.
cl.set(calendar.MONTH,10); //Default counting of January month starts with 0
booleab x = st.hasMoreTokens();
4. To convert a date into string, use toString(). This method returns a string.
cl.toString();
Gregorian calendar is another type class like as calendar class.
Ex: //System date and time
import java.util.*;
class Cal
{
public static void main(String args[ ])
{
//Create an obj to calendar class
Calendar cl = Calendar.getInstance();
//retrieve date details
int dd = cl.get(Calendar.DATE);
int mm = cl.get(Calendar.MONTH);
int yy = cl.get(Calendar.YEAR);
++mm;
System.out.println(System date: );
System.out.println(dd+ / +mm+ / +yy);
//retrieve time details
int h = cl.get(Calendar.HOUR);
int m = cl.get(Calendar.MINUTE);
int s = cl.get(Calendar.SECOND);
System.out.println(System time: );
System.out.println(h+ : +m+ : +s));
}
}
Date Class:- Date class is class useful to handle date and time.
1. To create an object to Date class.
Date d = new Date();
2. Format the date and times using getDateInstance() or getDateTimeInstance() methods of DateFormat
class. This is in java.txt package.
Syntax:- DateFormat fmt = DateFormat.getDateInstance(formatconst, region);
Here region is the place/the country.
Ex:-DateFormat fmt=DateFormat.getDateInstance(DateFormat.Medium, Locale.UK);
Syntax:- DateFormat fmt = DateFormat.getDateInstance(formatconst, formatconst
region);
Ex: - DateFormat fmt = DateFormat.getDateInstance(DateFormat.Medium,
DateFormat.SHORT, Locale.US);
Note: ---------------------------------------------------------------------------------------------------------------formatconst
Example(region= LocaleUK)
---------------------------------------------------------------------------------------------------------------DateFormat.LONG
03 September 2004 19:43:14 GMT + 5.30
DateFormat.FULL
03 September 2004 19:43:14 oclock GMT + 5.30
DateFormat.MEDIUM 03-Sep-04 19:43:14
DateFormat.LONG
03/09/04 7.43 pm
---------------------------------------------------------------------------------------------------------------Page 110 of 191

COREJAVA
3. Applying format to Date object is done by format () method.
String str = fmtt.format(d);
Ex: //To display system date and time
import java.util.*;
import java.text.*;
class MyDate
{
public static void main(String args[ ])
{
//Create an obj to Date class
Date d = new Date();
//Store the format in DateFormat obj
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, Locale.UK);
//Applying the format to d
String s = fmt.format(d);
//Display the formatted date and time
System.out.println(System date and time: +s);
}
}
Here d represents the system date & time already consists after creating an object.
H.W.
1. Create an Employee class with an employees id, name, and address store objects of this class in an
ArrayList. When an employees ID is given, display his name and address.
2. Create a vector with a group of strings. Sort them and display them in a ascending order. Display them
in reverse order also?
3. Create HashTable with some students hall tickets no.s & their results. Type a hall ticket number and
display his result?
4. Cut the string into pairs of pieces: India=>Delhi, America=>Washington, Britain=>London,
France=>Paris
Now display the token as given below.
City
Capital
Delhi
India
Washington
America
London
Britain
Paris
France

Q) Whatis the differencebetweenObservableandObserver?*****


Ans:- Observable is a class is used to create subclasses that other parts of our program can observe.
When an object of such a subclass undergoes a change, Observing classes are notified. Observing
classes must implement the Observer interface. It will have more methods than Observer interface.
An Observer is an interface, which is useful to observe an observable object, and must
implement the observer interface. This interface will defines only one method i.e. void update(Observable
observOb, Object arg). Here observOb is the object being observed, and arg is the value passed by
notifyObservers(). The update() method is called when a change in the observed object take place.
Stream: - A stream represents flow of data from one place to another place. They are two types of
streams,
1. Input Streams:- It receives or reads the data to output stream.
2. OutputStream:- It sends or writes the data to some other place.
Streams are represented by classes in java.io package.
Streams (java.io): - A stream is a sequence of bytes, or characters traveling from source to a destination.
When the bytes passing then it is called as byte stream and when the characters are passing
then it is called as character stream.
To handle data in the form of bytes, the abstract class: InputStream and OutputStream are
used.
InputStream
|
Page 111 of 191

COREJAVA
---------------------------------------------------------------------|
|
FilterInputStream
ObjectInputStream
|
----------------------------------------|
|
BufferedInputStream
DataInputStream

|
FileInputStream

OutputStream
|
----------------------------------------------------------------------|
|
|
FileOutputStream
FilterOutputStream
ObjectOutputStream
|
----------------------------------------|
|
BufferedOutputStream DataOutputStream
a) FileInputStream/FileOutputStream:- They handle data to be read or written to disk files.
b) FilterInputStream/FilterOutputStream:- They read data from one stream and write it another stream.
c) ObjectInputStream/ObjectOutputStream:- They handle storage of objects and primitive data.
Storing objects in a file called serialization.
Retrieving the data from files is called de-serialization.
Reader
|
----------------------------------------------------------------------------------------------|
|
|
|
BufferedReader
CharArrayReader
IntputStreamReader
PrintReader
|
FileReader
Writer
|
----------------------------------------------------------------------------------------------|
|
|
|
BufferedWriter
CharArrayWriter
IntputStreamWriter
PrintWriter
|
FileWriter
ByteStream stores the data in the form of bytes, CharacterStream stores the data in the form of
characters.
Buffered means a block of memory.
a) BufferedReader/BufferedWriter: - Handles character (text) by buffering them. They provide efficiency.
b) CharArrayReader/CharArrayWriter:- Handles array of characters.
c) InputStreamReader/OutputStreamWriter: - They are bridge between byte streams and character streams.
Reader reads bytes and then decode them into 16-bit Unicode character, write decodes character into
bytes and then write.
d) PrinterReader/PrinterWriter:- Handle printing of characters on the screen.
A file is an organized collection of data.

HowcanyouimproveJavaI/O performance:
Java applications that utilise Input/Output are excellent candidates for performance tuning.
Profiling of Java applications that handle significant volumes of data will show significant time spent in
I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O
efficiency should be a high priority for developers looking to optimally increase performance. The basic
rules for speeding up I/O performance are:
? Minimise accessing the hard disk.
Page 112 of 191

COREJAVA
? Minimise accessing the underlying operating system.
? Minimise processing bytes and characters individually.
Let us look at some of the techniques to improve I/O performance.
? Use bufferingto minimise disk access and underlying operating system. As shown below, with buffering
large chunks of a file are read from a disk and then accessed a byte or character at a time.
Withoutbuffering: inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
WithBuffering:yieldsbetter performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note: bis.read() takes the next byte from the input buffer and only rarely access the underlying operating
system.
Instead of reading a character or a byte at a time, the above code with buffering can be improved
further by reading one line at a time as shown below:
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
While (br.readLine() != null) count++;
By default the System.out is line buffered, which means that the output buffer is flushed when a
new line character is encountered. This is required for any interactivity between an input prompt and
display of output.
The line buffering can be disabled for faster I/O operation as follows:
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
PrintStream ps = new PrintStream(bos,false);
System.setOut(ps);
while (someConditionIsTrue)
System.out.println(blahblah);
}
Usesof files: 1. We can store the data permanently into the hard disk. (When we are strong the data in HashTable,
vector etc the data will store temporarily on the RAM).
Page 113 of 191

COREJAVA
2. Once we stored the data in the form of file we can share that data in different programs.
The above two are main advantages of file.
System.in it is a InputStream object
Here System is a class java.io. package.
in is a field.
System.in InputStream obj Keyboard
System.out PrintSream obj Monitor
System.err PrintSream obj Monitor
System.out will displays normal messages on the monitor, System.err will displays error
messages on the monitor.
Q) Whatis use of Stream?*****
Ans:- Stream will handle input/output devices. The achieving the hardware independent of java
programs we are using stream.

DataInputStream

System.in

FillOutputStrea
m

myfile

Ex: -

//Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(myfile);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(Enter data (@at end): );
while((ch = char) dis.read()) != @)
fout.write(ch);
//close the file
fout.close();
}
}
After executing & running the program, we can also open file using command type (i.e. a MsDos Command). Every time executing & running the program old data will be remove/overwrite and new
data will stored. To overcome this problem or to appending the data we have to use true in the following
statement.
FileOutputStream fout = new FileOutputStream(myfile, true);
Ex: //Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
Page 114 of 191

COREJAVA
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(myfile, true);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(Enter data (@at end): );
while((ch = char) dis.read()) != @)
fout.write(ch);
//close the file
fout.close();
}
}
To improve the efficiency or the speed of execution of program we to use Buffered class.
BufferedOutputStream bos = new BufferedOutputStream(fout, 1024);
Default size used by any Buffered class is 512 bytes.
In the place of fout.write(); we have to use bos.write(); and in the place of fout.close(); we have to
use bos.close();
Ex: //Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(myfile, true);
BufferedOutputStream bos = new BufferedOutputStream(fout, 1024);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(Enter data (@at end): );
while((ch = char) dis.read()) != @)
bos.write(ch);
//close the file
bos.close();
}
}
Ex: //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
throws IOException
{
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(myfile);
//now read from FileInputStream and display
int ch;
while((ch = fin.read()) != -1)
System.out.println((char)ch);
//close the file
fin.close();
}
}
Ex: //Reading data from a text file
import java.io.*;
Page 115 of 191

COREJAVA
class Read1
{
public static void main(String args[ ])
throws IOException
{
BufferedInputStream bin = new BufferedInputStream(fin);
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(myfile);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
}
Ex: //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
throws IOException
{
try{
//to enter filename from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.ot.print(Enter file name: );
String fname = readLine();
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(fname);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
catch(FileNotFoundException fe)
{
System.out.println(File not found);
}
}
Ex: //Creating a file
import java.io.*;
class Create2
{
public static void main(String args[ ])
throws IOException
{
//to write data into file
FileWriter fw = new FileWriter(myfile1.txt);
//take string
String str = This is an institute + \nIam a student here;
//read char by char from str and write into fw
for(int i = 0; i<str.length(); i++)
fw.write(str.charAt(i));
//close the file
fw.close();
Page 116 of 191

COREJAVA

Ex: -

Ex: -

Ex: -

}
}
//Creating a file
import java.io.*;
class Create3
{
public static void main(String args[ ])
throws IOException
{
//to write data into file
FileWriter fw = new FileWriter(myfile1.txt);
BufferedWriter bw = new BufferedWriter(fw, 1024);
//take string
String str = This is an institute + \nIam a student here;
//read char by char from str and write into fw
for(int i = 0; i<str.length(); i++)
bw.write(str.charAt(i));
//close the file
bw.close();
}
}
//Reading data from the file
import java.io.*;
class Read2
{
public static void main(String args[ ])
throws IOException
{
//attach file to FileReader
FileReader fr = new FileReader(myfile1.txt);
//now read data from fr and dispaly
int ch;
while((ch = fr.read()) != -1)
System.ot.println((char)ch);
//close the file
fr.close();
}
}
//Creating a file
import java.io.*;
class Read3
{
public static void main(String args[ ])
throws IOException
{
//attach file to FileReader
FileReader fr = new FileReader(myfile1.txt);
BufferedReader br = new BufferedReader(fr, 512);
//now read data from fr and dispaly
int ch;
while((ch = br.read()) != -1)
System.ot.println((char)ch);
//close the file
br.close();
}
}
1001
Rama
7000.05

Page 117 of 191

COREJAVA
EMPID
EMPNAME
EMPSAL
ObjectStream
JDBC is more convenience to handle or storing and retrieve the data from the table form.
ZippingandUnzippingthe file: -

Most repeated bit pattern


0

11111111
00000000

1
Zip

10101010
00001111

WinZip Software

01
101
Zipped file

File

1. File converts to compressed.


2. File format is changed.
In java language to zip and unzip a file we will use below two classes.
1. DeflaterOutputStream: - It is used to zip the file.
2. InflaterOutputStream: - It is used to unzip the file.
These above two classes are in java.util.zip packagae.
Ex: //Zipping
import java.util.*;
dos
import java.util.zip.*;
Writing
Writing
class Compress
here
here
{
public static void main(String args)
File
2
File 1
throws Exception
{
attach fos
attach fos
//attach file1 to FileInputStream
FileInputStream
fis
=
new
FileInputStream(file1);
//attach file2 to FileOutputStream
FileOutputStream fos = new FileOutputStream(file2);
//attach fos to DeflaterOutputStream
DeflaterOutputStream dos = new DeflaterOutputStream(fos);
//read data from fis and write into dos
int data;
while((data = fis.read()) != -1)
dos.write(data);
//close the files
fis.close();
dos.close();
}
}
Here we have to create file1 using Ms-Dos Edit command save it and then execute the java file.
Ex: //UnZip
import java.util.*;
dos
import java.util.zip.*;
Writing
Writing
class UnCompress
here
here
iis
{
File
2
File
3
public static void main(String args)
throws Exception
{
attach fis
attach fos
//attach file2 to FileInputStream
FileInputStream fis = new FileInputStream(file2);
//attach file3 to FileOutputStream
FileOutputStream fos = new FileOutputStream(file3);
Page 118 of 191

COREJAVA
//attach fis to InflaterInputStream (iis)
InflaterInputStream iis = new InflaterInputStream (fis);
//read data from iis and write into fos
int data;
while((data = iis.read()) != -1)
fos.write();
//close the files
iis.close();
fos.close();
}
}
H. W.
5. Copy a file content into another file (new file)
6. Append the contents of one file to another file existing file.
7. Count the no. of characters, words, and lines in a text file.
Network: Inter connections of computers is called Network.
A client is a machine that sends a request for some service.
Server is a machine that provides service to the clients.
Internet is a network of all the computers existing on the earth.
ISP Internet Service Provider.
The software which is available on the server is called Web Server.
Ex: - Apache, Tomcat, Web Logic, Web Sphere, etc
Protocol represented by a set of rules, to be followed by every computer in network.
Ex: - TCP/IP Transmission Control Protocol/Internet Protocol
HTTP is most widely used protocol on internet.
FTP (File Transfer Protocol) is used when we are downloading files.
SMTP (Short Mail Transfer Protocol) is used for sending mails.
POP (Post Office Protocol) is used to receiving mails.
Internet protocol address is a Unique ID number is given to every computer in network.
Ex: 192.45.50.01 ----- It is a IP address of server.
192.45.50.01 --------- is a equal to like www.yahoo.com
DNS Domain Naming System, It will convert the name into the IP address.
The current version of IP address is 6, which uses 16 bytes.
Class A 0
Network 7bits
Local Address 24bits
16,777,216 Hosts
Class B 10
Network 14bits Local Address 16bits
65,536 Hosts
Class C 110
Network 21bits Local Address 8bits
256 Hosts
Class D
Class E Research/Experimental works
Classes are of IP address.
Host means Server.
Socket: - A socket is a point of connection to connect a client
and server.
Every socket has an ID No. that is Port No. An ID
number is allotted to a socket is called Port number.

Server

Client

Socket

Q) Whenyouwill changesocketnumber?*****
Page 119 of 191

COREJAVA
Ans: -

1. When we use new socket we use a new port number.


2. On the same socket if the service changes.

Someallottedport numbers:S. No.

Port Number

Application

1.

13

Date and time services.

2.

21

FTP, which transfer files.

3.

23

Telnet, which provides remote login.

4.

25

SMTP, which delivers mail messages.

5.

67

BOOTP, which provides configuration at boot time.

6.

80

HTTP, which transfer webpage

7.

109

POP, this enables users to access mail boxes on remote system.

Ex: -

java.net package contains classes to create a socket for server and client.
Socket is a class to create a Socket client side.
ServerSocket is a class to create a Socket server side.
These two classes are in java.net package.
//Create a server that sends messages
import java.io.*;
import java.net.*;
class Server
Server
{
public static void main(String args)
Socket
throws Exception
{
//Create Server Socket
Client
ServerSocket
ss=
new
Socket
ServerSocket(777);
//make that Socket accepts Client
connection
Socket s = ss.accept();
System.out.println(Connection Established);
//attach OutputStream to Socket
OutputStream obj = s.getOutputStream();
//to send data to the Socket
PrintStream ps = new PrintStream(obj);
//now send data
String str = Hello;
ps.println(str);
ps.println(Bye);
//Disconnect the Server
s.close();
ps.close();
}
}
Now compile this program and dont run it, then we have to create socket for client side.
[
To display IP address we have to use command igcong
Syntax: -C:\rnr>ipconfig
]
Ex: //A Client that receives data
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String args)
Page 120 of 191

COREJAVA
throws Exception
{
//Create Client Socket
Socket s= new Socket(ipaddress/loacalhost, 777);
//attach InputStream to Socket
InputStream obj = s.getInputStream();
//To receive the data to this Socket
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
//Accept data coming from Server
String str;
while(str=br.readLine()) !=null)
System.out.println(str);
//Disconnect the Server
s.close();
br.close();
}
}
We can run as many JVMs at a time.
Communicatingfro Server:1. Create a ServerSocket
ServerSocket ss = new ServerSocket(Port No.);
2. Accept any Client
Socket s = ss.accept(); ------ It returns Socket object.
3. To send data, connect the OutputStream to the Socket
OutputStream obj = s.getOutputStream();
4. To receive data from the Client, connect InputStream to the Socket
InputStream obj = s.getInputStream();
5. Send data to the Client using PrintStream
Ex: PrintStream ps = new PrintStream(obj);
ps.print(str);
ps.println(str);
6. Read data coming from the Client using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
ch = br.read();
str = br.readLine();
CommunicatingfromClient: 1. Create a Client Socket
Socket s= new Socket(ipaddress/loacalhost, 777);
2. To send data connect the OutputStream to the Socket
OutputStream obj = s.getOutputStream();
3. To receive data fro the Server, connect InputStream to the Socket
InputStream obj = s.getInputStream();
4. Send data to the Server using DataOutputStream.
Ex: DataOutputStream dos = new DataOutputStream(obj);
Dos.writebyte(str);
5. Read data coming from the Server using BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
ch = br.read();
str = br.readLine();
3. ClosingCommunication:Close all Streams and Sockets
ps.close();
br.close();
dos.close();
ss.close();
s.close();
RMI (Remote Method Invocation) It is a technology to call and use remote methods of remote
objects.
Page 121 of 191

COREJAVA
Ex: -

//Chat Server
import java.io.*;
import java.net.*;
class Server2
{
public static void main(String args)
throws Exception
{
//Create Server Socket
ServerSocket ss= new ServerSocket(888);
Reference
//make this Socket wait for Client connection
Socket s = ss.accept();
System.out.println(Connection Established);
//to send data to the Client
PrintStream ps = new PrintStream(s.getOutputStream());
//to receive data from Client
BufferedReader br = new BufferedReader(newInputStreamReader (s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now communicate
while(true)
// Server runs continuously
{
String str, str1;
while(str = br.readLine() != null)
{
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
//Disconnect the Server
ss.close();
s.close();
ps.close();
br.close();
kb.close();
System.exit(0);
}
}
}
Ex: //Chat Client
import java.io.*;
import java.net.*;
class Client2
{
public static void main(String args)
throws Exception
{
//Create Client Socket
Socket s= new Socket(Localhost, 888);
//to send data to the Server
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//to receive data from Server
BufferedReader br=new BufferedReader(new InputStream(s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now start communicate
String str, str1;
while(str = br.readLine() .equals(exit))
Page 122 of 191

Object

COREJAVA
//As long as the String are not typing exit.
{
dos.writeBytes(str+\n);
str1 = br.readLine();
System.out.println(str1);
}
//Disconnect the Server
s.close();
dos.close();
br.close();
kb.close();
}
}
H. W.
8. Develop a server that sends to system data and time to the client display that data and time at client
side (Hint: Use Port No.13)
9. Write client server programs so that the client sends the name of a file to the server and the server
sends the file content to client display the file contents at client side (the file should present in the server).

Multi Threading
Thread: - A thread represents a process of execution (or) executing the set of statements is called a
thread.
Every java program is executed by using one thread i.e. is called main thread.
JVM will execute statements step by step.
//Every java program has a thread
---------class Current
---------JVM
{
---------or
public static void main(String args)
Microprocessor
{
Statements
System.out.println(This is first line);
Thread t = Thread.currentThread();
System.out.println(Present thread = +t);
System.out.println(Its name = +t.getName());
}
}
C:\rnr>javac Current.java
C:\rnr>java Current
O/P: - This is first line
Present Thread = Thread[main, 5, main]
Here main is a thread name.
5 is the Priority Number.
[main, 5, main] is called as Thread group.
From the above thread name is main. Thread has priority number. Priority number will varies
from 1 to 10.
Priority No. 1 -------
Minimum Priority
Priority No. 5 ------- Normal Priority
Priority No. 10 -------
Maximum Priority
Main thread priority number is 5.
We can provide more threads to the microprocessor. Microprocessor will execute the 10billions
of machine code instructions per second.
Executing the tasks (one or more statements is two types.
1. Singletasking:- Executing one task at a time is called
single tasking. In a Single tasking lot of processor
Task
time wasted.
Microprocessor
Ex: -

Page 123 of 191

COREJAVA
TimeSlice: - Time slice is the time allotted by the Microprocessor to execute each task.

Microprocessor

Memory
Task
0.25ms

0.25ms

0.25ms

0.25ms

Microprocessor will allot equal timings (0.25milli seconds)


for each task.

RoundRobinMethod:- Microprocessor uses round robin method to execute several tasks simultaneously.
Executing first task after last task is called round robin method.
Ex: - Robin is a bird which will comes down by making rounds and it will jump up by making rounds thats
why they have compared the microprocessor like that above.
2. Multitasking:- Executing several tasks simultaneously is called multitasking.
a) Processbasedmultitasking:- Executing several programs at a time is called process based multitasking.
Time slice, Round robin methods are process based multitasking.
b) Thread based multitasking: - Executing several
Three
parts of a program simultaneously is called
Microprocessor
thread based multitasking.
diff.
Using more than one thread is called
types
multithreading to perform multiple tasks
of
simultaneously at a time.
blocks
Createa thread:1. Write a class that extends thread class or
implements runnable interface.
Thread class, runnable implements will helpful to create a thread. These two are available in
java.lang package.
2. Write public void run in the class thread will execute only this method.
public void run()
Thread cant act upon any method, but default it works only on run() method.
3. Create an object to the class.
4. Attach a thread to this object.
5. Start thread, then will act upon that object.
Ex: //Creating thread
Class MyThread extend Thread
{
public void run()
{
for(int i = 1; i<100000; i++)
{
System.out.println(i);
}
}
}
class TDemo
{
public static void main(String args[ ])
{
MyThread obj = new MyThread();
Page 124 of 191

COREJAVA
Thread t1 = new Thread();
t1.start();
}
}
stop() method is used to stop the thread in old versions. But stop() method is deprecated in new
versions.
Forcibly to terminate the program we have to use control + c (Ctrl+c keys in the keyboard).
To stop the thread also we have to use control + c keys.
Ex: //Creating thread and smoothly terminate/stop the program or thread
Import java.io.*;
Class MyThread extend Thread
{
run()
boolean stop = false;
{
public void run()
----{
----for(int i = 1; i<100000; i++)
Microprocessor
}
{
System.out.println(i);
if(stop) return;
object
}
}
}
class TDemo
{
public static void main(String args[ ])
{
MyThread obj = new MyThread();
Thread t1 = new Thread();
t1.start();
System.in.read();
obj.stop = true;
}
}
This above program is for stopping the thread smoothly.
Q) Howcanyoustopthe threadwhichis running?*****
Ans:- 1. Declare a boolean variable and initialize it as false
Ex: boolean stop = false;
2. When ever the thread should be stopped store true into this variable
Ex: obj.stop = true;
3. If the variable becomes true using return statement come out run() method
Ex: if(stop) return;

Q) Whatis the differencebetweenextendsand implementRunnable?Whichone is advantage?*****


Ans:There is no difference between these two. Implement Runnable is advantage because
interfaces is always better than classes.
If we extend thread class, there is no scope any another class, this is the limitation of extends.
If we implement Runnable interface still there is a scope to extend other class.
The main advantage of multitasking is utilizing a processor time in an optimum way.
Ex: //Theatre Example
class MyThread implements Runnable
{
String str;
MyThread(String str)
{
this.str = str;
}
Page 125 of 191

COREJAVA
public void run()
{
for(int i = 1; i<=10; i++)
{
System.out.println(str+ : +i);
try{
Thread.sleep(2000);
}catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}

run()
{
--------}

Microprocessor

object
run()

}
{
class Theatre
----{
----t1 thread
public static void main(String args[ ])
}
{
//create objects to MyThread class
Microprocessor
object 1
MyThread obj1=new MyThread(Cut ticket);
MyThread obj2=new MyThread(Show ticket);
run()
//Create two threads and attach them to
t2 thread
{
//these two objects
----Thread t1 = new Thread(obj1);
----Thread t2 = new Thread(obj2);
//start the thread
}
t1.start();
object 2
t2.start();
}
}
When multiple threads are acting on the one or same object we will get sometimes unreliable
results.
Ex: //Two threads acting on one object
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve (int i)
{
wanted = i;
}
public void run()
{
System.out.println(Number of berths available = +available);
if(available >= wanted)
{
String name = Thread.currentThread.getName();
System.out.println(wanted + berths reserved for+name);
try{
Thread.sleep(2000);
available = available wanted;
}
catch(Interrupted Exception ie){ }
}
else
System.out.println(Sorry, no berths to reserve);
}
Page 126 of 191

COREJAVA
}
class Syn
{
public static void main(String args[ ])
{
//create an obj to Reserve class with 1 berth
Reserve obj = new Reserve(1);
//create 2 threads and attach them to obj
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
//give names to threads
t1.setName(First Person);
t2.setName(Second Person);
//run the threads
t1.start();
t2.start();
}
}
This above program will allot tickets for both persons. For this permanent solution we have to
block the 2nd thread till the completion of the 1st thread. So we have to use synchronization method to
block the 2nd thread.
Ex: //Two threads acting on one object
class Reserve implements Runnable
{
int available = 1;
2nd thread
st
int wanted;
1 thread
Reserve (int i)
{
wanted = i;
------------------}
public void run()
------------------synchronized(obj)
------------------{
System.out.println(Number of berths available = +available);
if(available >= wanted)
------------------object
{
------------------Synchronization
String name = Thread.currentThread.getName();
-System.out.println(wanted + berths reserved for+name);
try{
Thread.sleep(2000);
available = available wanted;
}
catch(Interrupted Exception ie){ }
}
else
System.out.println(Sorry, no berths to reserve);
}
}
}
class Syn
{
public static void main(String args[ ])
{
//create an obj to Reserve class with 1 berth
Reserve obj = new Reserve(1);
//create 2 threads and attach them to obj
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Page 127 of 191

COREJAVA
//give names to threads
t1.setName(First Person);
t2.setName(Second Person);
//run the threads
t1.start();
t2.start();
}
}
ThreadSynchronization(or) Synchronization: - Synchronization is locking the object, so that when a thread is
processing object any other thread will not be allowed to act upon the object. Synchronized object is also
called as Mutex i.e. Mutually Exclusive lock.
An object can be synchronized in two ways
1. Synchronizedblock(): synchronized(obj)
{
For group of statements we can use this synchronized
statements;
block.
}
Ex: - class BlockLevel{
//shared among threads
SharedResource x, y ;
//dummy objects for locking
Object xLock = new Object(), yLock = new Object();
pubic void method1() {
synchronized(xLock){
//access x here. thread safe
}
//do something here but don't use
SharedResource x, y ;
synchronized(xLock){
synchronized(yLock){
//access x,y here. thread safe
}
}
//do something here but don't use
SharedResource x, y ;
}
}
2. By making a method as synchronized method
synchronized void method()
{
For entire method to synchronized we will use
statements;
this method.
}
Ex: class MethodLevel{
//shared among threads
SharedResource x, y ;
pubic void synchronized
method1() {
//multiple threads can't access
}
pubic void synchronized
method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
Page 128 of 191

COREJAVA
Synchronizationimportant: - Without synchronization, it is possible for one thread to modify a shared object
while another thread is in the process of using or updating that objects value. This often causes dirty
data and leads to significant errors.
Disadvantageof synchronizationis that it can cause deadlocks when two threads are waiting on each other
to do something. Also synchronized code has the overhead of acquiring lock, which can adversely the
performance.
Synchronization is also known as thread safe, unsynchronized is also known as thread unsafe.
Locking means it will not allow another thread still the completion of one task of one thread.
Ex: //To cancel the ticket
Class CancelTicket extends Thread
{
object train, comp;
CancelTicket(object train, object comp)
Thread 1 CancelTicket
{
this.train = train;
this.comp = comp;
100ms
comp.obj
}
public void run()
{
synchronized(comp)
{
System.out.println(CancelTicket locked the
train.obj
200ms
compartment);
try{
sleep(100);
BookTicket
Thread 2
}catch(InterruptedException ie){ }
System.out.println(CancelTicket wants to lock on
train);
synchronized(train)
{
System.out.println(CancelTicket now locked train);
}
}
}
}
class BookTicket extends Thread
{
object train, comp;
BookTicket(object train, object comp)
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(train)
{
System.out.println(BookTicket locked the train);
try{
sleep(200);
}catch(InterruptedException ie){ }
System.out.println(BookTicket wants to lock on compartmet);
synchronized(comp)
{
System.out.println(BookTicket now locked compartment);
}
}
}
Page 129 of 191

COREJAVA
}
class DeadLock
{
public static void main(String args[ ])
throws Exception
{
//take train and compartment as objects
object train = new object();
object compartment = new object();
//create objects to CancelTicket, BookTicket
CancelTicket obj1 = new CancelTicket(train, compartment);
BookTicket obj1 = new BookTicket (train, compartment);
//create 2 threads and attach them to these objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
Save it as DeadLock.java compile & run the program.
Output:CancelTicket locked the Compartment
BookTicket locked the Train
CancelTicket wants to lock on train
BookTicket wants to lock the Compartment
Press Ctrl+c for forcibly to terminate the program, because to solve this program in another way.
Ex: //To cancel the ticket Solution for dead lock
Class CancelTicket extends Thread
{
object train, comp;
CancelTicket(object train, object comp);
Locking
{
Solution for
this.train = train;
DeadLock Changing
this.comp = comp;
direction of thread 2
}
public void run()
{
Thread 2
synchronized(comp)
Thread 1 BookTicket
{
CancelTicket
System.out.println(CancelTicket locked the compartment);
try{
comp.obj
100ms
sleep(100);
}catch(InterruptedException ie){ }
System.out.println(CancelTicket wants to lock on
train);
train.obj
200ms
synchronized(train)
{
System.out.println(CancelTicket now locked train);
}
}
}
}
class BookTicket extends Thread
{
object train, comp;
BookTicket(object train, object comp);
{
this.train = train;
Page 130 of 191

COREJAVA
this.comp = comp;
}
public void run()
{
synchronized(comp)
{
System.out.println(BookTicket locked the Compartment);
try{
sleep(200);
}catch(InterruptedException ie){ }
System.out.println(BookTicket wants to lock on compartmet);
synchronized(train)
{
System.out.println(BookTicket now locked train);
}
}
}
}
class DeadLock
{
public static void main(String args[ ])
throws Exception
{
take train and compartment as objects
object train = new object();
object compartment = new object();
//create objects to CancelTicket, BookTicket
CancelTicket obj1 = new CancelTicket(train, compartment);
BookTicket obj1 = new BookTicket (train, compartment);
//create 2 threads and attach them to these objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
DeadLock of thread: - When a thread locked an object and waiting for another object which has been
already locked by another thread and the other thread is also waiting for the first object it leads to
DeadLock situation.
In DeadLock both the threads mutually keep under waiting forever and further processing is
canceled.
A programmer should avoid DeadLock situations in his program by properly planning designing
the program.
ThreadClassMethods:1. To know the currently running thread.
Thread t = Thread.currentThread();
2. To start thread
t.start();
3. To stop execution of a thread for a specified time
Thread.sleep(milliseconds);
4. To get the name of a thread
String name = t.getName();
5. To set a new to a thread
t.setName(name);
6. To get the priority of a thread
int priority_no = t.getPriority();
7. To set the priority of a thread
Page 131 of 191

COREJAVA
t.setPriority(int priority_no);
Note: - The priority number constants are as given below
Thread.MAX_PRIORITY value is 10
Thread.MIN_PRIORITY value is 0
Thread.NORM_PRIORITY value is 5
8. To test if a thread is still alive
t.isAlive(); returns true/false
9. To wait till a thread dies
t.join();
10. To send a notification to awaiting thread
obj.notify();
11. To send notification to all waiting threads
obj.notifyAll();
12. To wait till the obj is released (till notification is sent)
obj.wait();
notify() method will sends a notification to a thread, i.e. some object is available to the thread.
The above three methods (10, 11, 12) are belong to object class.
Q) Whatis the differencebetweenGreenthreadand Nativethread?*****
Ans:- A program thread uses two types of operating system threads, they are Green Thread model
and Native Thread model. Green Thread model will provide only one thread for a program thread, where
as Native Thread provides a separate thread for each program thread.
Ex: -

//Thread Communication
Class Communicate
{
public static void main(String args[ ])
{
//create Producer, Consumer, objects
Producer obj1 = new Producer();
Consumer obj2 = new Consumer(obj1);
//create 2 threads and attach them obj1, obj2
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
class Producer extends Thread
{
Boolean dataprodover = false; // dataprodove is a data production over
SrtingBuffer sb;
producer()
{
1
sb = new StringBuffer();
Data Provider
2
}
true
3
public void run()
{
for(int i = 1; i<=10; i++)
{
try
10
{
sb.append(i+:);
Consumer
sleep(100);
Producer

System.out.println(appending);
}
catch(Exception e){ }
Page 132 of 191

COREJAVA
}
dataprodover = true;
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run()
{
try{
while(!prod.dataprodover)
{
sleep(10);
}
}catch(Exception e){ }
System.out.println(prob.sb);
}
}
Save it as communication.java. This above program/method is not efficient way to
communication between threads.
If we want communicate efficient way we have to use notify() method.
Ex: //Thread communication in efficient way
Class Communicate
{
public static void main(String args[ ])
{
//create Producer, Consumer, objects
Producer obj1 = new Producer();
Consumer obj2 = new Consumer(obj1);
//create 2 threads and attach them obj1, obj2
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
class Producer extends Thread
{
1
SrtingBuffer sb;
Data Provider
producer()
2
true
{
3
sb = new StringBuffer();
}
public void run()
{
synchronized()
10
{
for(int i = 1; i<=10; i++)
Consumer
Producer
{
try
{
sb.append(i+:);
sleep(100);
Page 133 of 191

COREJAVA
System.out.println(appending);
}
catch(Exception e){ }
}
sn.notify();
}

// or we can use sb.notifyAll();

}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run()
{
synchronized(prod.sb)
{
try{
prod.wait();
}catch(Exception e){ }
System.out.println(prod.sb);
}
}
}
Q) Whatis the differencebetweensleep()methodand wait() method?*****
Ans:- Both methods will make the thread wait for some time. When the thread comes out of sleep()
method the object may be still lock. When the threads comes out of the wait() method the object is
automatically unlocked.
But both methods will wait temporarily.
Ex: synchronized(obj)
synchronized(obj)
{
{
------------------------------------------locked
locked
------------------------------------------sleep(2000);
wait(2000);
------------------------------------------Unlocked
locked
------------------------------------------}
}
Whatare differenttypesof threads:1. User thread or Main thread.
2. Daemon thread
3. GUI thread
Q) Whatis Daemonthread?*****
Ans:- A Daemon thread is a thread that continuously provides services to other threads i.e. Daemon
thread are used for background services.
Ex: -

To start mysql
F:\rnr>mysqld Here d is the Daemon thread.
F:\rnr>
Now onwards Daemon thread makes the mysql database running continuously.
Daemon threads are generally used background services.
Page 134 of 191

COREJAVA
Q) Whatis threadlife cycle?*****
Ans:- Life cycle of thread means from the creation of thread till its termination. The states assumed by
the thread are called life cycle of a thread.
Start run wait (or) blocked state Destroy State

Life Cycleof Thread

Running
Yield
New Thread

Start

Not Runnable
Runnable
sleep()

The run method terminates

wait()
Dead/Terminates

Dead

blocked on I/O

(or)

Runnable means it will executes public void run methods yield makes pausing the thread.
Not Runnable means thread will stop runnable.
Afetr executing the all methods by run() method then the thread will be terminated.
Runnable: - Waiting for its turn to be picked for execution by the thread schedular based on thread
priorities.
Running: - The processor is actively executing the thread code. It runs until it becomes blocked, or
voluntarily gives up its turn with this static method Thread.yield(). Because of context switching
overhead, yield() should not be used very frequently.
Waiting: - A thread is in a blockedstate while it waits for some external processing such as file I/O to finish.
Sleeping: - Java threads are forcibly put to sleep (suspended) with this overloaded method:
Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blockedon I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
Blockedon synchronization: Will move to Runnable when a lock is acquired.
Page 135 of 191

COREJAVA
Dead: The thread is finished working.
Whatis the differencebetweenyieldand sleeping?*****
Ans:When a task invokes yield(), it changes from running state to runnable state. When a task
invokes sleep(), it changes from running state to waiting/sleeping state.

Whatare the statesof thread?*****


Ans:- New thread state Runnable Running wait (or) blocked state Destroy State
ThreadGroup:- A group of threads as single unit is called ThreadGroup.
If we applied certain methods on the ThreadGroup it will effect all other threads. Controlling all
the threadsx by giving a single command or method is possible, because of ThreadGroup.
ThreadGroup tg = new ThreadGroup(group name);
Thread t1 = new Thread(tg, obj, threadname);
Here obj is target object
Thread t2 = new Thread(tg, obj1, threadname);
We can also add one ThreadGroup to another ThreadGroup.
ThreadGroup tg1 = new ThreadGroup(tg, group name);
Daemon Thread: - Daemon threads are service providers fro other threads or objects. A daemon thread
executes continuously. It provides generally a background processing.
1. To make a thread as Daemon thread
t.setDaemon(true);
2. To know if a thread is Daemon or not
t1
Boolean x = t.isDaemon();
res
Ex: /*Using thread groups*/
t2
class WhyTGroups
{
public static void main(String args[ ])
t3
can
throws Exception
{
t4
Reservation res = new Reservation();
tg1
Cancellation can = new Cancellation();
//create a ThreadGroup with name
tg
ThreadGroup
tg
=
new
ThreadGroup(Reservation Group);
//create 2 threads and add them to ThreadGroup
Thread t1 = new Thread(tg, res, First thread);
Thread t2 = new Thread(tg, res, Second thread);
//create another ThreadGroup as a child to tg
ThreadGroup tg1 = new ThreadGroup(tg, Cancellation Group);
Thread t3 = new Thread(tg1, res, Third thread);
Thread t4 = new Thread(tg1, res, Fourth thread);
System.out.println(Number of threads in a group = +tg.activeCount());
//Find parent group of tg1
System.out.println(Parent of tg1 = +tg1.getParent());
//set maximum priority to tg1 as 7
tg1.setMaxPriority (7);
//know the ThreadGroup of t1 and t2
System.out.println(ThreadGroup of t1 = +t1.getThreadGroup());
System.out.println(ThreadGroup of t2 = +t2.getThreadGroup());
//start the threads
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Reservation extends Thread
Page 136 of 191

COREJAVA
{
public void run()
{
System.out.println(I am Reservation thread);
}
}
class Cancellation extends Thread
{
public void run()
{
System.out.println(I am Cancellation thread);
}}
Event Handling

Introduction
Graphical User Interface systems handle user interaction using an event driven model. That is, the user
performs an action such as moving the mouse, pressing a key or releasing one, etc. These all generate
events of some kind. A GUI system such as the Java AWT, Microsoft Windows, Motif, or any other
windowing system will sit in an event loop waiting for these events to occur. When one does, application
code is called in some way to respond to the event.
The way in which application code is called varies between the different windowing systems. In some,
the application programmer has to write an event loop handler themselves, and when an event occurs
the application has to figure out what to do with it. In other systems some assistance may be given with
this, where events are dispatched to graphical objects automatically. When they arrive, application code
still has to work out what type of event has occurred. In yet other systems, the application merely needs
to register an event handler with an object, and the handler will be called whenever the right event occurs
in the right object, without any further need for intervention by the application programmer.
Java in release 1.1 is now up to its third event processing model! The first one - called the ``old'' event
model was abandoned before Java left beta stage. It was replaced by the ``new'' event model for Java
1.0. Unfortunately, two things marred this transition to the new model:

Books had already begun to appear using the old event model, and hardly anyone mentioned
the new model.
The new model didn't work until JDK 1.0.2, so everyone continued to use the old model anyway.

The difference between the old and new models is subtle and depends on a complex interplay of events
that belong to the underlying native implementation and the Java events. This was covered in the Java
1.0 version of this book.
Both the old and new models had serious Software Engineering deficiences that led to poor quality code
as soon as applications started to grow in scale. A solution to this was already known as the Command
Pattern, and this was adopted for the third event model for the Java AWT. The Command Pattern was
renamed ``delegation'' by Sun engineers, and forms a much cleaner way of handling events. Basically, it
allows the application to register handlers (called listeners) with graphical objects, which are called when
suitable events arrive.
There are complex implementation layers and issues arising from the third event model. When the user
performs an action such as a keypress, a native code event is generated. This is firstly handled by native
code at, say, the Windows or X level. The event may be caught by the native toolkit or ignored. If caught,
two things may happen:

Page 137 of 191

COREJAVA

The event may be given to the native GUI object and then to the Java object.
The event may be given to the Java object and then to the native GUI object.

Which one of these occurs depends on the event type.


When an event is handed to the Java layer, it is changed into a Java event. Java code looks to see if
there is an event listener using the third event model. If there is, this is used. If there is not, then the
second ``new'' event model is used. Sometimes there is no listener but the third model should be used
anyway. This can be forced.
If all this sounds grim, then be reassured: if you only want to do simple things, the delegation event
model lets you do them simply. Most of the time you only want to simple things.

Listeners
A listener is registered with an event type for an object. For example, an application can register a key
event listener for any Component, or an action event listener for objects such as Button or TextField.
Listeners are where the programmer places application specific code to respond to user events. When a
suitable event occurs, an appropriate method on the listener is invoked.
For example, suppose we are building a Web browser. We may have a Back button to return to the
previously displayed page. When we click on this Back button, the application will need to reload the last
page into the browser window and reset history lists, current URL pointers, etc. This is not GUI code,
though it is clearly application code that affects GUI objects as well as other application objects of the
browser. The Back function can also be invoked in other ways, such as by a hot-key or by menu
selection. Not only is the behavior application specific, but there is more than one way way of invoking
this behavior. A listener object encapsulates this behavior, and should be registered with the Back
button, the hot-key combination and the menu selection.
When a listener is invoked, it has to be by one of its methods. There could be a standard method such
as execute() or by one customised to the event that caused it. The JDK 1.1 has chosen the second
method. So if the mouse is clicked in a Button, then an action event is generated (invisibly to most
applications), and theactionPerformed() method is called on any action listener. On the other hand,
whenever a key is pressed in a Component, then the method keyPressed() is called in any key event
listener.
This could have been more simply if simplicity was the only driving force behind this event model:
however, Java Beans imposes extra requirements which lead to these multiple event types.
The methods defined for listeners are done using interfaces. This is an absolutely appropriate use of the
interface mechanism. Since listeners contain application code, they will probably have an inheritance
based on the application, not on some vagaries of the GUI side. All the listener needs to do is to
implement certain methods, so that the internal event handling code can call the right method. So, for
example, the ActionListener is defined by
public interface ActionListener extends EventListener {
public abstract void actionPerformed(ActionEvent e)
}
whereas KeyListener is defined by
public interface KeyListener extends EventListener {
public abstract void keyPressed(KeyEvent e);
public abstract void keyReleased(KeyEvent e);
public abstract void keyTyped(KeyEvent e);
Page 138 of 191

COREJAVA
}
Implementing Listeners
Since a listener is defined as an interface, any application code inheriting a listener specification must
implement its methods. The rest of the listener code is upto the application. Listener methods will usually
interact with other objects of the application. Some of these will be GUI objects, some won't. It doesn't
really matter. Returning to our browser example, the Back button listener will need to access the URL
object to retrieve the previous URL, and the browser display object to show it. One is graphical, the other
is not.
Listener objects - just like any object - get knowledge about other objects in three ways

They create the other objects and store them in local variables.
The other objects are passed in by the constructor.
The other objects are set by special methods

Here is a trivial application just to show how listeners are created and used. The application has a Button
on the left, a Button on the right and a Label in the middle. The left Button has the label ``Left'', and the
right one has the label ``Right'' When either Button is pressed, the text showing in the Label is set to
either ``Left'' or ``Right'' i.e. the label of the Button pressed.
import java.awt.Button;
import java.awt.Label;
import java.awt.event.ActionListener;
/**
* This application consists of two Buttons with a Label
* between them. When a Button is pressed, its text is
* set in the Label
*
* @author Jan Newmarch
*/
public class DelegateDemo extends Frame {
public static void main(String argv[]) {
new SimpleEvent().show();
}
public DelegateDemo() {
// create the GUI objects
Button left = new Button("Left");
Button right = new Button("Right");
Label label = new Label("Center");
// set their geometry
add(left, "West");
add(right, "East");
add(label, "Center");
pack();
// create a listener and add it to each Button
SimpleListener simple = new SetText(label);
left.addActionListener(simple);
right.addActionListener(simple);
}
}
Page 139 of 191

COREJAVA
/**
* A listener object that is invokded when a Button is activated
* It finds the Button's label and sets it in a Label
*/
class SetText implements ActionListener {
private Label label;
public SetText(Label l) {
// the listener needs to know the Label it will act on
label = l;
}
public void actionPerformed(java.awt.event.ActionEvent e) {
// get the label showing in whichever Button was pressed
String name = e.getActionCommand();
// set this in the Label object
label.setText(name);
}
}

AWTEvent
Events that are handled by delegation objects are all subclassed from AWTEvent. If you are familiar with
the old or new event models, then you will have used theEvent class in your event handling code. Forget
about that class now. It is superceded by AWTEvent. Forget also about all the fields and values that are
present inEvent - they are all absent from AWTEvent. The class AWTEvent has only one field, id, and
that is protected anyway. The AWTEvent is very simple, and you don't even need to look at it unless you
are doing arcane things (which we will do later).
For each type of event that is present in the delegation model, there is a separate class. The classes are
divided into two types: low-level input or window events that every GUI object receives, and higher-level
semantic events that only have meaning for particular GUI objects. In addition there are low-level window
events that are only received by Frame and Dialog. This kind of division of types is not captured
anywhere in the language, rather it is a guide to the programmer.
The low-level events for any Component are
Table 1: Low-level Event Types
Class
id
ComponentEvent COMPONENT_MOVED
COMPONENT_RESIZED
COMPONENT_SHOWN
COMPONENT_HIDDEN
FocusEvent
FOCUS_GAINED
FOCUS_LOST
KeyEvent
KEY_PRESSED
KEY_RELEASED
Page 140 of 191

COREJAVA
MouseEvent

KEY_TYPED
MOUSE_CLICKED
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED

Where are PaintEvent.PAINT etc?


The low-level window events for Frame and Dialog are
Table 2: Low-level Window Event Types
Class
id
WindowEvent WINDOW_CLOSED
WINDOW_CLOSING
WINDOW_DEICONIFIED
WINDOW_ICONIFIED
WINDOW_OPENED
The semantic level events are
Table 3: Semantic Event Types
Class
Id
ActionEvent
ACTION_PERFORMED
AdjustmentEvent ADJUST_VALUE_CHANGED
ItemEvent
ITEM_STATE_CHANGED
For the low-level events, the protected id takes on different values to distinguish between the type of
event. This value can be found from the event methodgetId(). For the semantic level events, there is only
one value for id, so that although getId() will give a value, it isn't really very useful (unless you have
subclassed one of these semantic events and have your own extra id values). These values are used by
the AWT to call appropriate methods on listeners, and you do not usually need to look at these values.
The semantic events are generated by the following
Table 3: Semantic Event Generation
Event
Object
Action
ActionEvent
Button
Click on Button
List
Double-click on an item
MenuItem
Click on MenuItem
TextField
Press <Enter> key
AdjustmentEvent Scrollbar
Any Scrollbar action
ItemEvent
Choice
Select an item
List
Select or deselect an item
Checkbox
???
CheckboxMenuItem ???
Listeners for Different Events
For each event type that can occur, the application can add event listeners, that have methods invoked
when the event occurs. The listeners are defined asinterfaces, so that an actual listener has to
Page 141 of 191

COREJAVA
implement these methods. The names of the listener classes are simply derived from the names of the
events they handle, except that MouseEvent's have two different types of listener for efficiency reasons.
Table 4: Listeners for Each Event
Event
Listener
Method
ActionEvent
ActionListener
actionPerformed()
AdjustmentEvent AdjustmentListener adjustmentValueChanged()
ComponentEvent ComponentListener componentResized()
componentMoved()
componentShown()
componentHidden()
FocusEvent
FocusListener
focusGained()
focusLost()
ItemEvent
ItemListener
itemStateChanged()
KeyEvent
KeyListener
keyTyped()
keyPressed()
keyReleased()
MouseEvent
MouseListener
mouseClicked()
mouseEntered()
mouseExited()
mousePressed()
mouseReleased()
MouseMotionListener mouseDragged()
mouseMoved()
WindowEvent
WindowListener
windowClosed()
windowClosing()
windowDeiconified()
windowIconified()
windowOpened()
The elements of this table should be interpreted as follows:

An ActionListener has been registered with, say, a Button. When the Button is clicked, the
method actionPerformed() of the ActionListener will be called with a single parameter:
the ActionEvent that was generated.
A KeyListener may be registered for key events with, say, a TextField. When a key is pressed,
the method keyPressed() of the KeyListener will be called with the KeyEvent as parameter.
When the key is released, the method keyReleased() will be called with a different KeyEvent as
parameter, and also, because a key has been pressed and released (i.e. it has been typed), the
method keyTyped() is called with a third KeyEvent as parameter.
Two types of listener may be registered for mouse events: this represents a tradeoff between
consistency and efficiency. Consistency would have one mouse listener only. This would cause
event tracking for all of the different mouse events. However, tracking mouse motion is costly:
many events are generated as the user moves the mouse around. In network systems such as X
Windows, this can often swamp the available bandwidth leading to visible delays in mouse
tracking. Since many GUI objects might be interested in mouse clicks but not mouse motion,
using two separate listeners improves efficiency.

RegisteringListeners
A listener implements one of the interfaces ActionListener, AdjustmentListener, etc. Once created,
listeners are registered with GUI objects. Of course, the GUI object has to be capable of generating the
right type of event for the listener. Listeners are added to each object by a
suitable add<event>Listener() call. In the simple example we had earlier, this was done for
an ActionEvent listener on a Button by
Page 142 of 191

COREJAVA
SimpleListener simple = new SimpleListener(label);
left.addActionListener(simple);
The following table lists which objects can have which listener types added:
Table 5: Objects and Listeners for Them
GUI Object
Listener
Button
ActionListener
Choice
ItemListener
Checkbox
ItemListener
Component ComponentListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
Dialog
WindowListener
Frame
WindowListener
List
ActionListener
ItemListener
MenuItem
ActionListener
Scrollbar
AdjustmentListener
TextField
ActionListener
Note that every GUI object inherits from Component. So every object can
have Component, Focus, Key, Mouse and MouseMotion listeners added.
The next sections look at each event type in turn.

ActionEvents
Action events are generated for the following objects:
Table 6: Objects generating Action Events
GUI Object
Action
Button
Click on Button
List
Double-click on an item
MenuItem
Click on MenuItem
TextField
Press <Enter> key
An ActionListener can be registered with each of these objects, and its method actionPerformed() is
called when the user performs the indicated activity.
An ActionEvent has two methods that the programmer may find to be of use:
public String getActionCommand()
public int getModifiers()
Each ActionEvent carries around an ``action command''. This command may be set by
the Button or MenuItem by their setActionCommand(String) method. There is no such method
for List or TextField. The value of the action command (unless reset) is
Table 7: Value of Action Command
GUI Object
action command
Button
label
List
???
MenuItem
label
TextField
???

Page 143 of 191

COREJAVA
The action command gives runtime information about the context in which the event occurred. This is
semantic-level information, rather than low-level information: the text showing in the Button is usually
enough useful information. If low-level information is required, the source object can be obtained from the
methodgetSource() (or equivalent methods). This method is inherited by every event from the superior
class java.util.EventObject.
We shall illustrate use of action events by four programs which do basically the same thing, but use
different GUI elements to do this. The common part of these will be a Label which can have its
foreground color set to different values. The color can be selected in different ways for each program, but
they will all invoke the sameActionListener. This ActionListener is defined by the following:
import java.awt.Component;
import java.awt.Color;
import java.awt.event.ActionListener;
/**
* An ActionListener that changes the foreground
* color of a component passed in by the constructor
*
* @author Jan Newmarch
*/
public class SetColor implements ActionListener {
final Color colors[] = {Color.red, Color.blue, Color.green};
final String colorLabels[] = {"red", "blue", "green"};
private Component comp;
public SetColor(Component c) {
comp = c;
}
/**
* Invoked by an action event somewhere
* resets the foreground of a component passed
* in to the constructor
*/
public void actionPerformed(ActionEvent e) {
String colorName = e.getActionCommand();
// search for Color matching color name
for (n = 0; n < colorLabels.length; n++) {
if (colorLabels[n].equals(colorName)) {
// found a match, set foreground
comp.setForeground(colors[n]);
return;
}
}
System.out.println("Unknown color: " + colorName);
}
}
The first program to use this has a row of three buttons along the top and a label to below them. A
single SetColor listener will be created and registered with each button. The application looks like

The code is
Page 144 of 191

COREJAVA
import java.awt.*;
import SetColor;
public class ButtonColor extends Frame {
public static void main(String argv[]) {
new ButtonColor().show();
}
public ButtonColor() {
// the label that will be colored
Label label = new Label("Click on button to change color");
// a panel to hold the buttons
Panel panel = new Panel();
// buttons for each color
Button red = new Button("red");
Button blue = new Button("blue");
Button green = new Button("green");
// set geometry
panel.setLayout(new FlowLayout());
panel.add(red);
panel.add(blue);
panel.add(green);
add(panel, "North");
add(label, "Center");
pack();
// add the listener
SetColor sc = new SetColor(label);
red.addActionListener(sc);
blue.addActionListener(sc);
green.addActionListener(sc);
}
}
The second program to use the SetColor listener will just change elements of the user interface. That is,
instead of a set of buttons, it will use a list to the left of the label. In this version we shall only implement
the double-click action, leaving single-click till later (that uses a different type of event). The application
looks like

The code is
import java.awt.*;
import SetColor;
public class ListColor extends Frame {
public static void main(String argv[]) {
new ListColor().show();
}
public ListColor() {
// the label that will be colored
Page 145 of 191

COREJAVA
Label label = new Label("Double-click to change color");
// the list of colors
List colors = new List(3);
colors.add("red");
colors.add("blue");
colors.add("green");
// set geometry
add(colors, "West");
add(label, "Center");
pack();
// add the listener
SetColor sc = new SetColor(label);
colors.addActionListener(sc);
}
}
Note that we have not changed the application code at all, only the GUI code. In this we are partly lucky
since we are handling the same event type in both programs, but even handling different types does not
cause many changes.
The third program will make the same kind of change. This time we shall use a menu of colors to make
the selection. Each item in the menu will have the same listener added, just as for the buttons in the first
program. The application looks like

The code is
import java.awt.*;
import SetColor;
public class MenuColor extends Frame {
public static void main(String argv[]) {
new MenuColor().show();
}
public MenuColor() {
// the label that will be colored
Label label = new Label("Select color from menu");
// the menu bar
MenuBar mb = new MenuBar();
Menu color = new Menu("Color");
mb.add(color);
// menu color items
MenuItem red = new MenuItem("red");
MenuItem blue = new MenuItem("blue");
MenuItem green = new MenuItem("green");
color.add(red);
color.add(blue);
color.add(green);
Page 146 of 191

COREJAVA
// set the geometry
setMenuBar(mb);
add(label, "Center");
pack();
// add the listener
SetColor sc = new SetColor(label);
red.addActionListener(sc);
blue.addActionListener(sc);
green.addActionListener(sc);
}
}
Again there is no change to the application code.
The last example gives the last variation on this theme, using a TextField for color selection. The
application looks like

The code is
import java.awt.*;
import SetColor;
public class TextFieldColor extends Frame {
public static void main(String argv[]) {
new TextFieldColor().show();
}
public TextFieldColor() {
// the label that will be colored
Label label = new Label("Enter color in the TextField");
// the text field to enter the color
TextField text = new TextField(20);
// set geometry
add(text, "North");
add(label, "Center");
pack();
// add the listener
SetColor sc = new SetColor(label);
text.addActionListener(sc);
}
}
This last piece of code is rather lacking in ease of use, as it gives no clues as to what are allowable text
values!

AdjustmentEvents

Page 147 of 191

COREJAVA
Adjustment events are only generated for objects of class Scrollbar in Java 1.1. There is not so much
need to use this class in Java 1.1, as there is also aScrollPane class which looks after most details of
handling a viewport onto a component.
A listener of class AdjustmentListener is added to a Scrollbar by the method
public void addAdjustmentListener(AdjustmentListener)
The user can interact with the scrollbar by clicking the mouse within it, by dragging the slider or by
keyboard interaction such as the arrow keys or PageUp/PageDown keys. These all cause the method
public void adjustmentValueChanged(AdjustmentEvent)
to be called in the listener.
There is only the one method called despite the variety of ways that the user can interact with the
scrollbar. If the application needs to distinguish between these, it can call the
method getAdjustmentType() on the AdjustmentEvent. This will return one of the four values

UNIT_INCREMENT - down one ``line''


UNIT_DECREMENT - up one ``line''
BLOCK_INCREMENT - down one ``page''
BLOCK_DECREMENT - up one ``page''

The actual value of the scrollbar can be found from the method getValue() of the AdjustmentEvent. To
use this value, you need to know where on the scale from minimum to maximum it occurs. These - and
much other information - are available from the event of class Adjustable in which the event occurred
(right now we know this is a Scrollbar but it could be other things in the future - for example,
a Scale object).
Component Events
Most applications will not need to use events of type ComponentEvent. This is used for tracking
movement, resizing and visibility. An application will generally function perfectly well by ignoring these
events: the AWT toolkit will look after things such as calling layout managers on resize.
There are occasions when an application may want to track such events. For example, a visually
intensive piece of graphics such as animation should cease when the display object becomes invisible,
so it will want to track visibility changes. A ``smart'' text display may want to change the size of the font
used according to the amount of space it has, so it will want to track size changes.
An application wanting to track such changes registers a listener that implements ComponentListener.
This interface defines four methods that the listener must implement:
public void componentHidden(ComponentEvent);
public void componentMoved(ComponentEvent);
public void componentResized(ComponentEvent);
public void componentShown(ComponentEvent);
In objects of class ComponentEvent the id is used field to distinguish between four
types: COMPONENT_HIDDEN, COMPONENT_MOVED, COMPONENT_RESIZED andCOMPONENT_
SHOWN. The AWT uses this value to select which of the four listener methods to call, so you are unlikely
to need to look at this field.
The ComponentEvent class supplies a method
public Component getComponent()
if you need to determine which component has called the listener.
Here is a program to track resize and movement events on the toplevel Frame:
Page 148 of 191

COREJAVA
import java.awt.*;
import java.awt.event.ComponentEvent;
public class TrackResize extends Frame {
public static void main(String argv[]) {
new TrackResize().show();
}
public TrackResize() {
Label label = new Label();
add(label);
pack();
addComponentListener(new Tracker(label));
}
}
class Tracker implements ComponentListener {
private Label label;
Tracker(Label l) {
label = l;
}
public void componentHidden(ComponentEvent e) {
// empty
}
public void componentMoved(ComponentEvent e) {
showGeometry(e);
}
public void componentResized(ComponentEvent e) {
showGeometry(e);
}
public void componentShown(ComponentEvent e) {
// empty
}
private void showGeometry(ComponentEvent e) {
Component c = e.getComponent();
Dimension d = c.getSize();
Point p = c.getLocation();
label.setText("Position: (" + p.x +
"," + p.y + ") Size: (" +
d.width + "," + d.height + ")");
}
}
The Tracker class inherits only from Object. Because it has to implement all of
the ComponentListener interface it ends up with empty implementations of
thecomponentHidden() and componentShown() methods. This may become mildly annoying if it had to
be done frequently, so there is a ``convenience'' classComponentAdaptor which defines all these
methods as empty ones. Using this, you can inherit from ComponentAdaptor and then just override the

Page 149 of 191

COREJAVA
methods you need. The single inheritance model of Java does of course then require that the listener
cannot also inherit from other classes, so this may be of limited value.

FocusEvents
Applications are unlikely to need to track focus events, as the AWT toolkit looks after most aspects of
focus changes. If you need to, you can add a focus change listener by AddFocusListener(). The listener
must then implement the methods
public void focusGained(FocusEvent);
public void focusLost(FocusEvent);
There are no extra methods for handling these events.
Item Events
Item events are generated for the following objects:
Table 8: Objects generating Item Events
GUI Object
Action
Choice
Click on item
Checkbox
Select an item
Deselect an item
List
Select an item
Deselect an item
Extend a selection
Reduce a selection
An application wanting to follow selection changes registers an object that implements ItemListener.
When such a change occurs, it will have the methoditemStateChanged() called with an ItemEvent as
parameter.
Item event handling appears to be incomplete in Java 1.1 beta. The ItemEvent declares methods
ItemSelectable getItemSelectable();
Object getItem();
The interface ItemSelectable declares methods
interface ItemSelectable {
int[] getSelectedIndexes();
String[] getSelectitems();
Presently, the classes that implement the ItemSelectable interface are List, Choice and Checkbox.
Now consider the information we would be after when an item in a list is selected: the index and the
string showing. The index is given by the getItem() of theItemEvent, but it has to be coerced to
class Integer first. The actual string is not obtainable from the information given. The
method getItemSelectable()returns the item that the selection was performed on - the list. From there you
can find the set of all selected items (which may be more than one), but not the single list item that
changed state. To get at that, you have to check and then coerce the ItemSelectable to class List and
then use the List method getItem() to find the string selected.
// import java.awt.Label;
import java.awt.Color;
import java.awt.Component;
// import java.awt.Frame;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
/**
* An ItemListener that changes the foreground
Page 150 of 191

COREJAVA
* color of a component passed in by the constructor
*
* @author Jan Newmarch
*/
public class SetColor2 implements ItemListener {
final Color colors[] = {Color.red, Color.blue, Color.green};
final String colorLabels[] = {"red", "blue", "green"};
private Component comp;
public SetColor2(Component c) {
comp = c;
}
/**
* Invoked by an item event somewhere
* resets the foreground of a component passed
* in to the constructor
*/
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange == ItemEvent.SELECTED) {
System.out.println(e.getItem());
//String colorName = e.getActionCommand();
// search for Color matching color name
//for (n = 0; n < colorLabels.length; n++) {
//if (colorLabels[n].equals(colorName)) {
// comp.setForeground(colors[n]);
//return;
//}
//}
//System.out.println("Unknown color: " + colorName);
}
}
}
import java.awt.*;
public class ListColor2 extends Frame {
public static void main(String argv[]) {
new ListColor2().show();
}
public ListColor2() {
// the label that will be colored
Label label = new Label("Hello World");
// the list of colors
List colors = new List(3);
colors.add("red");
colors.add("blue");
colors.add("green");
// set geometry
add(colors, "West");
add(label, "Center");
pack();
// add the listener
SetColor2 sc = new SetColor2(label);
Page 151 of 191

COREJAVA
colors.addItemListener(sc);
}
}

KeyEvents
Key events may be generated for all components. They count as ``low level'' events for most objects, but
of course for TextArea and TextField they really have semantic content. For other classes keyboard
events are most likely to be use in implementing keyboard traversal mechanisms, such as the use of
arrow keys to move around a grid of labels, or of the tab key to move between objects.
Key events also have an important property not shared with most other event types, and that is they can
be changed by the application. For example, the application may change any text typed to lower case by
mapping any upper case characters entered into lower case.
A KeyEvent defines a large number of constants for the special keys on the keyboard. These are known
as action keys and are given in this table:

HOME
UP
F1 - F12
NUM_LOCK
BACK_SPACE

Table 9: Action Keys


END
PGUP
DOWN
LEFT
PRINT_SCREEN SCROLL_LOCK
PAUSE
INSERT
TAB
ESCAPE

PGDN
RIGHT
CAPS_LOCK
ENTER
DELETE

These can be tested by code such as


KeyEvent e;
...
if (e.isActionKey()) {
switch (e.getKeyCode()) {
case KeyEvent.HOME: ...
case KeyEvent.END: ...
case KeyEvent.PGUP: ...
...
}
}
There are related methods inherited from InputEvent, the super class of KeyEvent. These allow tests for
the modifier keys:
public boolean isShiftDown();
public boolean isControlDown();
public boolean isMetaDown();
The information from these can also be obtained from the method getModifiers(), and then comparing
this to InputEvent.CTRL_MASK, etc.
import java.awt.*;
import java.awt.event.KeyListener;
public class ShowKey extends Frame {
public static void main(String argv[]) {
new ShowKey().show();
}
public ShowKey() {
Page 152 of 191

COREJAVA
Label l = new Label("Hello");
add(l);
pack();
KeyInfo ki = new KeyInfo();
l.addKeyListener(ki);
}
}
class KeyInfo implements KeyListener {
public void keyPressed(KeyEvent e) {
System.out.print("Down: ");
printInfo(e);
}
public void keyReleased(KeyEvent e) {
System.out.print("Up: ");
printInfo(e);
}
public void keyTyped(KeyEvent e) {
System.out.print("Typed: ");
printInfo(e);
}
private void printInfo(KeyEvent e) {
System.out.println(e.toString());
System.out.println("char: " + e.getKeyChar() +
"keycode: " + e.getKeyCode());
}
}

JAVAAPPLETS
What Is an Applet?
Java applets are special kind of Java programs that run when embedded in a Java enabled Web
browser or a specialized tool such as appletviewer. The Web browser supplies the framework for
retrieving and loading an applet and also supplies the main window holding the applet. A Java
application does not require any additional software, such as a Web browser, other than the typical Java
runtime files included in the Java Developer's Kit. Java applications are designed to be run in standalone mode on a client machine and therefore can be thought of as a known entity. Java applets,
meanwhile, can be loaded from anywhere on the Internet, and therefore are subject to severe security
restrictions.
Java applets currently are being used for advertising purposes because they provide the capability to
include simple animation and sound in a Web advertisement. Many client/server developers currently are
looking at the company intranet as an excellent platform on which to finally deliver true cross-platform
corporate applications. Because of this, Java applets are certain to quickly progress from "neat" status to
true business use status.
What Is Required to Run an Applet?
Java applets are typically run within a Web browser. The popular Web browsers on the market support
embedded Java applets in HTML pages. These browsers include:
Page 153 of 191

COREJAVA
Sun HotJava 1.0
Netscape Navigator 2.0 (or greater)
Microsoft Internet Explorer 3.0
Oracle PowerBrowser 1.5
The Applet Viewer tool included with the Java Developer's Kit can be used to test and run Java applets
as well.
What Can an Applet Do?
An applet can:
Draw pictures on a web page
Create a new window and draw in it.
Play sounds.
Receive input from the user through the keyboard or the mouse.
Make a network connection to the server from which it came and can send to and receive
arbitrary data from that server.
An applet cannot:
Write data on any of the host's disks.
Read any data from the host's disks without the user's permission. In some environments,
notably Netscape, an applet cannot read data from the user's disks even with permission.
Delete files
Read from or write to arbitrary blocks of memory, even on a non-memory-protected operating
system like the MacOS. All memory access is strictly controlled.
Make a network connection to a host on the Internet other than the one from which it was
downloaded.
Call the native API directly (though Java API calls may eventually lead back to native API calls).
Introduce a virus or trojan horse into the host system.
An applet is not supposed to be able to crash the host system. However in practice Java isn't
quite stable enough to make this claim yet.
Building a Java Applet
The java.applet package contains standard framework for developing applets. To run an applet an HTML
file with appropriate information about the applets class file must be provided. The main() method which
is necessary for executing standalone applications is not necessary for running applets. There are
restriction on what an applet is allowed to do.
An applet is implemented by creating a subclass of the Applet class and overriding the appropriate
methods to customize the running of the applet. GUI components and containers can be embedded in
an applet to build a GUI for the applet.
APPLET LIFE CYCLE
Each applet has four major events in its lifetime:
Initialization
Starting
Stopping
Destroying
These four events correspond directly to four methods within the Applet class: init(), start(),
stop(), and destroy(). The following discussion provides some information on each of these
methods.
public void init()
The init() method is called when the applet is initially loaded. This method is used to
do one-time setup features such as add components to the layout manager, set screen
colors, and connect to a host database.
public void start()
The start() method is called after the applet has been initialized, and also each time
the applet is restarted after being stopped. Applets can be stopped when the user
changes to another Web page. If the user returns at a later time to the page with the
Page 154 of 191

COREJAVA
applet on it, the applet will be restarted by the browser. Therefore, the start() method
can be called many times during an applet's life cycle. Common operations that occur
during an applet's start() method are the initialization of threads within the applet and
the updating of the screen display.
public void stop()
The stop() method is called whenever the user leaves the current page. The stop()
method is used to temporarily suspend the execution of the applet until the start()
method is called again.
public void destroy()
The destroy() method is called whenever it is time to completely finish the applet's
execution. This method is generally called when the browser is exiting or the applet is
being reloaded from the host server. The destroy() method is used to free up allocated
resources such as threads or database connections.
The program below shows a simple applet that implements all four life cycle methods: init(),
start(), stop(), and destroy(). This applet updates the screen as well as the browser status bar
with some information indicating which method is being called.
An applet illustrating the life cycle methods.
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class LifeCycleApplet extends java.applet.Applet
{
Font theFont = new Font("Helvetica", Font.BOLD, 20);
int i;
String String1, String2;
public void paint(Graphics g)
{
g.setFont(theFont);
g.setColor(Color.blue);
g.drawString(String1 + String2, 5, 30);
}
public void init()
{
i = 0;
String1 = "";
String2 = "The applet is initializing!";
repaint();
showStatus("The applet is initializing!");
}
public void start()
{
i = 1;
String1 = String2;
String2 = "The applet is starting!";
repaint();
showStatus("The applet is starting!");
}
public void stop()
{
i = 2;
String1 = String2;
String2 = "The applet is stopping!";
repaint();
showStatus("The applet is stopping!");
}
public void destroy()
Page 155 of 191

COREJAVA
{

i = 3;
String1 = String2;
String2 = "The applet is being destroyed!";
repaint();
showStatus("The applet is being destroyed!");

}
}
HTML and Java Applets
Inorder to run an applet and HTML file with appropriate information about the applets class file must
be provided. The <APPLET> tag-Used to represent a Java applet to be loaded.
The <APPLET> Tag
The syntax for using the <APPLET> tag is the following:
<APPLET attributes>
applet_parameters
alternate_content
</APPLET>
The APPLET attributes are standard values that all applets accept and are a standard
part of HTML. The applet_parameters are applet-specific parameters that are read
by the applet at runtime. This is a handy way of passing arguments to an applet to allow
the applet to be more generic.
<APPLET> Tag Attributes
ALT-Alternate text that can be displayed by text-only browsers.
ALIGN-The ALIGN attribute designates the alignment of the applet within the browser
page.
CODE-(Required) The CODE attribute is used to indicate the .class file that loads the
applet.
CODEBASE-The CODEBASE attribute is used to indicate the location of the .class file
that loads the applet.
HEIGHT-(Required) The HEIGHT attribute is used to set the applet's bounding rectangle
height.
HSPACE-The HSPACE attribute sets the amount of horizontal space to set off around the
applet.
NAME-The NAME attribute sets the symbolic name of the applet.
VSPACE-The VSPACE attribute sets the amount of vertical space to set off around the
applet.
WIDTH-(Required) The WIDTH attribute is used to set the applet's box width.
The LifeCycle.html file contents.
<HTML>
<HEAD>
<TITLE>This is the LifeCycle applet!</TITLE>
</HEAD>
<BODY>
<H1>Life Cycle of Applet </H1>
<BR>
<APPLET CODE="LifeCycleApplet.class" WIDTH=600 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
public void paint()
The paint() method is called by the system when the applet needs to be drawn. The definition
of this method must have the form:
public void paint(Graphics g) {
// draw some stuff
}

Page 156 of 191

COREJAVA
The parameter g, of type Graphics, is provided by the system when it calls the paint() method. In Java,
all drawing of any kind is done using methods provided by a Graphics object. The paint() method of an
applet does not, by the way, draw GUI components such as buttons and text input boxes that the applet
might contain. Such GUI components are objects in their own right, defined by other classes.
The applet's paint() method is called by the system as soon as the applet appears on the screen. But it
can also be called at other times. It is called whenever the contents of the applet need to be redrawn.
This might happen if the applet is covered up by another window and is then uncovered. It can happen
when you scroll the window of a browser, and the applet scrolls into view. And, it is especially important
to note, the applet's paint() method can be called because the program makes a request for the applet to
be redrawn. Such requests are made by calling a method named repaint().

Passing Parameters to Java Applets


Parameters are an easy way to configure Java applets without actually changing the source file. In the
previous applet example, the text drawn on the screen was drawn using the blue color. This can be done
by passing a parameter to the applet specifying that it use the blue tag.
Passing parameters to the applet using HTML parameters.
<HTML>
<HEAD>
<TITLE>This is the LifeCycle applet!</TITLE>
</HEAD>
<BODY>
<H1> Life Cycle of Applet </H1>
<BR>
<APPLET CODE="LifeCycleApplet.class" WIDTH=600 HEIGHT=50>
<PARAM NAME=color VALUE="blue">
</APPLET>
</BODY>
</HTML>
How does the Java applet determine the value of the parameters?
The applet has to call the getParameter() method supplied by the java.applet.Applet parent class. Calling
getParameter("color") using the previous Java applet example would return a String value containing the
text "blue". It is then left up to the applet to take advantage of this information and actually paint the text
blue on the screen.
Here are three methods commonly used by applets:
String getParameter(String name)-Returns the value for the specified parameter string
URL getCodeBase()-Returns the URL of the applet
URL getDocumentBase()-Returns the URL of the document containing the applet

Page 157 of 191

COREJAVA
Example
import java.applet.*;
import java.awt.*;
public class AppletParam extends java.applet.Applet {

String input_from_page;
public void init() {
input_from_page=getParameter("string");
if (input_from_page==null)
input_from_page="Java";
input_from_page="Hello "+ str;

}
public void paint(Graphics g)
{
g.drawString(str,10, 100);
}
}

HTML FILE
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3Applet HTML Page</H3>
<P>
<APPLET code=" AppletParam.class" width=350 height=200>
<PARAM NAME="string" VALUE="Applet">
</APPLET>
</P>

<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>


</BODY>
</HTML>

The PARAM HTML tag occurs between <APPLET> and </APPLET>. It has two parameters of its own,
NAME and VALUE. The NAME identifies which parameter this is for the getParameter method.
VALUE is the value of the parameter as a String. Both must be enclosed in double quote marks like all
other HTML tag parameters.
Page 158 of 191

COREJAVA

SIMPLE GRAPHICS AND GUI TECHNIQUES

Applets can work in a Graphical environment. The AWT is actually a package named java.awt included
with the JDK is used for this purpose. The following Table lists the most commonly used classes with a
brief description of each class.
Commonly used user interface classes in package java.awt.
Class Name

Description

Button

A standard pushbutton user interface component

Canvas

A canvas that is used as a graphics drawing context

Checkbox

A standard checkbox user interface component

CheckboxGroup

A user interface component used to group checkboxes

CheckboxMenuItem

A checkbox that is displayed as a menu item

Choice

A menu component that displays the currently selected


choice

Color

A class used to encapsulate colors in Java

Component

The base class of all user interface components

Container

A base class for all container/grouping components

Dialog

A standard dialog screen that can be either modal or


nonmodal

FileDialog

A standard file selection dialog that is OS-dependent

Font

A class used to encapsulate fonts in Java

Frame

A frame that can contain window objects

Graphics

The base class used for all graphics and drawing


operations

Image

A class used to encapsulate images in Java

Label

A standard label user interface component

List

A standard list box user interface component

Menu

A menu component that resides on a menubar

MenuBar

The menubar that contains menus and menu items

MenuItem

Menu selection items that trigger program events

Panel

A user interface component used to surround other


components

Scrollbar

A standard scrollbar user interface component

TextArea

A multiline text editing window

TextField

A single-line text editing window

Window

A window inside a frame that contains multiple objects

import java.awt.TextField;
import java.awt.List;
import java.awt.Button;
import java.applet.Applet;
public class EditList1 extends java.applet.Applet
{
Page 159 of 191

COREJAVA
TextField theText;
List
theList;
Button
theButton;
public void init()
{
theText = new TextField();
theList = new List();
theButton = new Button("Add text to list!");
add(theText);
add(theList);
add(theButton);

}
}
Adding components to applets
Applets can be used as a container for visual components, such as those provided by the java.awt
package. Components are created, and then added to the applet container. The positioning of applet
components is controlled by a layout manager.
Layout managers
There are several different layout managers, and you can even write your own if so inclined. The easiest
layout manager is the FlowLayout, which adds components on a first-come, first-served manner. Applets
that use a flow layout will allow components to flow freely from left to right, top to bottom, and can handle
different applet sizes.

Example of FlowLayout, with different applet sizes


For more specialised layout, you could use a GridLayout manager, or a BorderLayout manager.
GridLayouts allow you to place applets in a grid format, and BorderLayouts allow you to specify a general
direction.

North
West

Centre

East

South
BorderLayout directions
As an example, here is a code snippet using a BorderLayout, which creates a text area with a button to
its right.
// Set layout manager to flow layout
setLayout(new BorderLayout());
Page 160 of 191

COREJAVA
// Add three components to applet
add(new TextArea(5,5), "North");
add(new Button("Ok"), "East");

AWTCOMPONENTS
There are a wide variety of AWT components, ranging from text labels and buttons to selection lists,
windows and dialogs. A selection of more common components from the java.awt package is presented
below, along with a sample applet to demonstrate each component's use.

Label
Labels are great for providing user prompts, and for displaying information that should not be modified by
users. If you want to have modifiable labels, consider using text fields instead. In almost all of the
examples presented here, a status bar containing a label is used to convey information to the user.

Button
Buttons are useful when an application must recieve specific instructions from the user before
proceeding. For example, when a user must enter data, and then wants to perform a task, a
button can be used to instruct the applet / application to proceed when the data entry is
complete.
click here

Example Source
public class ButtonApplet extends Applet {
Button button;
String msg;
public void init() {
button= new Button("click here");
add(button);
}

Choice
Choice components take up very little screen space, and can present the user with a series of choice
from which a single selection can be made

Example Source
import java.applet.*;
public class ChoiceApplet extends Applet {
public void init() {
Choice pizzaChoice=new Choice();
pizzaChoice.add("Large Pizza");
pizzaChoice.add("Medium Pizza");
pizzaChoice.add("Small Pizza");
add(pizzaChoice);
pizzaChoice.select("Medium Pizza");
}
Page 161 of 191

COREJAVA
}

Page 162 of 191

COREJAVA
TextField
Textfield components are useful for obtaining short pieces of information from users. They are limited to
single line input (for multiple lines, use a TextArea instead).
Go ahead and Type

Example Source
import java.awt.*;
import java.applet.*;
public class TextFieldApplet extends java.applet.Applet {
public void init(){
TextField text=new TextField(18);
text.setFont(new Font("Serif", Font.PLAIN,12));
text.setText("Go ahead and Type ");
add(text);
}
}

List
List components fulfill much the same functionality as choice components. Items can be added, and the
currently selected item can be returned. However, they take up more space than a choice
component. This can be useful at times, however, as the items can be presented to the user,
without he or she having to actually click on the component to see. Furthermore, multiple
selections are allowable with the list component (though this feature must be enabled).

import java.applet.*;
import java.awt.*;
public class ListApplet extends java.applet.Applet {
public void init() {
String fruit[]={"Mango","Pineapple","Banana","PawPaw"};
List fruitlist=new List(fruit.length-1,true);
for(int i=0;i<fruit.length;i++)
fruitlist.add(fruit[i]);
add(fruitlist);
}
}

TextArea
Textarea components are useful for getting a large amount of data from a user, or for displaying a large
amount of data that is free to be modified. They take up more screen real estate than textfields,
but can conserve quite a lot of room because they have support for scrollbars.

Page 163 of 191

COREJAVA

import java.awt.*;
import java.applet.*;
public class TextAreaApplet extends java.applet.Applet {
public void init() {
TextArea display=new TextArea(10,6);
display.setFont(new Font("Monospaced",Font.PLAIN,12));
display.setText(" This is a test and interesting too");
display.setEditable(false);
add(display);
}
}

CheckBox

Large Pizza

Medium
Pizza

Small Pizza

Example Source
public class CheckboxApplet extends java.applet.Applet implements ItemListener{
String msg;
Checkbox option1;
Checkbox option2;
Checkbox option3;
public void init() {
option1 = new Checkbox("Large Pizza");
option2 = new Checkbox("Medium Pizza");
option3 = new Checkbox("Small Pizza");
option1.setState(true);
add(option1);
add(option2);
add(option3);
}

ThreadingApplets
Applets are embeddable Java applications that are expected to be able to start and stop themselves on
command. Unlike threads, applets can be started and stopped any number of times. A Java-enabled
Web browser normally starts an applet when the applet is displayed and stops it when the user moves to
another page or scrolls the applet out of view. In general, we would like an applet to cease its
nonessential activity when it is stopped, and resume it when started again.
Consider a simple base class for an Applet that maintains a Thread to automatically update its display
at regular intervals. UpdateApplet handles the basic starting and stopping behavior as shown below.
public class UpdateApplet extends java.applet.Applet
Page 164 of 191

COREJAVA
implements Runnable {
private Thread updateThread;
int updateInterval = 1000;
public void run() {
while ( true ) {
try {
Thread.sleep( updateInterval );
}
catch (InterruptedException e ) { }
repaint();
}
}
public void start() {
if ( updateThread == null ) {
updateThread = new Thread(this);
updateThread.start();
}
}
public void stop() {
if ( updateThread != null ) {
updateThread.stop();
updateThread = null;
}
}
}
UpdateApplet is a Runnable object that alternately sleeps and calls its repaint() method. It has two other
public methods: start() and stop(). These are methods of the Applet class that are overridden; These
start() and stop() methods are called by the Java environment to tell the applet when it should and should
not be running.
UpdateApplet illustrates an environmentally friendly way to deal with threads in a simple applet.
UpdateApplet kills its thread each time the applet is stopped and recreates it if the applet is restarted.
When UpdateApplet's start() method is called, we first check to make sure there is no currently executing
updateThread. We then create one to begin our execution. When our applet is subsequently stopped, we
kill the thread by invoking its stop() method and throw away the reference by setting it to null. Setting
updateThread to null serves both to allow the garbage collector to clean up the dead Thread object, and
to indicate to UpdateApplet's start() method that the thread is gone.
In truth, an Applet's start() and stop() methods are guaranteed to be called in sequence. As a
result, we shouldn't have to check for the existence of updateThread in start()
With UpdateApplet is a simplest clock applet with just a few lines of code. Figure shows the Clock.
public class Clock extends UpdateApplet {
public void paint( java.awt.Graphics g ) {
g.drawString( new java.util.Date().toString(), 10, 25 );
}
}

Page 165 of 191

COREJAVA
Figure: The clock applet

The java.util.Date().toString() sequence simply creates a string that contains the current
time;
The Clock applet provides a good example of a simple thread;
The problem with applets is that we have no control over how a user navigates Web pages. For example,
say a user scrolls our applet out of view, and we use suspend() to suspend the applet. Now we have no
way of ensuring that the user will bring the applet back into view before moving on to another page. And
actually, the same situation would occur if the user simply moves on to another page and never comes
back.
If we call suspend(), we'd really like to make sure we call resume() at a later date, or we'll end up leaving
the thread hanging in permanent suspense. But we have no way of knowing if the applet will ever be
restarted, so just putting a call to resume() in the applet's start() method won't work.
UpdateApplet:
public void start() {
if ( updateThread == null ) {
updateThread = new Thread(this);
updateThread.start();
}
else
updateThread.resume();
}
public void stop() {
updateThread.suspend();
public void destroy() {
if ( updateThread != null ) {
updateThread.stop();
updateThread = null;
}
}

These modifications change UpdateApplet so that it suspends and restarts its updateThread, rather than
killing and recreating it. The new start() method creates the thread and calls start() if updateThread is
null; otherwise it assumes that the thread has been suspended, so it calls resume(). The applet's stop()
method simply suspends the thread by calling suspend().
What's new here is the destroy() method. This is another method that UpdateApplet inherits from the
Applet class. The method is called by the Java environment when the applet is going to be removed
(often from a cache). It provides a place where we can free up any resources the applet is holding. This
is the perfect place to cut the suspense and clean up after our thread. In our destroy() method, we check
to see that the thread exists, and if it does, we call stop() to kill it and set its reference to null.

Inter AppletCommunication
The button component was used to add items to the list component. All of these operations occurred
inside a single applet. However, imagine a case where a button-click in one applet could update a
Page 166 of 191

COREJAVA
database and trigger update messages to another applet running within the same Web page or even
running on a remote computer. This type of communication is known as inter-applet communication.
Possibilities of Inter-Applet Communication
There are several interesting possibilities that will be available when applets are truly enabled to
communicate among themselves. Here are possible types of communication:
Applets that share the same Web page within the same browser
Applets loaded in completely different browser windows
Applets loaded on different client's browsers
Applets loaded from different servers
Using a technology such as Java Beans or ActiveX will also allow developers to "wrap" their applets with
code that will expose an applet's methods and properties in some standardized way. Using the
component model, the applet could potentially be dropped onto a Visual Basic form or used to
communicate with applications written in other programming languages.

JavaSwing
What is Swing?

A group of 14 packages to do with the UI


451 classes as at 1.4 (!)
Part of JFC Java Foundation Classes (compare now defunct MFC)

Swing and the AWT

AWT = abstract windows toolkit (cross platform)


AWT = earliest version of Java GUI
eg Frame AWT not JFrame Swing
Most Swing components are 'lightweight'
Do not mix AWT and Swing
Use Swing

Swing and threads

A thread is a lightweight process


Most Swing components are not thread-safe
Solution is to make sure all code that creates and modifies Swing components executes in the
same 'event-dispatching' thread
Start a Swing application using the following code..

Swing and Threads - starting up

Page 167 of 191

COREJAVA
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI(); // << method to start it
}
});
}
CreateAndShowGUI
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Hi..");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add a label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}

LayoutManagers

Most Swing UIs utilise a LayoutManager to control positioning of items


There is a choice of these which work in different ways
Initially we do without one, and position items ourselves:
frame.setLayout(null);

Absolutepositioning
JFrame frame = new JFrame("I am a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,30,300,100);
frame.setLayout(null);
JButton butt=new JButton("Click me");
frame.getContentPane().add(butt);
butt.setBounds(20, 20, 200,20);
frame.setVisible(true);

Try this out


- start with last example and put this in CreateandShowGUI()
Responding to user actions
Page 168 of 191

COREJAVA
Based on an event-handling model
New component eg a button should have a Listener specified
The Listener object is programmed to respond to Event objects coming from the
component
The Listener object needs to implement the appropriate interface

Interfaces
An interface is a set of methods
eg the ActionListener interface has just one method public void actionPerformed(ActionEvent e)
A class can declare that it implements it eg
public class Main implements ActionListener
Then it must actually define the methods in that interface
Or the compiler will complain
Classes can implement multiple interfaces

Buttonclickdemo

See source code in Word


JButton and JLabel
clickCounts remembers the number of clicks
Class implements ActionListener
Make JFrame, JButton and JLabel
Instantiate application object
Set to be the listener of the button

Page 169 of 191

COREJAVA

Which button?

If have several buttons, all must link to actionPerformed


How to know which button was clicked?
Use the .getSource method of the ActionEvent object

Example which button


butt1=new JButton("Button 1");
..
butt2 = new JButton("Button 2");
..
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==butt1)
label.setText("Butt1 clicked");
else
label.setText("Butt2 clicked");
}

Setting a laf
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel" );
Page 170 of 191

COREJAVA
}
catch (Exception e)
{
System.out.println("Cant get laf");
}
..
JFrame frame = new JFrame();

This in main() - set laf as first step try .. catch.. because could fail UIManager is in java.lang
Findinginstalledlafs
Object a[]= UIManager.getInstalledLookAndFeels();
for (int i=0; i<a.length; i++)
System.out.println(a[i]);

JFrame.setDefaultLookAndFeelDecorated(true);
.. call JFrame constructor

Swing has a lot of classes

1.containers
things that hold other things
eg JFRame
2.controls
User I/O widgets
eg JButton
Containers
top level containers - JFrame JApplet JDialog
general purpose containers panel
scroll pane
split pane
tabbed pane
Page 171 of 191

COREJAVA
tool bar

JPanel( in createAndShowGUI)
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("I am a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,30,300,100);
frame.setLayout(null);
//Create a panel
JPanel myPanel = new JPanel();
myPanel.setBackground(new Color(255,3,25));
myPanel.setOpaque(true);
//Make it the content pane.
frame.setContentPane(myPanel);
frame.setVisible(true);

JPanel
Is a subclass of JComponent
So are all the other Swing components except the top-level containers
You can add a border
And a tool-tip
Tooltipandborder

Page 172 of 191

COREJAVA

JTextField

For single-line text input


Methods getText, setText
Can use ActionListener, triggered when Enter pressed

Example of JTextField

See source in Word doc


Check Main object fields for label and textfield
Make a panel, set as content pane
Make and add text field
Add actionlistener
Make and add a label
Program actionPerformed

JTextArea
JPanel myPanel = new JPanel();
app.textArea = new JTextArea("Type here",5, 20);
myPanel.add(app.textArea);
TextArea expands rows and columns as needed

Page 173 of 191

COREJAVA

JScrollPane
JTextArea textArea = new JTextArea("Type here",5, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.setContentPane(scrollPane);

JScrollBar
See source code
JScrollBar and JLabel
Constructor arguments
implements AdjustmentListener
adjustmentValueChanged
e.getValue()

Page 174 of 191

COREJAVA

JCheckBox

See source code


implements ActionListener
isSelected()

RadioButton

Come in groups only 1 selected per group


See demo code
Make radiobuttons
Make group
Add radiobuttons to group
ActionListener

RadioButtongroupborder
..
JPanel groupPanel = new JPanel();
groupPanel.setBounds(10,10,100,60);
groupPanel.setBorder(BorderFactory.createLineBorder(Color.black));
frame.getContentPane().add(groupPanel);
groupPanel.add(app.choice1);
groupPanel.add(app.choice2);

ListBox
..

See source code


Page 175 of 191

COREJAVA

Data held in array


List box shows array
List box inside scroll pane
myList.getModel().getElementAt(..

LayoutManagers

Page 176 of 191

COREJAVA

Grid
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(4,3,5,5));
for (int i=0; i<10; i++)
frame.getContentPane().add(new JButton(""+i));
frame.pack();
frame.setVisible(true);

Menus

Page 177 of 191

COREJAVA

Main app = new Main();


..
JMenuBar myMenuBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenuItem item = new JMenuItem("Exit");
item.addActionListener(app);
menu1.add(item);
myMenuBar.add(menu1);
frame.setJMenuBar(myMenuBar);
..
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}

JToolBar
..
.. frame is BorderLayout
..
JToolBar toolBar = new JToolBar("Test");
JButton butt1 = new JButton(new ImageIcon("icon.gif"));
toolBar.add(butt1);
..
frame.add(toolBar, BorderLayout.PAGE_START);

JComponents have a paint() method


This is called by the system when it needs to display the object
Initially and eg after a re-size
You can over-ride paint() to control the appearance of the component
This implies you sub-class the component
Page 178 of 191

COREJAVA

The paint method has a Graphics object as a parameter


This is a context eg color, font etc
You tell the Graphics object to show things

public class MyFrame extends JFrame


{
public MyFrame()
{
super("Some title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(20,30,230,180);
myPanel = new MyPanel();
myPanel.setOpaque(true);
setContentPane(myPanel);
setVisible(true);
}
MyPanel myPanel;
}

public class MyPanel extends JPanel


{
public void paint(Graphics g)
{
g.drawLine(0,0,getWidth(),getHeight());
g.drawString("Hello",getWidth()/2,getHeight()/2);
}
}

------------------* * * *-----------------

Page 179 of 191

COREJAVA

Viva Questions

1.List The Features of Java?


Simple
Architecture-neutral
Object-oriented
Portable
Distributed
High-performance
Interpreted
Multithreaded
Robust
Page 180 of 191

COREJAVA
Dynamic
Secure
2.What is Byte code?
Java compiler translates a Java program into an intermediate language called Java bytecodes-the platform-independent codes interpreted by the Java interpreter.
3.What are he various applications of Java?
Applets
Networking
Internationalization
Security
Object serialization
Java Database Connectivity (JDBC)
4.Why do Java is called Plat Form Independent?
Java is called platform independent language because 100% Pure Java programs are compiled
into machine-independent bytecodes, they run consistently on any Java platform
Explain the Structure of Typical Java Program?
Documentation section
Package statement
Import statement
Interface Statements
Class definitions
Main Method Class
{
Main Method Definition

}
5.What is Branching?
When a program breaks the sequential flow and jumps to another part of the code ,it is called
branching.
6.What is a Conditional and Unconditional Branching?
When the branching is based on a particular condition, it is known as conditional branching. If
branching takes place without any decision, it is known as unconditional branching.
7.What is the use of Switch statement?
The switch statement tests the value of a given variable against a list of case values and when a
match is found,a block of statements associated with that case is executed.
8.What are the Control Statements Available in Java?
While
The general syntax of the while statement is:
Page 181 of 191

COREJAVA
while (expression) {
statement
}

..
do-while
The general syntax of the do-while is:
do {
statement(s)
} while (expression);

..
for
The general form of the for statement can be expressed like this:
for (initialization; termination; increment)
{
statement
}
What are the Decision-Making Statements are Available in Java?
The if/else Statements
the simple form of if can be written like this:
if (expression) {
statement(s)
}
if (response == OK) {
// code to perform OK action
} else {
// code to perform Cancel action
}
The switch Statement
switch(expression)
{
case value1 :
statements;
break;
case value 2 :
statements;
break;
case value 3 :
statements;
break;
default :
}
What is the use of ? : Operator?
It is used for making two-way decisions,it is a combination of ? and : ,and three operands. This
operator is known as ternary operator.
What is the Encapsulation?What is the Role in Object Oriented Programming?
Encapsulation provides the ability to hide the internal details of an object from its users. The
outside user may not be able to change the state of an object directly. Encapsulation is
Page 182 of 191

COREJAVA
implemented using the access modifier keywords public, private and protected. The concept of
encapsulation is also known as data hiding or information hiding.
Define Abstraction?
Abstraction is one of the object-oriented concepts; it is nothing but expresses the essential things
not much in detail.
What is the Inheritance?
Inheritance is the process by which one object acquires the properties of another.
Define Polymorphism?
Polymorphism is a feature that allows one interface to be used for ageneral class of action.
What is Unicode?
Java use Unicode to represent a character. Unicode defines a fully international character set that
can represent all of the characters found in all human languages.
What is Scope and LifeTime of variables in Java?
The variable has the scope only with in the block, where it is declared. They are created when
their scope is entered, and destroyed when their scope is left.
What do you Mean by Casting?
Conversion of data into one type to another type is known as casting. They are classified into
two types explicit casting and implicit casting.
Explicit casting two incompatible types need explicit conversion (target-type) value
Implicit casting it is also known as automatic type conversion . When the two types are
compatible that is the destination type is larger than the source type automatic type conversion
will be tack place.
What will be the output of the following statement (A= 64;)?
System.out.println(A<<2)
64- 0100 0000
64<<2-0001 0000 0000=256.
What will be the output of the following statement (A= 64;)?
System.out.println(A<<2)
64- 0100 0000
64>>2-0000 1000=8
What is the Use of Break Statement?
A Java(TM) programming language keyword used to resume program execution at the
statement immediately following the current statement. If followed by a label, the program
resumes execution at the labeled statement.
What is the Use of Continue Statement?
A Java(TM) programming language keyword used to resume program execution at the end of
the current loop. If followed by a label, "continue" resumes execution where the label occurs.
What is the Use of Transient Keyword?
A keyword in the Java programming language that indicates that a field is not part of the
serialized form of an object. When an object is serialized, the values of its transient fields are not
included in the serial representation, while the values of its non-transient fields are included.
141. Write short note on isAlive().
How we can get size of an Array?
The size of an array can be get by using the statement
arrayname.length

Page 183 of 191

COREJAVA
Why two classes are used to handle String in java?
The Java platform provides two classes, String and StringBuffer, that store and manipulate
strings-character data consisting of more than one character. The String class provides for
strings whose value will not change.
The StringBuffer class provides for strings that will be modified; you use string buffers when
you know that the value of the character data will change. You typically use string buffers for
constructing character data dynamically.
What is the Wrapper Class?
An object that encapsulates and delegates to another object to alter its interface or behavior in
some way. All the primitive data types has it is own wrapper class.
Define Class & Object?
A class is prototype, that defines the variables and the methods common to all objects of a
certain kind. An object is a software bundle of related variables and methods. Software objects
are often used to model real-world objects you find in everyday life.
What is an Instance of a class?
Any item of data that is associated with a particular object. Each instance of a class has its own
copy of the instance variables defined in the class. Also called a field.
Define Class Variable?
A data item associated with a particular class as a whole--not with particular instances of the
class. Class variables are defined in class definitions. Also called a static field.
What is a Static Method?
A method that is invoked without reference to a particular object. Class methods affect the class
as a whole, not a particular instance of the class. Also called a static method.
What is the Use of this keyword?
this keyword can be used to represent the current object. And also used to hide the instance
variable.
What is Garbage Collection?
When there is no more reference to an object is
found jvm collect the memory
automatically. This process is known as Garbage Collection.
What is a destructor and how it is implemented in java?
The destructor is invoked when an object is destroyed. In java a mechanism called finalization is
used to handle the destructor. It needs to override a method called
protected void finalize()
What is Method Overloading?
Two or methods with in the same class have the same name, with different signature.
What is the difference between call-by-value and callby- reference?
In the case of call-by-value only the copies of the parameter are passed. So that changes made to
the parameter has no effect on the argument used to call it.
In the case of call-by-reference a reference to the argument is passed to the parameter. So that
changes made to the parameter change the argument used to call it.
What is an Access Specifier?
A member of a class can be accessed is determined by the access specifier. Java supports the
following access specifier
Page 184 of 191

COREJAVA
public
private
protected
What do you mean by garbage collection? Why do we need finalize()
method?
Deallocation of memory allocated dynamically for an object is done automatically in java. The
technique that accomplishes this is called garbage collection. When no reference to an object
exists, that object is assumed to be no longer needed, and the memory occupied by the object
can be reclaimed. There is no explicit need to destroy objects in java. The garbage collection
occurs sporadically during the execution of your program.
Finalization is a mechanism provided by java to allow an object to perform some action when it
is destroyed. For eg if an object is holding some non-java resource such as a file handle or
window character font, then you might want to make sure these resources are freed before a
object is destroyed. By using finalization, we can define specific actions that will occur when an
object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, simply define the finalize() method. The general form is:
protected void finalize()
{
//finalization code here
}
List out Various types of Inheritance?
Simple inheritance - One base class and one derived class.
Multilevel inheritance - a sub class derived from another sub class
Hierarchical inheritance two or more sub class have the same base class
Define Method Overriding?
Providing a different implementation of a method in a subclass of the class that originally
defined the method. That is defining one method with same name and signature.
Write short notes on final key word?
A Java(TM) programming language keyword. You define an entity once and cannot change it or
derive from it later. More specifically: a final class cannot be subclassed, a final method cannot
be overridden and a final variable cannot change from its initialized value.

Define Abstract class and Method?


A class that contains one or more abstract methods, and therefore can never be instantiated.
Abstract classes are defined so that other classes can extend them and make them concrete by
implementing the abstract methods. Abstract method is a method that has no implementation.
Distinguish between public, private and protected?
Public signifies that the method or variable can be accessed by elements residing in other
classes. Private signifies that the method or variable can only be accessed by other elements of
Page 185 of 191

COREJAVA
its class. Protected signifies that the method or variable can only be accessed by elements
residing in its class, subclasses, or classes in the same package.
Define Subclass?
Sub class is a class that is derived from a particular class, perhaps with one or more classes in
between. A subclass is a class that extends another class. A subclass inherits state and behavior
from all of its ancestors.
What is super class and what is the use of super keyword?
A class from which a particular class is derived, perhaps with one or more classes in between.
A Java(TM) programming language keyword used to access members of a class inherited by the
class in which it appears.
Define a Package?
A package is a collection of related classes and interfaces providing access protection and
namespace management. To make classes easier to find and to use, to avoid naming conflicts,
and to control access, programmers bundle groups of related classes and interfaces into
packages.
How a Package is created in Java?
To create a package and put a class or an interface in it, put a package statement at the top of the
source file in which the class or the interface is defined. For example, the following code
appears in the source file Circle.java and puts the
Circle class in the graphics package:
package graphics;
public class Circle extends Graphic implements Draggable
{
...
}
To import a specific member into the current file, put an import statement at the beginning of
the file before any class or interface definitions but after the package statement, if there is one.
import graphics.Circle;
What do you mean by API?
Application Programming Interface. The specification of how a programmer writing an
application accesses the behavior and state of classes and objects.
What do you mean by Core Packages?
The required set of APIs in a Java platform edition, which must be supported, in any and all
compatible implementations.
Define Interface?
An interface is a named collection of method definitions (without implementations). An
interface can also declare constants. All the methods declared in the interface are abstract
methods by default. And all the data members are static final members.
What are the difference between the abstract class and interface?
An interface cannot implement any methods, whereas an abstract class can.
A class can implement many interfaces but can have only one superclass.
An interface is not part of the class hierarchy. Unrelated classes can implement the same
interface
Page 186 of 191

COREJAVA
How is an interface used in Java?
A class that implements an interface adheres to the protocol defined by that interface. To declare
a class that implements an interface, include an implements clause in the class declaration. A
class can implement more than one interface (the Java platform supports multiple inheritance for
interfaces), so the implements keyword is followed by a comma-separated list of the interfaces
implemented by the class.
What is Java?
Java is an object oriented programming language
Is Java invented for Internet?
No, it was developed for programming towards tiny devices
What is byte code?
It is machine understandable code and targeted for JVM (Java Virtual Machine). It is class file.
What is JVM?
Java Virtual Machine which accepts java byte code and produces result
What are java buzzwords?
Java buzzwords explain the important features of java. They are Simple,
Secured, Portable, architecture neutral, high performance, dynamic, robust, interpreted etc.
Is byte code is similar to .obj file in C?
Yes, both are machine understandable codes
No, .obj file directly understood by machine, byte code requires JVM
What is new feature in control statements comparing with C/C++?
Labeled break and labeled continue are new
What are new features in basic features comparing with C/C++?
Data types: All data types on all machines have fixed size;
Constants: final is used to declare constant
Boolean Type: boolean is new data type in Java which can store true/false
There are no structures/unions/pointers
Is String data type?
No, Strings are classes in Java (Arrays are classes)
What are length and length( ) in Java?
Both gives number of char/elements, length is variable defined in Array class, length( ) is
method defined in String class
What is class?
Class is blue print for objects; Class is collection of objects; Class gives the general structure for
objects.
What is object?
Object is an instance of class. Object is real world entity which has state, identity and behavior.
What is encapsulation?
Encapsulation is packing of data with their methods
Page 187 of 191

COREJAVA
What is abstraction?
Abstraction is the process of identification of essential features of objects
What is data hiding?
Implementation details of methods are hidden from the user
What is hierarchy?
Ordering of classes (or inheritance)
What is inheritance?
Extending an existing class is called inheritance. Extracting the features of super class
Why inheritance is important?
Reusability is achieved through inheritance
Which types of inheritances are available in Java?
Simple, Hierarchical and Multilevel
Can we achieve multiple inheritances in Java?
With the help of interfaces we can achieve
What is interface?
Interface is collection of final variables and abstract methods
(We need not give final and abstract keywords and By default they are public methods)
What is the difference between class and interface?
Class contains implemented methods, but interface contains non-implemented methods
What is polymorphism?
Multiple (poly) forms (morphs)
Same instance can respond different manners is called polymorphism
Can we achieve run time polymorphism in Java?
Yes, also called as dynamic polymorphism. Possible by dynamic method dispatch
What is dynamic method dispatch?
When you assign object of sub class for the super class instance, similar methods of super class
are hidden
What is overloading?
Same method name can be used with different type and number of arguments (in same class)
What is overriding?
Same method name, similar arguments and same number of arguments can be
defined in super class and sub class. Sub class methods override the super class methods.
What is the difference between overloading and overriding?
Overloading related to same class and overriding related sub-super class
Compile time polymorphism achieved through overloading, run time polymorphism achieved
through overriding
Page 188 of 191

COREJAVA
What is keyword?
Java reserved word which should is not used as variable/class-name (e.g.: break, for, if, while
etc)
What is final keyword?
Used before variables for declaring constants
Used before methods for preventing from overriding
Used before class-name for preventing from inheritance
What is static keyword?
Used before variable for defining shared variables
Used before method for defining class-level methods, these methods
can be called without creating objects (e.g.: parseInt method of Integer class)
What is abstract keyword?
Used for creating abstract class, class which doesn't have any instance
What is this keyword?
To call current class variables and current class methods we can use this key word
What is this( )?
Used for calling another constructor of current class
What is super keyword?
To call super class variables and super class methods we can use super key word
What is super( )?
Used for calling of super class constructor and it should be first executable statement in sub
class constructor
What is package?
Package is collection of classes and interfaces
How to define package?
By using package keyword before the definition of class
What is CLASSPATH?
It is an environment variable which is used for defining the location of class files
What is jar?
Jar stands for Java archive files, compressed set of class files and can be used in CLASSPATH
What is the meaning of import java.awt.*;?
Import all the classes and interfaces in the java.awt.package. This doesn't imports other
packages
defined in java.awt. package.
Is it necessary to give import java.awt.event.*;, when already import java.awt.* given?
Yes, import java.awt.* doesn't imports event package defined in java.awt. package.
What is exception?
Abnormal termination of program is called exception

Page 189 of 191

COREJAVA
What is exception handler?
A method which controls abnormal termination of program
What are the keywords used for exception handling?
try, catch, throw, throws and finally
What is the difference between throw and throws keywords?
throw keyword is used for invoking an exception (For raising)
throws keyword lists exception names which can be ignored from the method execution
What is the difference between final and finally?
final is used for defining constants
finally is used for executing code after completion of exception handler
What is catch( ) block?
Exception handler that controls abnormal termination of program
Can we have multiple catch( ) blocks?
Yes, but first sub class exceptions should be handled
What happen is we not handle sub class exception first?
Generates compile time error saying that unreachable code is defined in the program
Multithreading Section
What is thread?
Thread is a part of process, also called as light weight process
What is multithreading?
Simultaneous execution of threads is called multithreading
What is a process?
Program under execution is called process
How to create thread?
By creating instance of Thread class or implementing Runnable interface
Can you name any methods of Thread class?
currentThread( ), setName( ), getName( ), setPriority( ), getPriority( ), join( ), isAlive( )
What is join( ) method of Thread?
Combines two or more threads running process and wait till their execution is completed
What are the states in Thread Life Cycle?
Ready, running, block, wait, dead
What is an applet?
Applet is a java program which runs via java-enabled browser
Is graphics possible only in applets?
No, stand alone program frames can also display graphics
What is the relation between java and Internet?
With the help of java applets, we can write programming for Internet
Page 190 of 191

COREJAVA
Which package is required to write GUI (Graphical User Interface) programs?
Java.awt
Which package is required to write Applets?
Java.applet
What is an event?
A kind of action
What is event handling?
A procedure which gives functionality for the events
How to implement event handling?
By using interfaces like ActionListener, MouseListener
What is the method available in ActionListener Interface?
public void action performed(AcitonEvent e)
How to pass parameters to Applets?
By using PARAM tag.

Page 191 of 191

Você também pode gostar