Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
Satellite AT & T
Hyundai
Server 50GBPS
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
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
PIV
x.java x.class JVM
Celeron
It consists
byte code
format
JVM
Cyrix
Componentsof JVM
JVM
Class
Execution
Byte code
Engine
verifier
Security Garbage
Manager Collector
4
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.
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
TCP/IP:- Transmission Control Protocol/Internet Protocol.
6
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.
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.
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.
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
Class files Loader
Subsystem
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;
print a; 2 + 2 memory JIT Compiler Processor
JavaProgramming: -
Comments represent description of the features of a program.
The main advantages of comments are readability7 of the program is increased.
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
main ()
10
{
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
8
VersionV 1.0: - 1 represents major version and 0 represents minor version.
9
* 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.
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.
12
newis an operator.
13
Systemis a class.
14
Out is a variable.
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.
Backslashcodes
S. No. Meaning
or escapesequence
Page 11 of 191
COREJAVA
1. \n New line
2. \r Enter key
3. \t Horizontal tab
4. \b Backspace key
5. \\ \
6. \
7. \
15
FONTis a class
16
BOLDis a constant
17
Network:- Interconnection of computers are called as network.
18
Invocation= Calling
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
-9223372036854775808 to
4. long 8 bytes +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
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 8
3. * Multiplication a*b 65
4. / Division a/b 2.6
Modulus operator (Remainder
5. % a% b 3
of division)
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
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
BitwiseCompliment(~): - This operator gives complement from of a number. -2 3
Ex: - int x = 10;
~x = -11; -3 2
Bitwiseand(&): - This operator performs anding operations on individual bits
a b a & b This table is called truth table. It means, it shows
-4 1
0 0 0 input and output bits 0
0 1 1
1 0 0
1 1 1
AND 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 0 = 10
x<< 2 0 0 1 0 1 0 0 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 0 0 0 0 1 0 1 0
Page 17 of 191
COREJAVA
x >> 2 0 0 0 0 0 0 1 0 =2
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 2 3 4 5 6 7 8 9 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
Block:- Block represents a group of statements written in left and right braces.
20
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);
}
}
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);
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
Class obj = new Class() InputStreamReader
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 1. No need to declare the size of vector. We may
advance. An array is denoted as [ ] give its size or you may not.
2. Vector can always grow in size if we start adding
2. Once declared array cant grow in size.
more elements to it then its size will grow.
3. Array can store primitive data types like int, 3. Storing the primitive data types is not possible in
char, float, double . case of Vector. It can store only object references.
4. Array is not synchronized. 4. Vector is synchronized.
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.
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.
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.
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);
}
}
Ex: - //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
Page 32 of 191
COREJAVA
2
3
Ex: - 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:-
babu
babu
babu
babu
Ex: - //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)
Ex: - //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.
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
{
public static void main(String args[ ]) s2 Hai
{
String s1 = Hello;
String s2 = new String(Hai);
Hello
s1= s1+s2; Hai
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.
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.
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()
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.
Q) Whyjava is objectorientedlanguage?*****
Ans:- Java obeys all the features of OOPS. (The above 6 features)
Page 38 of 191
COREJAVA
Object based programming languages contain all the features of oops except inheritance.
Ex: - Smalltalk, Simula67 etc
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 1. A method is a function, it represents group of
instance of a class. statements to perform tasks.
2. Constructor doesnt return any type, not even 2. Method can return void or valid return type.
void also.
3. Constructor will have the same name of that its 3. As a name except the class method name, begin
class. 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
6. This refers to instance of class.
present/same class.
7. Super refers to invoke the super class 7. Execute an overridden method in the super
constructor. class.
8. Constructor will automatically invoke when an
8. Method has called explicitly.
instance of class is created.
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.
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 1. An instance variable will have a separate copy
in memory is shared by all the objects of class. available in each object.
2. If any modification of one object will affect other 2. If any modification of one object will not affect
objects. other objects.
3. Static variables are executed at compilation 3. Instance variables are executed at runtime.
time.
4. Instance means objects. Objects are
dynamically created by JVM on the heap area of
4. Static variables are loaded on the method area
class loader sub system in the JVM architecture.
of class loader sub system in the JVM
Instance variables are loaded in the objects, so
architecture.
ultimately instance variables are loaded on the
heap area of class loader sub system.
5. Only static variables and methods can be 5. Only instance variables and methods can be
accessed of the call to super() or this(). 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
Instance method
Then these are executed secondly
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)
}
}
Object Object
reference variable reference variable
Srinivas Srinivas
p1 p1
20 20
Copy of reference M M
another
obj Lakxmi Object
We are
storing as 19 Venkat
obj
F 30
p2 M
Laxmi
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?
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
{
private double bal; Inner class
BankAcct(double b)
{
bal = b;
}
void start(double r)
{
//Create an object to inner class One Person class Another 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
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. Interest
6. Inner class features are accessible through outer
class only.
bal
7. Outer class object and inner class objects are
created separately in memory. this&0
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.
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()
{ Programmer 1
return name; P1
}
void setAddress(String address)
{ Programmer 2
this.address= address; P2
} Project
int getAddress() Database
{
return address;
}
void setSal(float sal)
{
this.sal= sal;
}
float getSal()
{
return sal;
}
}
Ex: - //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
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();
ID
//Store data into s
s.setId(10); Name
s.setName(Vijay); S1
s.setAddress(MIG-44, KPHB Colony, Address
Hyderabad);
s.setMarks(77); Marks
//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
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); //super() means calling super class default constructor
i = y;
}
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.
Polymorphism is not applied to overloading. t
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
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
at com.marlabs.vara.MethodOverride.main(MethodOverride.java:31)
Ex: - 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 overriding when he
1. A programmer uses method overloading when
wants to provide different implementation for the
he wants to extend an already available feature.
same feature.
2. A method overloading is code refinement. 2. Method overriding is code replacement.
3. A method overloading doesnt depends on 3. A method overriding depends on return type of a
return type of a method and exception. method and exception.
4. Overlaoding lets you define the same operation 4. Overriding lets you define the same operation in
in different ways for different data. 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 non-
final 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 Non-Citrous
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.
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.
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.
Page 73 of 191
COREJAVA
6. An interface may have variables, which are
6. An abstract class will have instance variables in public static and final by default. In another words,
its concrete sub class. . interfaces can declare only constants, not instance
variables.
7. An abstract class can extend only one another 7. An interface can extends multiple interfaces (or)
class. a class can implements multiple interfaces.
8. Interface methods must not be static. Because
8. An abstract class methods can be declared as
interface methods are abstract, they cannot be
static in its sub class.
marked final, strictfp, or native.
Typesof inheritance:-
1. Singleinheritance:- Producing sub classes from a single super class is called single inheritance.
A A
B C
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.
A B
A B
class A
class A C
class B C D
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
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.
(3)
(1) (2)
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 C
private
public
protected
default
same another
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.
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.
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
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
converts ch into lowercase
Ex: - //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
2. Shunting of coaches to railway engine is an example for stack. 1
Elements
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();
}
}
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
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
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
----------------------------------------------------------------------------------------------------------------
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
----------------------------------------------------------------------
| | |
FileInputStream FilterInputStream ObjectInputStream
|
-----------------------------------------
| |
BufferedInputStream DataInputStream
OutputStream
|
-----------------------------------------------------------------------
| | |
FileOutputStream FilterOutputStream ObjectOutputStream
|
-----------------------------------------
| |
BufferedOutputStream DataOutputStream
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).
DataInputStream FillOutputStrea
m
System.in 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 Ms-
Dos 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
{
ZippingandUnzippingthe file: -
Most repeated bit pattern
0
11111111
1
00000000 Zip
01
10101010
WinZip Software 101
00001111
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.*;
import java.util.zip.*;
dos
class Compress Writing Writing
{ here here
public static void main(String args) File 1 File 2
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
public static void main(String args) File 2 File 3
throws Exception
{ attach fis attach fos
//attach file2 to FileInputStream
FileInputStream fis = new FileInputStream(file2);
//attach file3 to FileOutputStream
FileOutputStream fos = new FileOutputStream(file3);
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
Q) Whenyouwill changesocketnumber?*****
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.
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.
Ex: - //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
ServerSocket ss= new Client
ServerSocket(777); Socket
//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)
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.
Microprocessor
Memory
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
parts of a program simultaneously is called Three
thread based multitasking. Microprocessor
diff.
Using more than one thread is called types
multithreading to perform multiple tasks
simultaneously at a time.
of
Createa thread:- blocks
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;
{
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);
}
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
{
SrtingBuffer sb; 1
producer() 2 Data Provider
{ 3 true
sb = new StringBuffer();
-
}
public void run() -
{ -
synchronized() 10
{
for(int i = 1; i<=10; i++) Consumer
{ Producer
try
{
sb.append(i+:);
sleep(100);
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.
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.
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:
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
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 DelegateDemo() {
// create the GUI objects
Button left = new Button("Left");
Button right = new Button("Right");
Label label = new Label("Center");
public SetText(Label l) {
// the listener needs to know the Label it will act on
label = l;
}
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.
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.
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
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
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.
ActionEvents
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:
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();
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 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();
The code is
import java.awt.*;
import SetColor;
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();
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 MenuColor() {
// the label that will be colored
Label label = new Label("Select color from menu");
color.add(red);
color.add(blue);
color.add(green);
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 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();
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
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
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:
Here is a program to track resize and movement events on the toplevel Frame:
public TrackResize() {
Label label = new Label();
add(label);
pack();
addComponentListener(new Tracker(label));
}
}
Tracker(Label l) {
label = l;
}
public void componentHidden(ComponentEvent e) {
// empty
}
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
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
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
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();
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();
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:
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 ShowKey() {
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 stand-
alone 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.
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().
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
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>
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.
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.
import java.awt.TextField;
import java.awt.List;
import java.awt.Button;
import java.applet.Applet;
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.
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
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
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
}
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).
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 {
}
}
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.
import java.awt.*;
import java.applet.*;
public class TextAreaApplet extends java.applet.Applet {
CheckBox
Medium
Large Pizza Small Pizza
Pizza
Example Source
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.
repaint();
}
}
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.
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();
}
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?
CreateAndShowGUI
Absolutepositioning
Interfaces
Buttonclickdemo
Which button?
Setting a laf
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel" );
This in main() - set laf as first step try .. catch.. because could fail UIManager is in java.lang
Findinginstalledlafs
JFrame.setDefaultLookAndFeelDecorated(true);
.. call JFrame constructor
1.containers
things that hold other things
eg JFRame
2.controls
User I/O widgets
eg JButton
Containers
top level containers - JFrame JApplet JDialog
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
JTextField
Example of JTextField
JTextArea
JScrollPane
JScrollBar
JCheckBox
RadioButton
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
LayoutManagers
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
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);
------------------* * * *-----------------
Viva Questions
Package statement
Import statement
Interface Statements
Class definitions
}
5.What is Branching?
When a program breaks the sequential flow and jumps to another part of the code ,it is called
branching.
..
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
}
public
private
protected
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.
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.
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
What is Java?
Java is an object oriented programming language
What is JVM?
Java Virtual Machine which accepts java byte code and produces result
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
What is abstraction?
Abstraction is the process of identification of essential features of objects
What is hierarchy?
Ordering of classes (or inheritance)
What is inheritance?
Extending an existing class is called inheritance. Extracting the features of super class
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 polymorphism?
Multiple (poly) forms (morphs)
Same instance can respond different manners is called polymorphism
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 keyword?
Java reserved word which should is not used as variable/class-name (e.g.: break, for, if, while
etc)
What is this( )?
Used for calling another constructor of current class
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
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.
What is exception?
Abnormal termination of program is called exception
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
What is an event?
A kind of action