MAIN Java Material
MAIN Java Material
J2SE
(Corporate Training Program)
6 Weeks/45 Days
“PRESENTED BY”
Address : Contact us :
Takeoff group, Website: www.takeoffprojects.com,
Email:[email protected] www.youngmindstechnologies.com
Young Minds Technologies (P), Ltd., Office – 0877- 2261612, 9030333433.
# 303, AVR Complex, Balaji Colony,
1 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
- 517501, Andhra Pradesh. INDIA.
ABOUT US
Takeoff Group is a division of young minds Technology Solutions Pvt Ltd. TAKEOFF
GROUP was established in the year 2007 as an India's leading Corporate Training & academic
projects Development Company as per the industry requirements. Takeoff majorly focuses on
corporate Training, Academic Project Development, Website Development, and placement
guidance. Today, Takeoff is entering a new phase of evolution – changing it from a volume-
driven service provider to value-centric enterprise that turns technology into competitive
advantage for all its Clients across the globe.
CSE
PROJECTS TRAINING
DOMAINS DOMAINS
2 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
3 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Index
Topic Page No
1. Introduction to java 04
2. First java Program 15
3. Naming conventions 18
4. Variables 19
5. Data Types 21
6. Operators 26
7. Control Statements 39
8. Input and Output 58
9. Arrays 68
10. Strings 82
11. StringBuffer And StringBuilder 94
12. OOPS 99
13. Classes and objects 105
14. Methods 115
15. Inheritance 125
16. Polymorphism 135
17. Type casting 144
18. Abstract classes 151
19. Interfaces 158
20. Packages 165
21. Exception Handling 174
22. The Wrapper Classes 189
23. The Collection Framework 204
24. Streams and Files 236
25. Threads 248
26. Networking 267
27. Graphics Programming Using AWT 275
28. Applets 309
4 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Introduction to java
Before starting to learn java, let us plungeinto its history and see how the language
originated. In 1990, Sun Microsystems Inc. (Us) has conceived a project to develop software for
consumer electronic devices that could be controlled by a remote(set-top boxes,television etc).
This project was called stealth project but later its name was changed to Green project.
In Jan of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and several
others met in Aspen, Colorado to discussthis project.
James Gosling has to identify the proper programming language for this project. Gosling
thought C and C++ could be used to develop the project. But the problem he faced with them is
that they were system dependent languages and hence could not be used on various processors
which the electronics devices might use.
WHY THE NAME IS JAVA?The team gathered to choose a new name. The suggested
words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to
spell and fun to say.
James Gosling and his team members were consuming a lot of coffee while developing
this language. They felt that they were able to develop a better language because of the good
quality of coffee they consumed. So the coffee had its own role in developing this language and
good quality of coffee was exported to the entire world from a place called 'JAVA ISLAND'.
Hence they fixed the name of the place for the language as JAVA. And the symbol for JAVA
Language is coffee cup and saucer.
5 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
By September of 1994, Naughton and Jonathan Payne started writing WebRunner-a Java
based Web browser, which was later renamed as HotJava. By October 1994, HotJava was stable
and was demonstrated to Sun executives. HotJava was the first browser, having the capabilities
of executing applets, which are programs designed to run dynamically on Internet. This time,
Java's potential in the context of the World Wide Web was recognized.
Sun formally announced Java and HotJava at SunWorld conference in 1995. Soon after,
Netscape Inc. announced that it would incorporate Java support in its browser Netscape
Navigator. Later, Microsoft also announced that they would support Java in their Internet
Explorer Web browser. JDK 1.0 released in January 23, 1996. The recently released version of
java is JAVA_SE8.
Features of java:
There are many features of java. They are also known as java buzzwords. They are:
1. Simple
2. Object-Oriented
3. Distributed
4. Robust
5. Secured
6. platform independent
7. Portable
8. Interpreted
9. High Performance
10. Multithreaded
11. Scalability
12. Dynamic
1) Simple:Java is simple programming language. Rather than saying that this is the feature
of java, we can say that this is the design aim of java. First of all the java soft people have
6 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
been omitted the difficult concepts of c and c++, like pointers and operator overloading,
etc. And the syntax of java is quite similar to the syntax of c and c++ languages.
2) Object-Oriented:Java is an object oriented programming language. This means java
programs use objects and classes. An object is anything that really exists in the world and
can be distinguished from others. Everything that we see physically will come into this
definition, for example, every human being, a book, a tree, and so on.
A group of objects exhibiting same behavior (properties + actions) will come under
the same group called a class.
Object-oriented programming(OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
4) Robust:Robust means strong. Java programs are strong and they don’t crash easily like
C/C++.There are two reasons for this. Firstly, java has got excellent inbuilt exception
handling feature. Another reason is java has strong memory management mechanism.
Class file
0 0 0
1 1 1
0 0 0
7) Portable: If a program yields the same result on every machine, then that program is
called portable. Java programs are portable. This is the result of system independence
nature.
8) Interpreted:Java programs are compiled to generate the byte code. This byte code can be
downloaded and interpreted by the interpreter in JVM. If we take any other language,
either an interpreter or a compiler is used to execute the programs. But in Java, we use
both compiler and interpreter for the execution.
9) High performance:The problem with interpreter inside the JVM is that it is slow.
Because of this, Java programs used to run slow. To overcome this problem, along with
the interpreter, Java soft people have introduced JIT(Just In Time) compiler, which
8 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
enhances the speed of execution. So now in JVM, both Interpreter and JIT compiler
work together to run the program.
12) Dynamic:Before the development of java, only static text used to be displayed in the
browser. But James Gosling demonstrated an animated atomic molecule structure. This
animation was done using applet program, which are dynamically interacting programs
on Internet.
9 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q).which part of JVM will allocate the memory for a java program?
Answer:Class loader sub system of JVM will allocate the necessary memory needed by the
java program.
Q).which algorithm is used by garbage collector to remove the unused variables or objects
from memory?
Answer:Garbage collector uses many algorithms but the most commonly used algorithm is
mark & sweep.
Q).what is the first browser, having the capabilities of executing the applets?
10 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Answer:HotJava is the first browser, having the capabilities of executing the applets.
Q). ………….. contains predefined classes and interfaces for developing Java programs.
A. Java language specification
B. Java API
C. Java JDK
D. Java IDE
Answer:B
Q)………….. is a technical definition of the language that includes the syntax and semantics of
the Java programming language.
A. Java language specification
B. Java API
C. Java JDK
D. Java IDE
Answer:A
11 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Class loader
Class file
sub system
Execution engine
Operating system
First of all, the.java program is converted into a .classfile consisting of byte code
instructions by the java compiler. Remember, this java compiler is outside the JVM. Now this
.classfile is given to the JVM.
12 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Class loader subsystem:The class loader subsystem loads the .class file into memory. Then it
verifies all byte code instructions whether all byte code instructions are proper or not. If it finds
any instruction suspicious, the execution is rejected immediately.
Run time data areas:If thebyte instructions are proper, then it allocates necessary memory to
execute the program. This memory is divided into 5 parts, called run time data areas, which
contain the data and results while running the program. These areas as follows:
1) Method area: Method area is the memory block, which stores the class code, code of the
variables, and code of the methods in the java program.
2) Heap:This is the area where objects are created. Whenever JVM loads a class, a method
and a heap area are immediately created in it.
3) Java Stacks:Method code is stored on method area. But while running a method, it needs
some more memory to store the data and results. This memory is allotted on Java stacks.
So, Java Stacks are memory areas where java methods are executed. While executing
methods, a separate frame will be created in the java stack, where the method is executed.
JVM uses aseparate thread to execute each machine.
4) PC (Program Counter) registers:These are the registers (memory areas), which contain
memory address of the instructions of the methods. If there are 3 methods, 3PC registers
will be used to track the instructions of the methods.
5) Native method stacks:Java methods are executed on java stacks. Similarly, native
methods are executed on Native method stacks. To execute the native methods, generally
native method libraries (for example C/C++ header files) are required. These header files
are located and connected to Jvm by a program, called Native method interface.
Execution engine:Execution engine contains Interpreter and JIT compiler, which are responsible
for converting the byte code instructions into machine code so that the processor will execute
them. Most of the JVM implementations use both the interpreter and JIT compiler
simultaneously to convert the bytecode. This technique is also called adaptive optimizer.
Generally, any language (like c/c++, FORTRAN, COBOL, etc.) will use either an interpreter or a
compiler to translate the source code into a machine code. But in JVM, we got interpreter and
JIT compiler both working at the same time on byte code to translate it into machine code.
13 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
C++ is also an object-oriented programming language, just like Java. But there are some
important feature-wise differences, between c++ and Java.
C++ Java
C++ is not a purely object-oriented Java is purely an object-oriented programming
programming Language, since it is possible language, since it is not possible to write a Java
to write C++ programs without using class program without using at least one class.
or an object.
Pointers are available in C++. We cannot create and use pointers in java.
Allotting memory and deallocating Allocation and deallocation of memory will be
memory is the responsibility of the taken care by JVM.
programmer.
C++ has goto statement. Java does not have goto statement.
Automatic casting is available in C++. In some cases, implicit casting is available. But it
is advisable that the programmer should use
casting wherever required.
Multiple inheritance feature is available in No multiple inheritance in Java, But there are
C++. means to achieve it.
Operator overloading is available in C++. It is not available in Java.
#define, typedef and header files are #define, typedef and header files are not available
available in C++. in Java, but there are means to achieve them.
There are 3 access specifiers in C++; Java supports 4 access specifiers:
private, private,
public, and public,
protected protected, and
default
There are constructors and destructors in Only constructors are there in Java. No destructors
C++. are available in this language.
14 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q).……… is the memory block which stores class code, code of variable and code of methods
in the java program.
Answer:Method area.
Q).……………. is the area in run time data areas where objects are created.
Answer:Heap.
Q). ………….. Are the memory areas where java methods are executed.
Answer:Java Stacks.
Q) If there are N methods, how many PC registers are used to track the instructions of the
method?
Answer:Jvm allocates N registers to track N instructions.
15 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
install the JDK if you haven`t installed it, for this download the JDK and install it.
set path of the jdk/bin directory.
create the java program
compile and run the java program
import java.lang.*;
class Simple
{
Public static void main (String args [])
{
System.out.println ("Hello Java");
}
}
Output:Hello Java
import java.lang.*;Here, * means all the classes and interfaces of the package, i.e. java.lang, are
imported into our program. In import statement, the package name that we have written acts like
a reference to the JVM to search for the classes there. JVM will not copy any code from the
classes or packages.
16 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
class:keyword is used to declare a class in java.
static:is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require creating object to invoke the main
method. So it saves memory.
void:is the return type of the method, it means it doesn't return any value.
17 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) What if the static modifier is removed from the signature of the main method?
Answer:Program compiles. But at runtime throws an error "NoSuchMethodError".
18 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
All the classes, interfaces, packages, methods and fields of java programming language
are given according to java naming convention.
Now, let us see some of the major naming conventions to be followed in Java.
Name Convention
class name Should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
interface name Should start with uppercase letter and be an adjective e.g. Runnable,
Remote, ActionListener etc.
Method name Should start with lowercase letter and be a verb e.g. actionPerformed(),
main(), print(), println() etc.
variable name Should start with lowercase letter e.g. firstName, orderNumber etc.
package name Should be in lowercase letter e.g. java, lang, sql, util etc.
constants name Should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
etc.
Note:All keywords should be written by using all small letters like public, static, void….
Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always
e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.
19 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Variables in java
A variable provides us with named storage that our programs can manipulate. Each
variable in java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
You must declare all variables before they can be used. The basic form of a variable
declaration is shown here:
Example: int a;
int a=10,b=20;
Here data type is one of java's data types and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated list.
1) Local variables:
Instance variables are declared in a class, but outside a method, constructor or any
block.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
20 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be accessed directly by calling the variable name inside the
class. However within static methods and different class should be called using the
fully qualified name:ObjectReference.VariableName.
3) Class/static variables:
Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
Static variables can be accessed by calling it with the class name as
follows:ClassName.VariableName.
When declaring class variables as public static final, then variables names (constants)
are all in upper case. If the static variables are not public and final the naming syntax
is the same as instance and local variables.
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
} //end of class
21 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
Primitive data types:There are eight primitive data types supported by Java. Primitive data
types are predefined by the language and named by a keyword. Let us now look into detail about
the eight primitive data types.
22 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Boolean datatype:Boolean data types represent any of the two values, true or false. JVM uses 1
bit to represent a Booleanvalue internally.
We should not enclose the boolean value true(or false) in any quotation marks.
Char datatype:In Java, the data type used to store characters is char. Character is 16 bits wide in
Java. Java uses Unicode to represent characters.Unicode is a computer industry standard for
representing text related data. This includes alphabets, symbols ($, &, *, #, @, !, etc.), and
special figures such as ¢, £, ¥, etc.Java support lot of Unicode symbols from many more human
languages for this purpose, it requires 16 bits.The range of a char is 0 to 65,536.
Integral datatypes:These datatypes represent integer numbers, i.e. numbers without any
fractional parts or decimal points. For example, 125, -225678, 0, 1022, etc. The integer datatypes
are again sub devided into byte, short, int, and long types.
Integer datatype:Int data type is a 32-bit signed two's complement integer.It is one of the most
commonly used data types in Java.Int is generally used as the default data type for integral
values unless there is a concern about memory.
Byte datatype: Byte data type is an 8-bit signed two's complement integer.byte is smallest Java
integer type.byte is mostly used when dealing with raw data like reading a binary file.Byte data
type is used to save space in large arrays, mainly in place of integers, since a byte is four times
smaller than an int.
Long datatype:Long data type is a 64-bit signed two's complement integerand is useful for
those occasions where an int type is not large enough to hold the desired value. The range of a
long is quite large. This makes it useful when big, whole numbers are needed. The default value
of long datatype is ‘0L’.
Floating point datatypes: These datatypes are useful to represent numbers with decimal
point. For Example, 3.14, 0.0012, -123.11, etc. are called floating point numbers. These are again
classified as float (Single precision floating point number) and double (Double precision floating
point number).
Float datatype: In programming, any decimal or fractional value is called a ‘float’. If there is a
decimal after the number, it will be classified as a float. In Java, a float is made up of 32-bits
IEEE floating points*.If we have to assign float value then we must use ‘f’ or ‘F’ literal to
specify that current value is “Float”.
Double datatype: Double is a data type that is twice the size of a float. I.e. it is made up of 64-
bit IEEE floating points.In Java any value declared with decimal point is by default of type
double.Default value is 0.0d.Double precision is actually faster than single precision on some
modern processors that have been optimized for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
24 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Non primitive datatypes:The non-primitive data types in Java are objects and arrays. These
non-primitive types are often called "reference types" because they are handled "by reference"--
in other words, the address of the object or array is stored in a variable, passed to methods, and
so on.
int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000’
String (or any object) null
boolean false
Answer:unicode system is an encoding standard that provides a unique number for every
character, no matter what the platform, program, or language is. Unicode uses 2 bytes to
represent a single character.
Answer:float can represent up to 7 digits accurately after decimal point, whereas double can
represent up to 15 digits accurately after decimal point.
25 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) What happens if you don’t initialize an instance variable of any of the primitive types in
Java?
Answer:Java by default initializes it to the default value for that primitive type. Thus an int
will be initialized to 0, a boolean will be initialized to false.
Q) Why does char datatype in java has 2 bytes of memory where as in C it is only 1 byte?
Answer:Because C follows only ASCII format where as java follows UNICode format which in
turn represents 18 languages. So it takes more memory.
26 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Operators in java
An operator is a symbol or keyword that tells the computer to perform certain
mathematical or logical calculations. An Operator acts on some variables, called Operandsto get
the desired result.
Operator
a + b
Operands
There are following type of operators to perform different types of operations in Java.
1. Arithmetic operators
2. Increment/Decrement operators
3. Assignment operator
4. Relational operators
5. Logical operators
6. Bitwise operators
7. Ternary or Conditional operators
8. Member operator
9. New operator
10. Cast operator
Arithmetic operators:
These Operators are used to perform fundamental arithmetic operations like addition,
subtraction, etc. There are 5 arithmetic operators in java. Since these operators act on two
operands at a time, these are called binary operators.
27 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The following table displays the functioning of these operators, here we are assuming the
value of a as 13 and b as 5.
Addition operator (+) is also used to join two strings, as shown in the following code
snippet:
String s1=”wel”;
String s2=”come”;
Now, we get welcome in s3. In this case, + is called String concatenation operator.
Increment/Decrement operators:
28 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Increment operator:
Writing ++ before a variable is called pre incrementation and writing ++ after a variable
is called post incrementation. In pre incrementation, incrementation is done first and any other
operation is done next. In post incrementation, all the other operations are done first and
incrementation is done only at the end.
Output: Output:
1 1
2 1
2 2
Decrement operator:
Writing – before a variable is called pre-decrementation and writing – after the variable is
called post-decrementation. Like the incrementation operator, here also the same rules apply.
Pre-decrementation is done immediately then and there itself and post-decrementation is done
after all the other operations are carried out.
Assignment operator:
Assignment operator is used to store some value into a variable. It is used in 3 ways:
29 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Note: we cannot use a literal or constant value at the left side of the = operator.
For example:
15=x; // invalid
Compound assignment:
Some time we need to modify same variable value and reassigned it to same reference
variable. In such cases, we can eliminate repetition of the variable and use compound assignment
operator or shortcut notation.
class Assign
{
public static void main(String[] args)
{
int tot=0;
for(int i=1;i<=10;i++)
{
tot+=i;
}
System.out.println("total="+tot);
}
}
Output:
Total=55
30 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Relational Operators:
Relational operator compares two values and determines the relationship between
them.Relational Operators are Binary Operators.Relational Operators returns “Boolean” value
.i.e. it will return true or false.Most of the relational operators are used in “If statement” and
inside looping statement in order to check truthness or falseness of condition.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
class Relational
{
public static void main(String[] args)
{
int a=10,b=5;
if((a-b)==0)
{
System.out.println("two numbers are equal");
}
else
{
System.out.println("two numbers are not equal");
}
}
}
Output:
Two numbers are not equal
Logical operators:
31 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Bit-Wise operators:
Bitwise operators are used to perform operations at binary level. Decimal values are
converted into binary values(contains only 0s and 1s) and these operators are used for testing the
bits, or shifting them right or left. Before going for bitwise operators we need to know how to
convert decimal values into bits.
Perform LCM on decimal number with respect to 2. The remainder values are stored in
the reverse order which gives binary equivalent for that decimal. As shown in the example
below:
32 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Remainder
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive – OR
<< Left Shift
>> Right Shift
~ Complement
In order to perform operations using Bitwise AND, OR, Exclusive – OR. We need to
follow the truth table below:
Consider x=40 and Y=60, the binary forms of these values are:
33 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Now we got our output in terms of bits. How to convert bits into decimal again is shown
below:
Binary: 01111000
Decimal:0*27 +1*26 +1*25 +1*24 +1*23 +0*22 +0*21 +0*20
=0 + 64 + 32 + 16 + 8 + 0 + 0 + 0
= 120
X<<1 means that the bits will be left shifted by one place, if we use x<<2 then that means
the bits are left shifted by 2 places.
Similarly X>>1 means that the bits will be right shifted by one place, if we use x>>2 then
that means the bits are right shifted by 2 places.
X =00101000 X =00101000
X << 1 = 01010000 X >> 1 = 00010100
= 80 = 20
class Bits
{
public static void main(String[] args)
{
int x=10,y=11;
System.out.println("x&y="+(x&y));
System.out.println("x|y="+(x|y));
System.out.println("x^y="+(x^y));
System.out.println("x<<2="+(x<<2));
System.out.println("x>>2="+(x>>2));
}
}
Output:
x&y=10
x|y=11
x^y=1
x<<2=40
x>>2=2
34 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
This operator is called ternary because it acts on 3 variables. The other name for this
operator is conditional operator, since it represents a conditional statement. Two symbols are
used for this operator ? and :
This means that first of all, expression1 is evaluated. If it is true, then expression2 value
is stored into the variable. If expression1 is false, then expression3 value is stored into the
variable. It means: if(expression1 is true)
variable = expression2;
else
variable =expression3;
Example:
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a
common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using
the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
35 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
class Cond
{
public static void main(String[] args)
{
int x=1;
int y=(x==1? 2: 0);
System.out.println("x value is:"+ x);
System.out.println("y value is:"+ y);
}
}
Output:
X value is: 1
Y value is: 2
Member operator:
Member operator is also called dot operator since its symbol is a . (dot or period), this
operator tells about member of a package or a class, it is used in three ways:
1. We know a package contains classes. We can use . operator to refer to the class of a
package.
Syntax: packagename.classname;
Example:java.io.BufferedReader // BufferedReader is a class java.io package
2. We know that each class contains variables or methods. To refer to the variables of a
class, we can use this operator.
Syntax: classname.variablename; (or)
Objectname.variablename;
3. We know that a class contains methods. Using dot operator, we can refer to the
methods of a class.
36 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
new operator:
new operator is often used to create objects to classes. We know that objects are created
on heap memory by JVM, dynamically (at runtime).
Cast operator:
Cast operator is used to convert one datatype into another datatype. This operator can be
used by writing datatype inside simple braces,
Priority of operators:
When several operators are used in a statement, it is important to know which operator
will execute first and which will come next.Some operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition operator:
Associativity: when there is more than one operator with same precedence
[priority]then we consider associativity, which indicated the order in which the expression has
to beevaluated. It may be either from Left to Right or Right to Left.
For example, x = 5 + 4 * 3; here x is assigned 17, not 27 because operator * has higher
precedence than +, so it first gets multiplied with 4*3 and then adds into 5.
37 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
38 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) Which Java operator is right associative?
Answer:The = operator is right associative.
Q) What are order of precedence and associativity, and how are they used?
Answer:Order of precedence determines the order in which operators are evaluated in
expressions. Associativity determines whether an expression is evaluated left-to-right or
right-to-left.
Q) What is the difference between the prefix and postfix forms of the ++ operator?
Answer:The prefix form performs the increment operation and returns the value of the
increment operation. The postfix form returns the current value all of the expression and
then performs the increment operation on that value.
Q)What is the difference between the Boolean & operator and the && operator?
Answer:If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression involving the
&& operator is evaluated, the first operand is evaluated. If the first operand returns a value
of true then the second operand is evaluated. The && operator is then applied to the first
and second operands. If the first operand evaluates to false, the evaluation of the second
operand is skipped.
39 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
40 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
These statements change the flow of execution depending on a given logical condition.
Used to execute or skip some set of instructions based on given condition.
1. The if – else Statement:
The if-else statement is the most basic of all the control flow statements. Here we are
having two blocks: if block and else block. It is clearly observed that if block is executed only if
the condition following if is true. If the condition is false else block is executed. Hence it is
called as “two – way” control statement. In if – else statement either true block or false block
will be executed but not both.
Syntax:
if(Condition)
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}
Rest of the Program Statements-X;
Flowchart:
41 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:Write a program to print whether the given num is odd or even.
public class Demo
{
public static void main(String args[])
{
int a=21;
if(a%2==0)
{
System.out.println("Given number is Even");
}
else{
System.out.println("Given number is Odd");
}
}
}
Output:
Given number is Odd
This is another way of multiway decision. A multipath decision is a chain of if‘s in which
the statement associated with each else is an if. Hence it forms a ladder called else–if ladder.
Syntax:
if (Test Condition -1)
{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
:
:
else if ( Test Condition –n)
{
Statement –n;
}
else
{
default statement;
}
Rest of the Program Statements-X;
42 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Flow chart:
Entry
False
Condition1
False
Condition2
True
Condition3 False
Statement1 True
Condition_n
Statement2 True
True False
Statement3
Statement-n
Default Statement
Statement-x
43 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
else if((b>a) && (b>c))
{
System.out.println("Highest Number is:"+b);
}
else
{
System.out.println("Highest Number is:"+c);
}
}
}
Output:
Highest Number is: 30
3. The switch:
Switch is another conditional control statement used to select one option from several options
based on given expression value; this is an alternative to theelse-if ladder. Switch Case Syntax is
similar to – C/C++ switch.
Syntax:
switch: The switch keyword is followed by a parenthesized expression (the expression must be
either int or char type), which is tested for equality with the following cases. There is no bound
to the number of cases in a switch statement.
44 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
case:The case keyword is followed by the value to be compared to and a colon. Its value is of the
same data type as the expression in the switch. The case which is equal to the value of the
expression is executed.
default: If no case value matches the switch expression value, execution continues at
the default clause. This is the equivalent of the "else" for the switch statement. It is
conventionally written after the last case, and typically isn’t followed by break because execution
just continues out of theswitch. However, it would be better to use a break keyword
to default case, too. If no case matched and there is no default clause, execution continues after
the end of the switch statement.
break: The break statement causes execution to exit the switch statement. If there is no break,
execution flows through into the next case, but generally, this way is not preferred.
Switch allows you to choose a block of statements to run from a selection of code, based
on the return value of an expression.
Flow chart:
Entry
Expression
Unmatch
Unmatch
Match Statement-n break
case-n
Unmatch
Match
default Statement-s break
exit
45 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Example:
int exp = 2;
Switch (exp)
{
Case 0: System.out.println(“Hello, krish”);
break;
Case 1: System.out.println(“Hello, Radha”);
break;
Case 2: System.out.println(“Hello, Rama”);
break;
default: System.out.println(“No data found”);
break;
}
Program:Write a program to display the traffic control signal lights using switch.
46 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Loop:A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
In other words it iterates a code or group of code many times.
Why use loops: Suppose you want to execute some code/s 10 times. You can perform it by
writing that code/s only one time and repeat the execution 10 times using loop. For example:
Suppose that you have to print table of 2 then you need to write 10 lines of code, by using loop
statements you can do it by 2 or 3 lines of code only.
1. for Loop:
The for loop works well where the number of iterations of the loop is known before the
loop is entered. The head of the loop consists of three parts separated by semicolons (;).
a. The first part is the one which runs before the loop is entered. This is usually called “the
initialization” of the loop variable. This executes only once.
b. The second part is a “test”.The test condition is a relational expression that determines
the number of iterations desired or it determines when to exit from the loop.
For loop continues to execute as long as conditional test is satisfied.
When the condition becomes false the control of the program exits from the body
of for loop and executes next statements after the body of the loop.
c. The third part is a statement to be run every time the loop body is completed. This is
usually an “increment or decrement” of the loop counter.
This decides how to make changes in the loop.
47 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Initialization
False
Condition
True
Statements
Incr/decr
Program:Print the first five numbers starting from one together with their squares.
Output:
Number=1 Square=1
Number=2 Square=4
Number =3 Square=9
Number =4 Square=16
Number =5 Square=25
48 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Nested for Loop:
We can also use loop within loops. i.e. one for statement within another for statement is
allowed in java. In nested for loops one or more for statements are included in the body of the
loop.
Syntax:
for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
Program:Example for nested for loops
public class Fun {
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output: *
**
***
****
*****
2. while Loop:
The while is an entry-controlled loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed.
The execution process is repeated until the test condition becomes false and thecontrol is
transferred out of the loop.
On exit, the program continues with the statement immediately after the body of the loop.
The body of the loop may have one or more statements.
The braces are needed only if the body contains two or more statements. It's a good
practice to use braces even if the body has only one statement.
49 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Syntax:
Initialization Expression;
while ( Test Condition)
{
Body of the loop
Updation Expression
}
Flowchart: Entry
Condition False
True
statements
Note:If you pass 1 as a expression in while loop, it will run infinite number of times.
Syntax:
while(1)
{
//statements
}
50 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
3. do-while Loop:
The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once.
Entry
Flow chart:
statements
True
Condition
False
exit
class simple
{
public static void main(String args[])
{
int num = 0;
do
{
num = num + 2;
System.out.println(num);
}while(num<20);
}
}
Output: 2
4
6
8
10
12
14
16
18
20
A break statement terminates the execution of the loop and the control is transferred to the
statement immediately following the loop. i.e., the break statement is used to terminate loops or
to exit from a switch.
It can be used within for, while, do-while, or switch statement.
The break statement is written simply as break;
In case of inner loops, it terminates the control of inner loop only.
Syntax:
Jump-statement;
break;
The jump statement in java can be while loop, do while loop, for loop or switch case.
52 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Flow chart:
Entry
False
Output:
1234
The continue statement is used to bypass the remainder of the current pass through a
loop.
The loop does not terminate when a continue statement is encountered. Instead, the
remaining loop statements are skipped and the computation proceeds directly to the next
pass through the loop.
The continue statement can be included within a while, do-while, for statement.
It is simply written as “continue”. The continue statement tells the compiler “Skip the
following Statements and continue with the next Iteration”.
In “while” and “do” loops continue causes the control to go directly to the test –condition
and then to continue the iteration process. In case of “for” loop, the updation section of
the loop is executed before test-condition, is evaluated.
53 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Syntax:
Jump-statement;
Continue;
Flowchart: Entry
Condition Continue
with in loop True
Output:
12346789
54 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The return statement terminates the execution of a method. A method returns to the code that
invoked it when it
completes all the statements in the method,
reaches a return statement, or
throws an exception.
Syntax:
Statement(s);
return expression;
55 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The method contains a group of statements and performs a task or processing. Methods can
accept the data from outside for their processing and they can also return the results. A method is
executed when called from another method. The method that is executed in java by JVM is
‘main()’ method and hence to execute any method, we should call it from main().
Any method declared ‘void’ doesn`t return a value. It doesn’t need to contain a return
statement but it may do so. In such a case, a return statement can be used to branch out of a
control flow block and exit the method and is simply used like this:
return;
program:write a program to demonstrate return statement in main()
publicclass Return
{
publicstaticvoid main(String args[])
{
int x=1;
System.out.println("Before return");
if(x==1) return;
System.out.println("After return");
}
}
Output:
Before return
56 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
If you try to return a value from a method that is declared void, you will get a compiler
error. If we want to come out of a called method which is declared as void, instead of using
return;, we can also use,
System.exit(0);
Here, exit(0) is a static method in the class, named ‘System’. So it can be called
System.exit(0). While calling this method, programmers need to pass int values (generally 0 or 1
is passed).
Important Interview Questions:
Q) What are control statements?
Answer:Control statements are the statements which alter the flow of execution and provide
better control to the programmer on the flow of execution. They are useful to write better
and complex programs.
57 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). The do-while loop repeats a set of code atleast once before the condition is tested?
a) True
b) False
Answer:a
58 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Stream:
A stream is required to accept input from the keyboard. A Stream represents flow of
data.A water-pipe carries water from one place to another place. Similarly, a stream carries data
from one place to another place.
Input streams (which receive or read data coming from some other place).
Output streams (which send or write data to some other place).
The java.io package contains all the classes required for input and output operations.
Keyboard is represented by a field, called “in” in System class. When we write System.in, we
are representing a standard input device, i.e. keyboard, by default.
System class:
System class has three fields. All these three fields represent some type or stream.
59 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To accept data from the keyboard, i.e. System.in, we need to follow the steps below:
i. Connect the keyboard to an input stream object. Here, we can use
“InputStreamReader” that can read data from the keyboard.
The above two statements can be combined and re-written in a single statement as:
60 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Now, we can read the data coming from the keyboard using methods available in
BufferedReader:
Now, follow these steps in order to accept a single character from the keyboard.
Here, the read() method reads a single character from the keyboard but it returns its
ASCII number, which is an integer. Since, this integer number cannot be stored into character
type variable ch, we should convert it into char type by writing (char) before the method as:
Here, “int” data type is converted into “char” type. Converting one data type into another
data type is called type casting or simply casting. Here (char) is the cast operator.
If read() method could not accept a character due to some reason, then it gives rise to a
runtime error which called by the name IOException. So wherever we use read () method we
need to throw IOException without handling it by writing:“throws IOException” at the side of
the method where read() is used.
Program: write a java program to accept a single character from the keyboard.
import java.io.*;
public class Return
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Gender (F/M):");
char gen=(char)br.read();
System.out.println("you entered: "+gen);
}
}
Output:Enter Gender (F/M): M
you entered: M
61 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, readLine() method accepts a string from the keyboard and returns the string into str.
In this case casting is not needed since readLine() is taking a string and returning the same data
type. But this method can give rise to the runtime error: IOException, which can be thrown out
without handling by using the statement:throws IOException.
import java.io.*;
publicclass Accept
{
publicstaticvoid main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a name:");
String name=br.readLine();
System.out.println("You entered:"+name);
}
}
Output:Enter a name:sai
You entered:sai
First, we should accept the integer number from the keyboard as a string, using
readLine() as:
String str = br.readLine ();
Now, this str can be type casted into other types as shown below:
Type of value to get Syntax for casting
Int int n=Integer.parseInt(str);
Float float n = Float.parseFloat(str);
Byte byte n = Byte.parseByte(str);
Short short n = Short.parseShort(str);
Long long n = Long.parseLomg(str);
Boolean boolean n = Boolean.parseBoolean(str);
62 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Instead of writing two statements, we can write only one as shown below:
int n = Integer.parseInt(br.readLine());
Similarly, we can use the same for remaining types also.
In the above program after entering gender as ‘M’, the user will press enter button, which
releases ‘\n’ code. The read() method reads only the character ‘M’ and stores it into ‘gen’
variable, the readLine() method reads ‘\n’ and stores it into name variable this is the reason i/p
for name is not accepted.
char gen=br.readLine().charAt(0);
63 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:Accepting and displaying employee details.---version 2
import java.io.*;
publicclass Employee
{
publicstaticvoid main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter ID: ");
int id = Integer.parseInt(br.readLine());
System.out.println("enter gender: ");
char c = (char) br.read();
br.skip(2);
// (or)
//char c=br.readLine().charAt(0);
System.out.println("Enter name:");
String name = br.readLine();
System.out.println("id: " + id);
System.out.println("gender: " + c);
System.out.println("name: " + name);
}
}
Output:
enter ID: 99
enter gender: M
Enter name: sai
id: 99
gender: M
name: sai
Program:To accept a year number from the keyboard and test if it is leap or not.
import java.io.*;
publicclass Leap
{
publicstaticvoid main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter year no:");
int year=Integer.parseInt(br.readLine());
if((year % 100==0) && (year % 400==0))
System.out.println("It is leap year");
elseif((year % 100 !=0) && (year % 4==0))
System.out.println("It is leap year");
else
System.out.println("It is not leap year");
}
64 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2. Scanner:
Scanner class belongs to “java.util”, this class is useful to accept different types of input in
the same line.
1) Creating Scanner class object and connecting to the keyboard.
Scanner sc=new Scanner(System.in);
2) Now all the input values are stored in the Scanner object. Retrieve those values using the
following methods.
Method Description
public String next() it returns the next token from the scanner.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double nextDouble() it scans the next token as a double value.
Now, if the user has given integer value from the keyboard, it is stored into the Scanner
object (sc) as a token. To retrieve that token, we can us the method:sc.nextInt();
To read character value using scanner class, we can use: sc.next().charAt(0);
Program:Write a program to read different types of data separated by space, from the
keyboard using Scanner class.
import java.util.*;
public class Fun {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter ID, name, sal: ");
int id=sc.nextInt();
String name=sc.next();
float sal=sc.nextFloat();
System.out.println("ID: "+id+”\n Name: ”+name+”\n Salary: ”+sal);
}
}
Output:
Enter ID, name, sal: 99 Krish 20000.00
ID: 99
Name: Krish
Salary: 20000.0
65 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
1. System.out.print()
2. System.out.println()
3. System.out.printf()
Both of the statements 1 and 2 are used to display the output on the screen. The difference
between these two is that print() method keeps cursor in the same line after displaying the output
and println() method throws cursor to the next line after displaying the output.
To format and display the output, printf() method is available in PrintStream class. This
method works similar to printf() in C. we know that System.out returns printStream class object,
so to call the printf() method, we can use:
System.out.printf(“formatstring”,variables_list);
%s – String
%c – char
%d – decimal integer
%f – floating number
%o – octal number
%n – newline character
%b, %B – boolean value
%x, %X – hexadecimal number
Example:
float sal=10000.00;
System.out.printf(“Salary: %f”, sal);
Here, the string Salary: will be displayed as it is in the output. After this, we have %f,
which represents a format character to display a float value, i.e. sal value. So the output will be:
Salary= 10000.00
66 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
67 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) What is a Stream?
Answer:A stream is required to accept input from the keyboard. A stream represents flow of
data from one place to another place.
Q). In how many ways can you read data from keyboard?
Answer:In java there are 2 ways to read data from keyboard.
1. BufferedReader class.
2. Scanner class.
Q). which class breaks the input into tokens using a delimiter which is whitespace bydefault,
It provides many methods to read and parse various primitive values?
Answer:Scanner class is used to break the input into tokens, which by defaultly takes space
as a delimiter.
Q). What is the use of Scanner class, When was it introduced in Java?
Answer:Scanner class introduced in Java 1.5 for reading Data Stream from the input device.
Q). what is the Scanner class method to read a character from the keyboard?
Answer:To read character value from the keyboard by using sc.next.charAt(0) method.
Q). what is the BufferedReader class method to read a character from the keyboard?
Answer:To read character value from the keyboard by using br.read() or
br.readLine().charAt(0) method.
68 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Arrays:
Suppose a class contains 50 students, and we want to store their roll numbers, we need 50
separate variables for storing the roll numbers, as shown here:
int number1;
int number2;
int number3;
.
.
int number49;
int number50;
Now, to store roll numbers into these variables, we need another 50 statements. We can represent
these 50 roll numbers by a single variable. Such variable is called an “array”.
Definition:
The Collection of homogeneous data elements is called an Array. (Or) An Array represents
group of elements of same data type.
That means we can store a group of int values or a group of float values or a group of
strings in the array. But we can’t store combination of int values and float values.
Array in java is index based, first element of the array is stored at 0thindex.
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
69 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Types of Arrays:
Case 1:We can declare a one dimensional array and can directly store elements at the time of
declaration only as below:
Here,
a. int represents that the elements stored is of type integer,
b. marks[] is the name given to that array,
c. a pair of square braces [] (called subscripts) represents it is a single dimensional
array,
d. actual elements are mentioned inside the curly { and } braces and
e. the elements are separated by commas.
Now, JVM creates 5 blocks of memory as they are 5 elements being stored in the array.
These blocks of memory can be individually referred to as marks[0], marks[1], marks[2],…
marks[4]. Here 0,1,2,…4 is called “index” (element position) of an array. 1D array can have
only one index. In general, any element can be shown by writing marks[i] where i=0,1,2,…4.
70 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
50 60 55 67 70
marks[i]
Now, we want to access the elements of an array by using a for loop as shown below:
Program 1:Write a program to create a 1D array and display its elements one by one by
using a loop.
Output:
50
60
75
66
87
Case 2:Another way of creating a one dimensional array is by declaring the array first and
then allotting memory for it by using “new” operator.
Syntax: int marks[];
marks = new int[5];
These two statements can also be written by combining them into a single statement as:
71 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Syntax: int marks[] = new int[5];
Here, we should understand that JVM allots memory for storing 5 integer elements
into the array. But there are no actual elements stored in the array so far. To store the
elements into the array, we can use statements like these in the program:
marks[0] = 50;
marks[1] = 60;
…
marks[4] = 70;
Instead we can pass the values from the keyboard to the array by using a loop, as given here:
Program 2:Write a program to create a 1D array and read the values from the
keyboard and display its elements one by one by using a loop.
import java.util.*;
public class Array
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[5];
for(int j=0;j<5;j++)
{
System.out.println("Enter element num"+(j+1)+": ");
arr[j] = sc.nextInt();
}
System.out.println("Displaying:");
for(int i=0;i<5;i++)
{
System.out.print(arr[i]+”\t”);
}
}
}
Output:
Enter element num1: 22
Enter element num2: 33
Enter element num3: 44
Enter element num4: 55
Enter element num5: 66
Displaying:
22 33 44 55 66
72 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Alternative ways of writing one dimensional array:
Program 2: Write a program which accepts the marks of a student into a 1D array
from the keyboard and finds total marks and percentage.
import java.util.*;
public class Array
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int tot=0;
float perc=0.0f;
int arr[] = new int[5];
for(int j=0;j<5;j++)
{
System.out.println("Enter marks of subject "+(j+1)+": ");
arr[j] = sc.nextInt();
}
for(int i=0;i<5;i++)
{
tot += arr[i];
}
perc = (float)tot/5;
System.out.println("Total marks: "+tot);
System.out.println("Percentage: "+perc);
}
}
Output:
Enter marks of subject 1: 50
Enter marks of subject 2: 50
Enter marks of subject 3: 50
Enter marks of subject 4: 50
Enter marks of subject 5: 50
Total marks: 250
Percentage: 50.0
73 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
A two dimensional array represents several rows and columns of data. For example,
the marks obtained by a group of students in five different subjects can be represented by a
2D array. If we write the marks of three different subjects as:
Student1 50 65 70 75 80
Student2 80 90 98 99 35
45 55 65 86 77
Student3
So the preceding marks represent a 2D array since it got 3 rows (no. of students) and
in each row 5 columns (no. of subjects). Hence there are total of 3x5 = 15 elements. We use
2D arrays for representing data in the form of table or matrix.
Case 1:We can declare a two dimensional array and directly store elements at the time of it
declaration, as:
Example: int marks[ ][ ] = {{50, 60, 70, 75, 80}, {80, 90, 98, 99, 35}, {45, 55, 65, 86, 77}};
Here,
a. “int” represents integer type elements stored into the array,
b. “marks” represents name of the array,
c. two subscripts [ ][ ] after the array name indicates 2D array contains two indices. 1 st
index represents row and the 2nd index represents columns of that array,
d. each row of the elements shoould be written inside the curly braces { and },
e. the elements in each row are separated by commas.
Since there are 3 rows and 5 columns in array, JVM creates 3x5 = 15 blocks of memory
as there are 15 elements being stored into the array. These blocks can be individually reffered
to as:
marks[0][0], marks[0][1], marks[0][2], marks[0][3], marks[0][4]
marks[1][0], marks[1][1], marks[1][2], marks[1][3], marks[1][4]
marks[2][0], marks[2][1], marks[2][2], marks[2][3], marks[2][4]
74 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
By this, it is clear that the rows are starting from 0 to 2 and the columns are starting
from 0 to 4. So any element can be referred to as marks[i][j], where i represents row position
and j represents column position. Hence a 2D array has two indices they are i and j. We can
represent an array as shown below:
Program: Write a program to take a 2D array and display its elements in matrix form.
import java.util.*;
public class Array
{
public static void main(String[] args)
{
int arr[][]={{50,65,70,75,80},{80,90,98,99,35},{45,55,65,86,77}};
for(int i=0;i<3;i++)
{
for(int j=0;j<5;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}
Output:
50 65 70 75 80
80 90 98 99 35
45 55 65 86 77
75 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Case 2:
Another way of creating a two dimensional array is by declaring the array first and
then alloting memory for it by using new operator:
Here, JVM allots memory for storing 15 integer elements into the array. But there are
no actual elements stored in the array so far. We can store these elements by accepting them
from the keyboard or from within the program.
Program: Write a program which accepts elements of a matrix and display its
transpose.
import java.util.*;
public class Array
{
public static void main(String[] args)
{
int arr[][]= new int[2][2];
Scanner sc = new Scanner(System.in);
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++){
System.out.println("enter element ["+i+"]["+j+"]: ");
arr[i][j]=sc.nextInt();
}
}
System.out.println("Transpose of a matrix: ");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(arr[j][i]+"\t");
}
System.out.println();
}
}
}
Output:
enter element [0][0]: 1
enter element [0][1]: 2
enter element [1][0]: 3
enter element [1][1]: 4
Given matrix:
1 2
3 4
Transpose of a matrix:
1 3
2 4
76 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
A three dimensional array is the combination of several 2D arrays. For example, a college
has 2 departments and we want to represent the marks obtained by the students of each
department in 5 different subjects. We can write these marks as shown here:
Syntax: int marks[ ][ ][ ] = {{{50, 60, 70, 7, 80}, {80, 9, 98, 99, 35}, {45, 55, 65, 8, 77}},
{{20, 30, 40, 50, 60}, {35, 40, 45, 50, 55}, {60, 65, 70, 75, 80}}};
(or)
int marks[ ][ ][ ] = new int[2][3][5];
Here,
a. “int” represents integer type elements stored into the array,
b. “marks” represents name of the array,
c. three subscripts [ ][ ][ ] after the array name indicates 3D array contains three indices
and each index starts with zero.
1st index represents number of tables (2D arrays) in that array,
2nd index represents row size of the table,
3rd index represents column size of the table.
The elements of this array can be accessed as marks[k][i][j] by using 3 for loops. The
3D array marks[ ][ ][ ] can be represented as below:
77 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output:
Department 1:
student 1 marks:
50 60 70 75 80 total: 335
student 2 marks:
80 90 98 99 35 total: 402
student 3 marks:
45 55 65 86 77 total: 328
Department 2:
student 1 marks:
20 30 40 50 60 total: 200
student 2 marks:
35 40 45 50 55 total: 225
student 3 marks:
60 65 70 75 80 total: 350
78 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
arrayname.length:
If we want to know the size of any array, we can use the property ‘length’ of an array.
arrayname.length returns an integer number which represents the size of an array. This property
may return 0 or positive integer value.
For example, take the array arr[ ] with the size 10 and there are five elements in it, as:
Now, arr.length gives 10. The arr[ ] contained 3 elements, but ‘length’ property does not give the
number of elements of the array. it gives only its size.
But, in case of a two or three dimensional array, ‘length’ property gives the number of rows of
the array, as given here:
The java command line argument is an argument i.e. passed at the time of running the
java program.The arguments passed from the console can be received in the java program and it
can be used as an input. To catch and store these values, main() has a parameter, String args[]
as:
public static void main(String args[ ])
Here, args[ ] is a 1D array of String type. So, it can store a group of Strings, passed to main()
from outside by the user. The user should pass the values from outside, at the time of running the
program at command prompt, as:
79 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The three values passed to main() at the time of running the program are 11, 99, and sai.
These three values are automatically stored in the main() methods`s args[ ] in the form of
Strings. This is because, args[ ] is a String type array. Thus,
99 is stored as args[1],
args[0] args[1] args[2]
Sai is stored as args[2].
Command line represents the run command and the values given at the time of running
the program.Command line arguments represent the values passed to main() method. If there are
three command line arguments, then JVM allots memory for those 3 values only. If there are no
command line arguments then JVM will not allot any memory. So the size of ‘args’ array is same
as the number of arguments passed to it.
Program 2: Write a program to perform addition of two numbers using command line
arguments.
public class Return
{
public static void main(String[] args) throws Exception
{
if(args.length != 2)
{
System.out.println("Please enter values: ");
return;
}
String s1 = args[0];
String s2 = args[1];
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
System.out.println("The sum: "+(d1+d2));
}
}
Output:
javac Return.java
java Return 11 22
The sum: 33.0
80 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). What value does array elements get, if they are not initialized?
Answer: They get default values.
81 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). There are two array objects of int type. one is containing 100 elements and another one
is containing 10 elements. Can you assign array of 100 elements to an array of 10
elements?
Answer:Yes, you can assign array of 100 elements to an array of 10 elements provided they
should be of same type. While assigning, compiler checks only type of the array not the
size.
public class MainClass
{
public static void main(String[] args)
{
int[] a = new int[10];
int[] b = new int[100];
a = b; //Compiler checks only type, not the size
}
}
82 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Strings
Most of the data that transmits on internet will be in the form of groups of characters. Such
groups of characters are called as ‘Strings’. For example, in a business order form, a person
enters details like his name, credit card number, address etc., which are all nothing but Strings
only. So a string represents group of characters.
The Java platform provides the String class to create and manipulate strings. Hence every string
is an object of String class but not a character array. String is a class in java.lang package which
contains all necessary methods to manipulate strings.
Even though, String is a class, it is used often in the form of a data type as:
Here, s is a variable of type ‘String’ and Java is a value assigned to s. If we want to declare a
value as string that must be placed in double quotes.
Creating Strings:
1) We can create a string just by assigning a group of characters to a string type variable:
Syntax: String s;
s =”Hello”;
Note: These two statements can be combined and written as:
String s =“Hello”;
In this case JVM creates an object (allocates memory for storing data) and stores
string: “Hello” in that object. This object can be refered by using the variable ‘s’.
83 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) We can create a string by using new operator, like given here:
3)The third way of creating the strings is by converting the character arrays into strings. Let us
take a character type array: arr[ ] with some characters as:
1) String concat(String s): This method returns a string after concatenating the string ‘s’ at
the end of the string.conact() method concatinates or joins two or more strings.
The same concatenation can be done by using “+” operator, which is called
“string concatenation operator”.
String s3=str1+str2;
84 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) int length(): This method returns length or number of characters of a String.
3) char charAt(int i): This method returns a character at specified location ‘i’.
4) String toLowerCase():This method converts all the characters of the string into lower
case, and returns the lower-cased string.
Example: String str1 = “HELLO“;
System.out.println(str1.toLowerCase());
Output: hello
5) String toUpperCase():This method converts all the characters of the string into upper
case, and returns the upper-cased string.
Example: String str1 = “hello “;
System.out.println(str1.toUpperCase());
Output: HELLO
6) String trim():This method removes spaces from the beginning and the ending of the
string.
Example: String str1 = “ hello welcome “;
System.out.println(str1.trim());
Output: hello welcome
9) int compareToIgnoreCase (String s):This method is similar to the compareTo() but this
doesn`t consider the case.
Example: String str1 = “ANT”;
String str2 = “ant”;
System.out.println(str1.compareTo(str2));
Output: 0
10) int indexOf(String s):This method returns an integer value indicating the first
occurrence of string s in the main string.
Example: String str1 = “This is a book”;
String str2 = “is”;
System.out.println(str1.indexOf(str2));
Output: 2
11) int lastIndexOf(String s):This method is similar to indexOf() method but returns the last
occurrence of the string s.
Example: String str1 = “This is a book”;
String str2 = “is”;
System.out.println(str1.lastIndexOf(str2));
Output: 5
12) boolean startWith(String s):This method returns true, if string starts with given string
‘s’, else returns false.
Example: String str1 = “This is a book”;
System.out.println(str1.startsWith(“T”));
Output: true
13) boolean endsWith(String s):This method returns true, if string ends with given string
‘s’, else returns false.
Example: String str1 = “This is a book”;
System.out.println(str1.endsWith(“ok”));
Output: true
86 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
14) String replace(char c1, char c2):This method returns a string after replacing all the
occurrences of character ‘c1’ with ‘c2’.
Example: String str1 = “Hello”;
System.out.println(str1.replace(‘l’,’x’));
Output: Hexxo
15) String subString(int i):This method return a sub string from the main string starting
from the index ‘i’.
Example: String str1 = “This is a book”;
System.out.println(str1.subString(5));
Output: is a book
16) String subString(int i,int j):This method return a sub string from the main string starting
from the index ‘i’ till ‘j-1’.
Example: String str1 = “This is a book”;
System.out.println(str1.subString(5, 7));
Output: is
17) void getChars(int i, int j, char arr[ ], int k):This method copies characters from string
into a character array. The characters starting from position ‘i’ to ‘j-1’ in the string and
copies them in array ‘arr’ starting from index ‘k’.
Example: String str1 = “This is a book”;
char c[ ];
str1.getChars(9, 14, c, 0);
for(int i=0; i<c.length; i++)
System.out.println(c[i]);
Output: b
o
o
k
87 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:Write a program which will help us to understand how to create strings and how
to use some important methods of String class.
88 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
String Comparison:
The relational operators like >, >=, <, <= and != cannot be used to compare the strings.
We can compare string in java on the basis of content and reference.It is used in authentication
(by equals() method), sorting (by compareTo() method), reference matching (by == operator).
So, there are three ways to compare strings in java:
1. By compareTo() method
2. By == operator
3. By equals() method
1. compareTo() method:
89 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2. ‘= =’ operator:
When an object is created by JVM, it returns the memory address of the object as a
hexadecimal number, which is called 'object reference’. When a new object is created a new
reference number is alloted to it.
Hence if we use ‘= =’ operator for comparing two strings then, it checks whether the
reference numbers of these two strings are equal are not. If the reference numbers are equal
then it will return true, else it will return false.
Inspite of the fact that both the strings s1 and s2 are same, we are getting wrong output in
above program. Let us take the first statement:
String s1 = “Hello”;
When JVM executes the preceding statement, it creates an object on heap and stores
“Hello” in it. A reference number, say 4f35a7 is alloted for this object. Similarly when the
following statement is executed,
Here, s2 is created by using ‘new’ operator and hence JVM allots another reference
number, say 5g67b1. So that statement, if(s1==s2) will compare these reference numbers, i.e.,
4f35a7 and 5g67b1. Both are not same. So, ‘s1==s2’ returns false and hence the output is “Not
Same”. Actually we need to compare content of the strings but not their references. This is the
90 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
reason == is not used to compare the strings.Hence to compare two strings, we use equals()
methods instead of == operator.
4f35a7 Hello
S1
== equals()
5h67b1 Hello
S2
3. equals() method:
The equals() method is used to compare the content of two strings. This should be
used as “s1.equals(s2)”. Hence the two strings s1 and s2 are compared. If the two strings are
equal then this method returns true else it returns false.
When the next statement,String s2 = “Hello”;is executed by the JVM, it searches in the
string constant pool to know whether the object with same content is already available there are
not. Since the same object is already available there (which is s1), then JVM does not create
another object. It simply create another reference variable (s2) to the same object, and copies the
reference number of s1 into s2. So, we have same value in s1 and s2. Hence, the output “Both are
same”.
2f67b2 Hello
S1
2f67b2
S2 String Constant Pool
Figure 2 String comparison when the strings are created using assignment
Immutability of String:
Objects are broadly classified as mutable and immutable objects. Mutable objects are those
objects whose contents can be modified. Immutable objects are those objects, once created can
not be modified. String class objects are immutable. Once string object is created its data or state
can't be changed but a new string object is created.Let us take a program to understand whether
the string objects are immutable or not.
92 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Let us consider the statement, s1 = s1+s2; and the output of the program, “Youngminds”. It
seems that the string s1 content is modified. Earlier s1 got “Young” and s2 had “minds”. After
s1+s2, they are joined and the total string become “Youngminds”. This string is assigned to s1
again. If s1 is mutable, it gets the newstring “Youngminds”. This is what we can see in the
output. So s1 appears to be mutable.
Butstrings are definitely immutable. Here, “Young” is not changed, but a new memory
location is created by JVM which contains “Youngminds” and its reference is allocated to s1 as
shown below:
s1 X Young
minds
s2
Youngminds
93 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q).What is the difference between == and equals() while comparing strings? Which one is
reliable?
Answer:== operator compares the references of the String objects. It doesn’t compare the
contents of the objects. equals() method compares the contents. While comparing the
strings, equals() method should be used as it yields the correct results.
94 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
a. StringBuffer class
b. StringBuilder class
StringBufferclass:
There are different ways to create a StringBuffer object based on the constructors it is having.
They are:
2. StringBuffer(): creates an empty string buffer with the initial capacity of 16 characters.
Syntax: StringBuffer sb = new StringBuffer( );
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
Syntax: StringBuffer sb = new StringBuffer(50);
95 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, StringBuffer object is created as an empty object with a capacity for storing 50 characters.
Of course, even if we declare the capacity as 50, it is possible to store more than 50 characters
into this StringBuffer. Because StringBuffer is mutable and can be expand dynamically in
memory.
StringBuffer Class Methods:
1) StringBuffer append(x):‘x’ may be boolean, byte, int, long, float, double, char,
characterarray, String or another StringBuffer. It will be added to StringBuffer object.
Example: StringBuffer sb = new StringBuffer(“Uni”);
sb.append(“versity”);
System.out.println(sb);
Output: University
2) StringBuffer insert(int i, x):‘x’ may be boolean, byte, int, long, float, double, char,
characterarray, String or another StringBuffer. It will be inserted into StringBuffer at the
position represented by i.
Example: StringBuffer sb = new
StringBuffer(“Intelligent Person”);
sb.insert(11, “Young”);
System.out.println(sb);
Output: Intelligent Young Person
3) StringBuffer delete(int i, int j):This removes the characters from ith position till j-1th
position in the StringBuffer.
Example: StringBuffer sb = new
StringBuffer(“University”);
sb.delete(0,3);
System.out.println(sb);
Output: versity
96 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
5) StringBuffer replace(int i, int j, String str ): This replaces characters from i to j-1, by
the string ’str’ in StringBuffer object.
Example: StringBuffer sb = new
StringBuffer(“This is a book”);
sb.replace(8,9,”java”);
System.out.println(sb);
Output: This is java book
1. int length()
2. int indexOf(String str)
3. int lastIndexOf(String str)
4. String subString(int i)
5. String subString(int I, int j)
97 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
StringBuilder class:
The creation of StringBuilder and the methods of StringBuilder are all similar to
StringBuffer class. The StringBuilder class has been added in jdk 1.5 which has same features
like StringBuffer class. StringBuilder class objects are also mutable.
The main difference between StringBuffer and StringBuilder classes is that the
StringBuffer class is synchronized by default whereas StringBuilder class is not.
This means when several threads act or process on StringBuffer class object, they are
executed one by one on the object, thus ensuring reliable results.
But in case of StringBuilder object, since it is not synchronized, it allows several threads to
act on it simultaneously. This may lead to inaccurate results in some cases.
98 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
StringBuffer class will take more execution time than StringBuilder class. If we work
on single thread program then we will go to StringBuilder because it gives quick response.
99 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
OOPS:
The language like C, Pascal, Fortran etc., are called Procedure oriented programming
languages since in these languages, a programmer uses procedures or functions to perform a task.
When the programmer wants to write a program, he will first divide the task into separate sub
tasks, each of which is expressed as a function. So a C program generally contains several
functions which are called and controlled from a main() function. This approach is called
procedure oriented approach.
method1
sub task1
main()
method method1
sub task2
The languages like C++ and Java use classes and objects in their programs and are called
object oriented programming languages. A class is a module which itself contains data and
methods (functions) to achieve the task. The main task is divided into several modules, and these
are represented as classes. Each class can perform some tasks for which several methods are
written in a class. This approach is called object oriented approach.
data
class1
methods
class with
main() class2 data
methods
method
100 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In POP, program is divided into small parts In OOP, program is divided into parts
called functions. called objects.
In POP, Importance is not given In OOP, Importance is given to the data rather
to data but to functions as well than procedures or functions because it works as
as sequence of actions to be done. a real world.
POP does not have any access specifier. OOP has access specifiers named Public, Private,
Protected, etc.
In POP, Data can move freely from In OOP, objects can move and communicate with
function to function in the system. each other through member functions.
To add new data and function in POP is not OOP provides an easy way to add new data and
so easy. function.
In POP, Most function uses Global data for In OOP, data cannot move easily from function
sharing that can be accessed freely from to function, it can be kept public or private so
function to function in the system. we can control the access of data.
POP does not have any proper way for OOP provides Data Hiding so provides more
hiding data so it is less secure. security.
Examples of POP are: C, VB, FORTRAN, Examples of OOP are: C++, JAVA, VB.NET,
and Pascal. C#.NET.
o Class/Object
o Encapsulation
o Abstraction
o Inheritance
o Polymorphism
101 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Class/Object:
Entire OOP methodology has been derived from a single root concept, called ‘object’. An
object is anything that really exists in the world and can be distinguished from others. For
example, a table, a ball, a car, a dog, a person, etc.
Every object has properties and can perform certain actions. For example, let us take a
person whose name is ‘Raju’. Raju is an object because he exists physically. He has properties
like name, age, sex, etc. These properties can be represented by variables in our programming.
Similarly, Raju can perform some actions like talking, walking, eating and sleeping. We
may not write code for such actions in programming. But, we can consider calculations and
processing of data as actions. These actions are performed by methods (functions). So an object
contains variables and methods.
It is possible that some objects may have similar properties and actions. Such objects
belong to same category called a ‘class’.
name Raju
age 25
sex M
talking talk()
walking walk()
eating eat()
102 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Encapsulation:
Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixture of several medicines.
In encapsulation the variables of a class will be hidden from other classes, and can be
accessed only through the methods of their current class, therefore it is also known as data
hiding.
Abstraction:
Abstraction is the process of hiding the unnecessary data from the user. A good example
for abstraction is a car. Any car will have some parts like engine, radiator, mechanical and
electrical equipment etc,. The car driver should know how to drive the car and does not require
any knowledge of these parts. For example driver is never bothered about how the engine is
designed and the internal parts of the engine.
The advantage of abstraction is that every user will get his own view of the data according
to his requirements and will not get confused with unnecessary data. A bank clerk should see the
customer details like account number, name and balance amount in the account. He should not
be entitled to see the sensitive data like the staff salaries, profit or loss of the bank, etc,. So such
data can be abstracted from the clerk’s view. Whereas the bank manager is interested to know
this data, it will be provided to the manager.
103 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Inheritance:
Inheritance is the process of creating a new class from existing class. So the newly created
class acquires all the properties from existing class.
The existing class is also called as super or base or parent class. The new class is called as
sub or derived or child class.Inheritance is achieved by using extends keyword.
The main advantage with inheritance is code reusability. That means all the properties of a
class can be reused many number of times in a class without re-declaration.
Polymorphism:
The word polymorphism is came from two Greek words “poly” means “many” and
“morphos” means “forms”. Thus polymorphism represents the ability to assume several different
forms.
In programming, we can use a single variable to refer to objects of different types and
thus, using that variable we can call the methods of the different objects. Thus a method call can
perform different tasks depending on the type of object.
Polymorphism provides flexibility in writing programs in such a way that the programmer
uses same method call to perform different operations depending on the requirement.
104 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) What is object oriented approach?
Answer:Object oriented approach is a programming methodology to design computer
programs using classes and objects.
Q) What is a class?
Answer:A class is simply a representation of a type of object. It is the blueprint/ plan/
template that describe the details of an object.
Q) What is an object?
Answer:Object is termed as an instance of a class, and it has its own state, behavior and
identity.
Q) What is Encapsulation?
Answer:Encapsulation is a technique used for hiding the properties and behaviors of an
object and allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated object.
105 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In the above example after the class keyword we should write the class name. In the
class, we write instance variables and methods. See the method void talk(). This method does not
return any result (void) and it does not accept any data from us. So we did not declare variables
after the method name. Through this method, the person is talking with us.
Writing a class without an object is not sufficient. So to use a class, we should create an
object to the class. Object creation represents allotting memory necessary to store the actual data
of the variables. To create an object the following syntax is used.
106 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, new is an operator that creates the object to a class, hence the right hand side part of
the statement is responsible for creating the object. In the left side part Person is the class name
and p is the object name. p is actually a variable of Person class. This variable stores the
reference number of the object returned by the JVM.
Generally class code along with method code is stored in ‘method area’ of the JVM.
When an object is created the memory is allocated on ‘heap’. After creating an object, JVM
produces a unique reference number for the object from the memory address of the object, this
reference number is also called “hash code” number.
Please observe the output of the above preceding program. In this program, we created
the object ‘p’, but did not initialize the instance variables. Initialization means storing the starting
data. Since we did not initialize the instance variables, Java compiler adds some additional code
to Person class and it initializes the instance variables with default values.
107 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
It is the duty of the programmer to initialize the instance variables, depending on his
requirements. There are various ways to do this. First way is to initialize the instance variable of
Person class in another class.
Type1: It is possible to initialize the instance variables of one class in another class through the
reference.
Access specifiers:
These are the keywords which specify how to access or read the members of a class or
the class itself. We can us access specifiers before a class and its members. There are 4 access
specifiers in Java.
1) public: public members of a class are available anywhere outside the class.
2) private: private members of a class are not available outside the class. They are
accessible only with in the class by the methods of a class.
3) protected: protected members are available outside the class, but generally, with in
the same class. Protected keyword is used in inheritance.
4) default: when the programmer does not write any access specifier. Java compiler
internally uses a default keyword.
Type2:we can initialize the instance variables at the time of their declarations.
108 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Constructors:
A constructor is a special member function and a constructor is similar to a method that is
used to initialize the instance variables of a class. A constructor has the following characteristics.
1) A constructor’s name and class name should be same. And the constructor’s name should
end with a pair of simple braces.
For example, in Person class, we can write a constructor as:
Person()
{
}
2) A constructor may have or may not have parameters. Parameters are the variables to
receive data from outside into the constructor. If a constructor does not have any
parameters, it is called ‘default constructor’. If a constructor has 1 or more parameters, it
is called ‘parameterized constructor’.
3) A constructor does not return any value, not even “void”. i.e., we should not write “void”
before the constructor.
4) A constructor is automatically called and executed at the time of creating an object.
5) A constructor is called and executed only once per object. This means when we create an
object, the constructor is called. When we create second object, again the constructor is
called second time.
Types of constructors:
In java the constructors are mainly classified into 2 types.
Constructor
Parameterized Default
constructor or
No-Parameterized
constructor
System-defined User-defined
Default constructor Default constructor
109 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Default Constructor:
If a constructor does not have any parameters on its signature is called default
constructor. This can be divided into two types.
Syntax: Person()
{
}
Program: write a java program by using default constructor to initialize the instance
variables of a class.
class Takeoff
{
String name;
float sal;
Takeoff()
{
name="sai";
sal=20000.00f;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Salary="+sal);
}
}
publicclass YoungMinds
{
Parameterized constructor:
If a constructor has one or more parameters on its signature is called parameterized
constructor.
Syntax: constructor(datatype var1,datatype var2)
{
-------
-------
}
The main advantage of parameterized constructor is, we can initialize an object by taking
dynamic values at the time of execution.
Program:write a java program to initialize the instance variables of person class using
parameterized constructor.
class Takeoff
{
String name;
float sal;
Takeoff()
{
name="sai";
sal=20000.00f;
}
Takeoff(String s,float f)
{
name=s;
sal=f;
}
void display()
{
System.out.println("Name="+name+ “and salary=”+sal);
}
}
publicclass YoungMinds {
111 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
this keyword:
this is a keyword that refers to the object of present class. Generally, we write instance
variables, constructors and methods in a class. All these members are referenced by ‘this’. When
an object is created to a class, a default reference is also created internally to the object. This
default reference is nothing but ‘this’. So ‘this’ can be refer to all the things of the present object.
Instance variables
this constructors
methods
object
1. this.
2. this( )
If any data member is preceded by ‘this.’ then that must be data member of class only.
112 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
class This
{
int id;
String name;
}
Output: Id=1110
Name=sai
2. this() :Which can be used to call one constructor from the another constructor in the
same class. The main advantage of this() is, we can call multiple constructors by creating
a single object.
113 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
classThis2
{
privateint x;
This2()
{
this(55);
this.access();
}
This2(int x)
{
this.x=x;
}
void access()
{
System.out.println("x="+x);
}
}
publicclass ThisDemo
{
publicstaticvoid main(String args[])
{
This2 t=new This2();
}
}
Output: x=55
Q) What is hash code and how can you find the hash code of an object?
Answer:Hash code is a unique identification number allotted to the objects by JVM. This
hash code number is also called reference number which is created based on the location of
the object in memory, and is unique for all objects except String objects.
The hashCode() method of ‘Object’ class in java.lang package is useful to find the
hash code of an object.
115 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Methods in java:
A method represents a group of statements that performs a task. Here ‘task’ represents a
calculation or processing of data or generating a report etc., For example, take sqrt()method. It
calculates a square root value and returns that value. A method has two parts:
It contains method name, method parameters and method return data type. Method
prototype is written in the form.
In the above syntax, method name represents the name given to the method.
After the method name, we write some variables in the simple braces. These variables are
called parameters. Method parameters are useful to receive data from outside into the
method. This data can be used by the method.
Return data type is used to represent what type of result/data the method is returning.
Syntax: {
Statements;
}
116 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
For example, we want to write a body that calculates sum of two numbers. It may contain
the body, as shown here:
{
double c=a+b;
System.out.println(“sum of two numbers=”+c);
}
If a method returns some value, then a return statement should be written within the body
of the method, as:
Example:
{
double c=a+b;
return c;
}
Program:Write a program for a method without parameters and without return type.
class MethodSample
{
privatedouble num1,num2;
MethodSample(double a,double b)
{
num1=a;
num2=b;
}
void sum()
{
double res=num1+num2;
System.out.println("Sum="+res);
}
}
117 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
publicclass MethodDemo
{
publicstaticvoid main(String[] args)
{
MethodSample s=new MethodSample(10.0,20.0);
s.sum();
}
}
Output: sum=30.0
In the preceding program, the method does not accept any values, we did not declare any
parameters in the braces ( ). This method does not return any result, so ‘void’ is written before
the method.
The sum( ) method is acting on num1 and num2 which are instance variables of the
Sample class. Since instance variables are available in the object, while calling the method we
create an object to MethodSample class, and using the object we called the method. Such
methods are called ‘instance methods’.
Program:Write a program for a method with two parameters and return type.
class MethodSample
{
double sum(double num1,double num2)
{
double res=num1+num2;
return res;
}
}
publicclass MethodDemo
{
publicstaticvoid main(String[] args)
{
MethodSample s=new MethodSample();
doubleresult=s.sum(10,22.5);
System.out.println("Sum="+result);
}
}
Output: sum=32.5
118 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The datamembers of a class are mainly classified into two types:
1. Non-static datamembers
2. Static datamembers
Non-static static
If any datamember of a class is not preceded If any datamembers of a class is preceded by
by static keyword is known as non-static static keyword is known as static datamember.
datamember.
Syntax: datatype variablename; Syntax: static datatype variablename;
For these datamembers memory is allocated Memory will be allocated for these
at the time of creating an object. datamembers at the time of loading class only.
Memory allocated for these datamembers is Memory is allocated for these datamembers
multiple times, whenever a new object is only once in the program, (so that waste of
created. memory space can be reduced).
These datamembers are specific to an object, These are the common sharable memory
so that these are also known as object locations for every object of sane class. So that
datamembers (or) Instance datamembers. these are also called class members.
These properties should be accessed with These properties can be accessed mainly with
object reference only. class name reference (also possible to access
with object reference).
Static methods:
A static method is a method that does not act upon instance variables of a class. A static
method is declared by using the keyword ‘static’. Static methods are called using
classname.methodname()and objectname.methodname(). The other name for static method is
class method.Static methods can be accessed directly in static and non-static methods.
The main advantage with both static datamembers and static methods are, any object of
same class can use those properties even memory is allocated only once in the program.
119 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
class Test
{
staticintx=55;
staticvoid access()
{
System.out.println("x="+x);
}
}
publicclass StaticDemo
{
publicstaticvoid main(String[] args)
{
Test.access();
}
}
Output: x=55
Static block:
Syntax: static
{
Statements;
}
JVM executes a static block on a highest priority. This means JVM first goes to static
block even before it looks for the main() method in the program.
Program: write a program to test which one is executed first by JVM, the static block or
the static method.
publicclass Test1
{
static
{
System.out.println("Inside static block");
}
Program: write a program without main() method. This program compiles but gives an
error at runtime.
class Sample
{
static
{
System.out.println("static block");
}
}
Output:
In the above program the compiler throws an Exception. Now, we can cheat the JVM by
terminating it before it realizes that there is no main() method in the program.
Program: write a program without main() method. This program and also runs.
class Sample
{
static
{
System.out.println("static block");
System.exit(0);
}
}
Output:
121 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Instance methods:
Instance methods are the methods which act upon instance variables. To call the instance
methods, object is needed, since the instance variables are contained in the object. We call the
instance methods by using ‘objectname.methodname()’. The specialty of instance methods is
that they can access not only instance variables but also static variables directly.
1. Accessor methods
2. Mutator methods
Accessor methods:
These are the methods that simply access or read the instance variables. They do not modify
the instance variables. Accessor methods are also called “getter()” methods. They are generally
written in the form of “getxxx( )” methods.
Example: getName()
getSalary()
getId()
Mutator methods:
Mutator methods not only access the instance variables but also modify them. These
methods are also called “setter()” methods.They are generally written in the form of “setxxx( )”
methods.
Example: setName()
setSalary()
setId()
122 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: write a program to create Employee class object and store data into the object
using “setter methods”, and retrieve the data from the object using “getter methods”.
class Employee
{
privateint id;
private String name;
privatedouble sal;
void setId(int id)
{
this.id=id;
}
void setName(String name)
{
this.name=name;
}
void setSal(double sal)
{
this.sal=sal;
}
int getId()
{
return id;
}
String getName()
{
return name;
}
double getSal()
{
return sal;
}
}
publicclass EmployeeDemo
{
publicstaticvoid main(String[] args)
{
Recursion:
A method calling itself is known as ‘recursive method’, and that phenomenon is called
‘recursion’. Recursive function is very useful to solve many mathematical problems like to
calculate factorial of a number, generating Fibonacci series, etc. let us take an example to find
factorial value of a given number. Factorial value for a number is defined as:
num * (num-1) * (num-2)…… * 1.
For example, factorial of 5 will be 5*4*3*2*1=120, as long as num value is > 0.
publicclass Recursion
{
staticlong factorial(int num)
{
long result;
if(num==1) return 1;
result=factorial(num-1)*num;
return result;
}
publicstaticvoid main(String[] args)
{
System.out.print("Factorial of 5 is:");
System.out.print(Recursion.factorial(5));
}
}
Output: Factorial of 5 is:120
Factory methods:
A factory method is a method hat returns an object of the class to which it belongs.All
factory methods are static methods, but all static methods are not factory methods.
The main advantage of a static method is that a factory method receives various options
from the user and can create object depending up on the user options. Several constructors are
replaced by a single factory method.
Example:NumberFormat obj=NumberFormat.getNumberInstance();
124 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In the above example, ”getNumberInstance()” is a factory method of NumberFormat
class and returns an object to NumberFormat class.
Here we are creating Employee class object ‘obj’ using new operator.
NumberFormat obj=NumberFormat.getNumberInstance();
getNumberInstance().
a. First, store the class name ‘Employee’ as a String into a object. For this purpose,
Class c=Class.forName(“Employee”);
b. Next, create another object to the class whose name is in the object c. For this
purpose, we need newInstance() method of the class ‘Class’, as:
Employee obj=(Employee)c.newInstance();
4. By cloning a already available object, we can create another object. Creating exact
copy of a existing object is called ‘cloning’.
Employee obj2=(Employee)obj1.clone();
Q) Why instance variables are not available to static methods?
Answer: After executing static methods, Jvm creates the objects. So the instance variables are
Q) Is it possible to compile and run a java program without writing main( ) method?
125 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Inheritance
Deriving new classes from existing class, such that the new classes acquire all the
features of exiting class is called “Inheritance”. With the use of inheritance the information is
made manageable in a hierarchical order.
The idea of inheritance is simple but powerful: When you want to create a new class
and there is already a class that includes some of the code that you want, you can derive your
new class from the existing class. In doing this, you can reuse the fields and methods of the
existing class without having to write them yourself. Hence, the main advantage with inheritance
is code reusability.
The class which inherits the properties of other class is known as “subclass” (derived
class, child class) and the class whose properties are inherited is known as “superclass” (base
class, parent class).
All the classes are derived from topmost class i.e., “Object”. The Object class, defined
in the java.lang package, defines and implements behavior common to all classes, including the
ones that you write.
In any object oriented programming language, inheritance should be done from “top to
bottom” that means super class properties are inherited into child class but not sub class
properties into super class.
A
A extends to B
(or)
B is derived from A
B
The “extends” keyword indicates that you are making a new class that derives from an
existing class.
126 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Types of Inheritance:Inheritance is mainly classified into 5 types. They are:
1. Single inheritance: If one class properties are inherited into another single class is known as
“Simple or Single Inheritance”. Inheritance flow for the below figurecan be represented as:
“A B”
Class A
Single class B is inherited
from single class A
Class B
127 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Class A
Class C is inherited from
Class B class B which intern
inherited from class A
Class C
128 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
3. Hierarchical inheritance: Whenever one class properties are inherited into number of
classes is known as “Hierarchical Inheritance”. This indicates a form of tree structure with
one root (i.e., parent class) containing number of leaves (i.e., child classes). Inheritance flow
for the below figure can be represented as: “A B, A C, and A D”.
Class A
Classes B, C, D are
inherited from the same
class A.
Class B Class C Class D
Output:
Method of super class A
Method of sub class B
5. Multiple inheritance: Whenever multiple class properties are inheritedinto single class, then
such inheritance is known as “MultipleInheritance”. Inheritance flow for the below figure
can be represented as: “A D, BD, and C D”.
We know that in multiple inheritance, sub classes are derived from multiple super
classes. If two super classes have same names for their members (variables & methods) then
which super class member is inherited into the subclass is the main confusion in multiple
inheritance. This confusion is called “ambiguity problem”. So, Java does not support
multiple inheritance at class level because of ambiguity problem.
Note:
At the time of inheritance, properties of base class can be extended into derived class. So that
by creating an object for derived class, it is sufficient to allocate memory space for both base
and derived class.
If an object is created for the derived class, first memory is allocated for base class; later it
will be assigned for derived class properties.
Inheritance is a compile-time mechanism. A super-class can have any number of subclasses.
But a subclass can have only one superclass. This is because Java does not support multiple
inheritance.
130 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Constructors in Inheritance:
While inheriting one class in another class all the properties will be inherited except
constructor why because the scope of the constructor is within the class. But, in Java default
constructor of super class is automatically called in sub class constructor.
131 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Sometimes, the super class members and sub class members may have same names. In
that case, by default only sub class members are accessible.In such a case, to access the super
class members from sub class, “super” keyword is used. “super” refers to super class members
from a sub class. For example:
Program:Write a Java program to access the super class method and instance variables
by using super keyword from sub class.
class OneSuper
{
int i=0;
void show()
{
System.out.println("Super class method: i= "+i);
}
}
class TwoSub extends OneSuper
{
int i=20;
void show()
{
System.out.println("Sub class method: i= "+i);
super.show();
System.out.println("Super i= "+super.i);
}
}
public class Super
{
public static void main(String args[])
{
TwoSub t = new TwoSub();
t.show();
}
}
Output:
Sub class method: i= 20
Super class method: i= 0
Super i= 0
132 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
3. super can be used to refer to super class constructor. We need not call the default constructor
of the super class, as it is by default available to sub class. To call the parameterized
constructor, we can write:
Syntax: super(values)
If any class is preceded by final keyword those properties cannot be inherited in any other
class. Hence “final” keyword is used to restrict inheritance.
Example: final class A
{ --------
}
class B extends A //Not valid
{---------
}
133 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The private members of super class are not available to sub classes directly. But
sometimes, there may be a need to access the data of super class in the sub class. For this
purpose, protected specifier is used. “protected” is commonly used in super class to make the
members of super class available directly in its sub classes. Thus protected specifier works like
public with respect to sub classes.
Program:Write a Java program to understand private members are not accessible in sub
class, but protected members are available in sub class.
class Access
{
private int a;
protected int b;
}
class sub extends Access
{
public void get()
{
System.out.println(a); //error - a is private
System.out.println(b);
}
}
public class Test
{
public static void main(String args[]){
Sub s = new Sub();
s.get();
}
}
Output:
Test.java:10: a has private access in Access
System.out.println(a);
^
1 error
In the next program, we create shape classwith a protected instance variable ‘l’. From
shapeclass, we derive Square class and from Square class, we derive Rectangle class. We want
to calculate areas of Square and Rectangle classes. For this purpose, in Square class we can
directly use ‘l’ of the Shape class and calculate the area of Square as l*l. we can also calculate
area of rectangle, by taking another variable ‘b’ and using the ‘l’ of Shape, as l*b.
134 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program to find the areas of Square and Rectangle by deriving them
from Shape.
class Shape
{
protecteddouble l;
Shape(double l)
{
this.l=l;
}
}
class Square extends Shape
{
Square(double l)
{
super(l);
}
void area()
{
System.out.println("Area of Square="+(l*l));
}
}
class Rectangle extends Square
{
privatedouble b;
Rectangle(double x,double y)
{
super(x);
b=y;
}
void area()
{
System.out.println("Area of Rectangle="+(l*b));
}
}
publicclass Inherit
{
publicstaticvoid main(String[] args)
{
Square s=new Square(5.5);
s.area();
Rectangle r=new Rectangle(5.5,6);
r.area();
}
}
135 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Polymorphism
Polymorphism came from the two Greek words ‘poly’ means many and ‘morphos’ means
forms. The ability to exist in different forms is called ‘polymorphism’. In Java, a variable, an
object or a method can exist in different forms, thus performing various tasks depending on the
context. Because same variable or method can perform different tasks, the programmer has the
advantage of writing flexible code.
If the same method performs different tasks, then that method is said to exhibit
polymorphism(or) With same method name is existing in multiple times to perform multiple
operations is mainly known as “Polymorphism”.
1. Dynamic Polymorphism
2. Static Polymorphism
Dynamic Polymorphism:
class A class B
{ {
void show() public static void main(String args[])
{ {
--------- A obj = new A();
} Binding obj.show();
} }
}
136 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In Java, any non-static method can be called using object reference. For objects memory
is allocated at runtime so that binding between methods call and method body is allocated at
runtime only. That means whenever we want to achieve dynamic polymorphism that must be
through “non-static methods”.
In Java, dynamic polymorphism can be achieved in two different ways. They are:
a. Method Overloading
b. Method Overriding
Method Overloading:
Writing two or more methods in the same class in such a way that each method has same
name but with different method signatures is called method overloading.The scope of
overloading is within the class only.
Let us take a class “Sample” with two instance method having same name as:
{
System.out.println(“Sum of two= “+(a+b));
}
void add(int a, int b, int c)
{
System.out.println(“Sum of Three= “+(a+b+c));
}
The bodies of these methods are different and hence they can perform different tasks. For
example, the first method adds two integer numbers and the second method adds three integer
numbers. However, to call these methods, we use the same method name. Suppose, we called the
method as:
When there is a difference in the method signatures, then the JVM understands both the
methods are different and can call the appropriate method. The difference in the method
signatures will arise because of one of the following reasons:
JVM matches the values passed to the method at the time of method call with the method
signature and picks up the appropriate method. In this way, difference in the method signatures
helps JVM to identify the correct method and execute it. Such methods are called overloaded
methods and this concept is referred to as “method overloading”.
138 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:Write a Java program to create Sample class which contains two methods with
the same name but with different signatures.
class Sub
{
void add(int a, int b)
{
System.out.println("Sum of two= "+(a+b));
}
void add(int a, int b, int c)
{
System.out.println("Sum of three= "+(a+b+c));
}
}
public class Test
{
public static void main(String args[])
{
Sub s = new Sub();
s.add(10, 15);
s.add(10, 15, 20);
}
}
Output:
Sum of two= 25
Sum of three= 45
Method Overriding:
Writing two or more methods in super and sub classes with same name and with same
method signatures is called method overriding (or) The sub class method overrides the super
class method and this concept is called method overriding.
139 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
JVM calls the method depending on the class name of the object used to call the method.
The scope of overriding is both in super and sub classes.
In inheritance, we always create an object to sub class and hence only the sub class
method is called. In the above program, method overriding is done with instance methods.
Static Polymorphism:
In Java, static polymorphism always can be exhibited using static methods. Static
polymorphism can be achieved only be overloading. Static methods can be overloaded similar to
non-static methods and its scope is only with in the class.
140 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Syntax: class < class name>
{
static return_type methodname()
{
---------
---------
}
static return_type methodname(datatype variable1)
{
---------
---------
}
………
}
A static method is a method whose single copy in memory is shared by all the objects of
the class. Static method belongs to the class rather than to the objects. So they are also called
“class methods”.
}
Output:
Square value: 625.0
141 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In preceding program, we created super class reference to sub class object, as:
One o = new Two( );
Here, ‘o’ is super class reference variable. Using this variable, we are calling the
calculate() method as o.calculate(25). So the super class calculate() method is executed. Suppose,
we created a sub class reference as,
Two t = new Two( );
and called the calculate() method using this sub class reference as t. calculate(25), then
the sub class calculate() is executed by the JVM. The point is, when static methods are
overridden, the JVM decides which method is to be executed depending on the reference type
used to call the method.
Important Interview Question:
Q).What is difference between method overloading and method overriding?
Answer:
S.No. Method Overloading Method Overriding
1. Writing two or more methods in the Writing two or more methods in super
same class in such a way that each and sub classes with same name and
method has same name but with with same method signatures is called
different method signatures is called method overriding.
method overloading.
142 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Private methods are the methods which are declared by using the access specifier
‘private’. This access specifier makes the method not to be available outside the class. Private
methods are not available in sub classes. This means, there is no possibility to overridethe
private methods of super class in its sub classes. So only method overloading is possible in case
of private methods.
If a method is written in the sub class with the same name as that of the private method of
the super class, then the method in super class and the method in sub class act as different
methods. That means the super class will get its own copy and the sub class will have its own
copy.
Similar to private methods, final methods cannot be overridden. Methods which are
declared as ‘final’ are called final methods. Therefore only method overloading is possible with
final methods. There are two uses declaring a method as ‘final’. There are:
Performance is increased because of ‘inline operation’
When a programmer does not want others to override his method, he should declare his
method as ‘final’.
Important Interview Question:
Q).Can we take private methods and final methods as same?
Answer:
Yes. The Java compiler assigns the value for the private methods at the time of
compilation. Also, private methods cannot be modified at run time. This is the same case
with final methods also. Neither the private methods nor the final methods can be
overridden. So, private methods can be taken as final methods.
143 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
final Class:
A final class is a class which is declared as final. final keyword before a class prevents
inheritance (sub classes cannot be created to a final class).
Example: final class A
{
-------
-------
}
class B extends A // invalid
144 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Type casting:
Converting one data type into another data type is called ‘type casting’ or simply called
‘casting’. Whenever we assign a value to a variable using assignment operator, the java compiler
checks for uniformity and hence the datatypes at both sides should be same. If the data types are
not same then we should convert the types to become same at the both sides.
To convert the datatype we use ‘cast operator’. Cast operator means writing the datatype
between simple braces, before a variable or method whose value is to be converted.
1. Primitive data types or fundamental data types:The data types which represent a
single entity (or value) are called ‘primitive data types’. For example, take ‘int’ type;
it can store only one integer value. Take ‘boolean’ value, it can store either true or
false only one value. So they come under primitive data types. the following are the
primitive data types:
char, byte, short, int, long, float, double, boolean.
2. Referenced data types or advanced data types:These data types represent several
values. For example, take an array. It can store several values. Similarly take a class.
It can store different values. So they are called advanced data types. We can access an
array or an object of a class in memory through references. So, they are also called
‘referenced data types’. The following are the examples for referenced data types:
Answer: primitive data types represent single value. Advanced data types represent a group of
values. Also, methods are not available to handle the primitive data types. In case of advanced data
145 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
We can convert a primitive data type into another primitive data type using casting.
Similarly, it is possible to convert a referenced data type into another referenced data type by
using casting. But we cannot convert a primitive data type into a referenced data type by using
casting. For this purpose, methods of Wrapper classes should be used.
It is possible to convert one primitive data type into another data type. This is done in two
ways.
1) Widening
2) Narrowing
The primitive data types are classified into two types, lower types and higher types.
Naturally, the lower types are the type which use less memory and which can represent lesser
number of digits in the value. The higher types use more memory and can represent more
number of digits. To recognize the lower and higher types, the following diagram is useful.
Thus ‘char’ is a lower type than ‘int’. ‘float’ is a higher type than long. ‘boolean’ is
not included earlier, because it cannot be converted into any other type.
Converting a lower data type into a higher data type is called widening. See the
examples:
o char ch=’A’;
int num=(int)ch; // num contains 65, the, ASCII value of ’A’.
Here, we are converting int type variable ‘ch’ into int type. For this purpose, we used the
cast operator by writing ‘int’ in the simple braces before the variable ‘ch’. Now that ch is
converted into int type, it can be assigned to the variable num.
o int x=9500;
float sal=(float)x; // sal contains 9500.0
146 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, we are converting int type variable ‘x’ into float. So, we wrote (float) before the
variable x.
Widening is safe because there will not be any loss of data or precision or accuracy. This is
the reason, even through the programmer does not use cast operator, Java compiler does not
complain. Of course, in this case, Java compiler does the casting operation internally and hence
this is also called ‘implicit casting’.
Answer: Automatic casting done by the java compiler internally is called implicit casting. Implicit
casting is done to convert a lower data type into a higher data type.
o int n=66;
char ch=(char) n; // ch contains ‘B’.
Here, we are converting int type to char type. The value of n is 66, which is when converted
into char type represents the character ‘B’, since 66 is ASCII value of B’. This character is stored
into ch.
o double d=12.6789;
int n=(int) d; // n stores 12.
Here, we are converting double type into int type by using the cast operator (int) before the
variable d. the value in d is 12.6789. Since it is converted into int type, the fraction part of the
number is lost and only 12 is stored in n. Here, we are losing some digits. So narrowing is not
safe. This is the reason, Java compiler forces the programmer to use cast operator when going for
narrowing. The programmer should compulsory cast the data type. So, narrowing is also called
‘explicit casting’.
147 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Answer: The casting done by the programmer is called explicit casting. Explicit casting is
compulsory while converting from a higher data type to a lower data type.
A class is a referenced data type. Converting a class type into another class type is also
possible through casting. But the classes should have same relationship between them by the way
of inheritance.
For example, you cannot convert a Dog class into a Horse class, as those classes do not
have any relationship between them. But you can convert a College class into a University class,
since College is derived from University. And you can convert a Department class into a
College, since Department is a sub class of College class. See the following figure which shows
that the classes Department, College and University have relationship by the way of inheritance.
Converting a sub class type into a super class type is called ‘generalization’, because we
are making the sub class to become more general and its scope is widening. This is also called
widening or up-casting. Widening is safe because the classes will become more general. So, the
java compiler will not ask for cast operator in generalization. It will do implicit casting.
148 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Similarly, converting a super class type into a sub class type is called ‘specialization’.
Here, we are coming down from more general form to a specific form and hence the scope is
narrowed. Hence, this is also called narrowing or down-casting. Narrowing is not safe because,
the classes will become more and more specific thus giving rise to more and more doubts. So,
the java compiler specifically asks the programmer to use cast operator.
Answer: Generalization is a phenomenon when a sub class is promoted to a super class, and hence
where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.
Program:
class One
{
void show()
{
System.out.println("super class method");
}
}
class Two extends One
{
void show2()
{
System.out.println("sub class method");
}
}
publicclass Cast {
149 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In the above program, if the programmer wants to call o.show2() method of sub class,
then the java compiler raises an error message at compilation time, as:
So, in widening, the programmer can access all the super class methods, but not the sub
class methods. Suppose, we override the super class methods in sub class, then it is possible to
access the sub class methods but not the super class methods. Anyhow, the programmer will get
only 50% functionality into his hands.
Narrowing represents converting super class type into sub class type.
Program:write a program for creating sub class reference which is used to refer to the
super class object.
class One
{
void show()
{
System.out.println("Super class method");
}
}
class Two extends One
{
void show2()
{
System.out.println("Sub class method");
}
}
publicclass NarrowCast {
t.show2();
This will also give the same error. So, in narrowing using super class object, we cannot access any
of the methods of the super class or sub class. So the programmer will get 0% functionality in this case.
There is a solution for this problem. Let us not create an object to super class, as we did in the
previous case. This time, we create an object to sub class and use narrowing, as show in he below
program.
Program: Write a program for creating super class reference to refer to sub class object.
class One
{
void show()
{
System.out.println("Super class method");
}
}
class Two extends One
{
void show2()
{
System.out.println("Sub class method");
}
}
publicclass NarrowCasting {
One o;
o=new Two();
Two t=(Two)o;
t.show();
t.show2();
}
}
In this program, we convert the super class reference type into sub class reference type. Then
using the sub class reference, we try to call the methods. It is possible to access all the methods
of the super class as well as the sub class. Narrowing using sub class object will provide 100%
functionality to be accessible to the programmer.
151 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Abstract classes:
In java language ‘abstract’ is a keyword represents incomplete. A class that is
declared with abstract keyword is known as abstract class in java. It can have abstract and non-
abstract methods (method with body).
While inheriting the concrete (complete) class to any other class all the properties of base
class are extended into derived class, so that we can achieve reusability. But in some cases we
want reuse separate body part, at that time the body part of the base class method will be wasted.
To overcome this problem we can use abstract classes.
Program:
class Demo
{
void calculate(double x)
{
System.out.println("Square="+(x*x));
}
}
publicclass Abs
{
In the preceding program, the requirement of all the objects is same, i.e., to calculate
square value. But, sometimes the requirements of the objects will be different entirely depend on
the specific object only. For example, in the preceding program, if the first object wants to
calculate square value, the second object wants the square root value and the third object wants
cube value. In such a case, how to write the calculate() method in Demo?
152 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Since, calculate() method has to perform three different tasks depending on the object,
we cannot write the code to calculate square value in the body of calculate() method. On the
other hand, if we write three different methods like calculate_square(), calculate_sqrt(), and
calculate_cube( ) in Demo, then all the three methods are available to all the three objects which
is not advisable. When each object wants one method, providing all the three does not look
reasonable. To serve each object with the one and only required method, we can follow the steps.
1. First, let us write a calculate( ) method in Demo. This means every object wants to
calculate method.
2. If we write body for calculate( ) method, it is commonly available to all the objects. So
let us not write body for calculate( ) method. Such a method is called abstract method.
Since, we write abstract method in Demo, it is called abstract class.
3. Now derive a sub class sub1 from Demo, so that the calculate( ) method is available to
the sub class. Provide body for calculate() method in sub1 such that it calculates square
value . Similarly, we create another sub class sub2 where we write the calculate() method
with body to calculate square root value. We create the third sub class sub3 where we
write the calculate() method to calculate cube value.
4. It is possible to create objects for the sub classes. Using these objects, the respective
methods can be called and used. Thus, every object will have its requirement fulfilled.
calculate();
Demo
153 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: The above program can be rewritten by using abstract method as,
abstractclass Demo
{
abstractvoid calculate(double x);
}
class Sub1 extends Demo
{
void calculate(double x)
{
System.out.println("Square="+(x*x));
}
}
class Sub2 extends Demo
{
void calculate(double x)
{
System.out.println("Square root="+Math.sqrt(x));
}
}
class Sub3 extends Demo
{
void calculate(double x)
{
System.out.println("Cube="+(x*x*x));
}
}
publicclass AbstDemo
{
publicstaticvoid main(String[] args)
{
Sub1 s1=new Sub1();
Sub2 s2=new Sub2();
Sub3 s3=new Sub3();
s1.calculate(3);
s2.calculate(4);
s3.calculate(5);
}
}
Output:Square=9.0
Square root=2.0
Cube=125.0
An abstract method does not contain any body. It contains only the method header so we
can say, it is an incomplete method. An abstract class is a class that generally contains some
abstract methods. If any class is incomplete, that can be declared as abstract class.
Both the abstract class and the abstract method should be declared by using the keyword
“abstract”.
154 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
If any method preceded by abstract keyword is known as abstract method.
If any class contains atleast one abstract method that class becomes abstract class.
Let us take another example to understand the abstract class. We see many cars on the road.
These cars are all objects of Car class. For example, Maruti, Santro, Benz, are all objects of car
class. Suppose, we plan to write Car class, it contains all the properties (variables) and methods
(actions) of any car object in the world. For example, we can write the following members in Car
class:
Registration number:Every car will have a registration number and hence we write this
as an instance variable in Car class. All cars whether it is Maruti or Santro should have
a registration number. It means registration number is a common feature to all the
objects. So, it can be written in the Car class.
Fuel tank: Every car will have a fuel tank, opening and filling the tank is an action. To
represent this action, we can write a method like: void openTank()
Let us assume that all cars have same mechanism of opening tank. So, the code
representing the opening mechanism can be written in openTank()method’s body. So it becomes
a concrete method.
155 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Steering:Every car will have a steering and steering the car is an action. For this, we
write a method as: void steering(int direction, int angle)
All the cars do not have same mechanism for steering. Maruti cars have manual steering.
Santro cars have power steering. So, it is not possible to write a particular mechanism in
steering( )method. So, this method should be written without body in Car class. It becomes an
abstract method.
Brakes:Every car will have brakes. Applying brakes is an action and hence it can be
represented as a method, as: void braking(int force)
All cars do not have same mechanism for brakes. Maruti cars have hydraulic brakes. Santro
cars have gas brakes. So, it is not possible to write a particular mechanism in braking( ) method.
So, this method should be written without body in Car class. It becomes an abstract method.
m s objects
So, the Car class has an instance variable, one concrete method and two abstract methods.
Hence, Car class will become abstract class.
Program:
abstractclass Car
{
int regno;
Car(int r)
{
regno=r;
}
void openTank()
{
System.out.println("Please take car key");
System.out.println("and fill fuel into the tank");
156 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
}
abstractvoid steering(int direction,int angle);
abstractvoid braking(int force);
}
publicclass AbsExample
{
publicstaticvoid main(String[] args)
{
Maruti m=new Maruti(9999);
Santro s=new Santro(6666);
Car ref;
ref=m;
ref.openTank();
ref.steering(1, 90);
ref.braking(500);
}
}
157 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output: Please take car key
And fill fuel into the tank
Maruti uses manual steering
Take a turn
Maruti uses hydraulic brakes
Apply brakes and stop the car
ref=s;
The keyword abstract represents an incomplete class which depends on the sub classes
for its implementation. Creating sub class is compulsory for abstract class. final keyword
prevents inheritance. This means, we cannot create sub class to final class. So, the key words
abstract and final are contradictory and hence both cannot be used simultaneously for a class.
158 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Interfaces
Interface is a replacement of abstract class. An interface in java is a blueprint of a
class.The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body.An interface is a specification of method
prototypes.
An interface is similar to a class in the following ways:An interface can contain any
number of methods.An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.However, an interface is different from a class in several
ways, including:
We cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract and public. The syntax for abstract method in
the interface is:
Syntax: public abstract return_type method_name(parameter1, parameter2,…);
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final, so the variables in the interface should initialize at the
time of declaring and whose value cannot be changed at the time of executing a program.The
default signature of every data member or a variable of an interface is:
Syntax: public static final datatype variable_name = value;
An interface is not extended by a class; it is implemented by a class.A class uses the
implements keyword to implement an interface.
Syntax: class <class_name> implements <interface_name>
{
----------
}
An interface can extend multiple interfaces.
Important Interview Question:
Q). Why the methods of interface are public and abstract by default?
Answer:
Interface methods are public since they should be available to third party vendors to
provide implementation. They are abstract because their implementation is left for third
party vendors.
159 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
There are mainly three reasons to use interface:
Since an interface contains all unimplemented methods. So, it is not possible to create an
object to interface. In this case, we can create separate classes where we can implement all the
methods of the interface. Thus we can create an object to this implementation classes. The
flexibility lies in the fact that every implementation class can have its own implementation of the
abstract methods of the interface as shown in figure below:
abstract
methods
Interface
implement implement
all the all the
methods of methods of
interface interface
Implementing interface:
160 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:Write a program to create an interface MyInter that connects to a database and
retrieves the data from the database.
interface MyInter
{
void connect();
void disconnect();
}
class OracleDB implements MyInter
{
public void connect() {
System.out.println("Connect to Oracle Database");
}
public void disconnect() {
System.out.println("Disconnect from Oracle Database");
}
}
class SybaseDB implements MyInter
{
public void connect() {
System.out.println("Connect to Sybase Database");
}
public void disconnect() {
System.out.println("Disconnect from Sybase Database");
}
}
public class InterfaceDemo
{
public static void main(String[] args) throws Exception
{
Class c = Class.forName(args[0]);
MyInter mi = (MyInter)c.newInstance();
mi.connect();
mi.disconnect();
}
Output:
javac InterfaceDemo.java
java InterfaceDemo OracleDB
Connect to Oracle Database
Disconnect from Oracle Database
In the preceding program, two third party vendors (OracleDB and SybaseDB) provided
their respective implementations to MyInter interface. Providing a possible way to create objects
to the implementation classes and call the connect() and disconnect() methods from the main
program. This program is also written by the same programmer who develops the interface.
Since the programmer does not know about the names of the implementation classes at the time
161 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
of writing a program, he should create object to implementation class without knowing its name.
For this the following steps are followed:
Take the driver name (e.g., OracleDB) from the client through command line arguments and
pass it to forName() method. This method belongs to class “Class” which is in java.lang
package. forName() accepts the name of a class a string, checks whether the given class is
available or not. If available it loads that class in object of class “Class” as:
Class c = Class.forName(args[0]);
Now create an object to the class whose name is in c. This can be done by newInstance()
method of the class. To use MyInter reference to refer to this object, the object type should
be converted as MyInter type by using casting.
MyInter mi = (MyInter)c.newInstance();
Call the connect() and disconnect() methods of the driver class using ‘mi’, as:
mi.connect(); //establishes the connection
mi.disconnect(); //disconnects from database
MyInter
void connect()
void disconnect() OracleDB Oracle database
main()
API document SybaseDB Sybase database
The relationship between interfaces and classes is clearly explained in the figure below:
a class extends another class,
an interface extends another interface and
a class implements an interface.
162 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
class 1 interface 1
extends extends
implements
class 2 interface 2
We know that in multiple inheritance, sub classes are derived from multiple super
classes. If two super classes have same names for their members (variables and methods) then
which member is inherited into the sub class is the main confusion in multiple inheritance. This
is the reason java does not support the concept of multiple inheritance. This confusion reduced
by using multiple interfaces to achieve multiple inheritance. Interface always contains abstract
methods so that there is no problem of ambiguity, so that interfacesupports multiple inheritance.
Let us take two interfaces as:
Example: interface A
{
int x = 20; //public static final
void method(); //public abstract
}
interface B
{
int x = 20; //public static final
void method(); //public abstract
}
class MyClass implements A,B //Now there is no confusion to refer to any member of interface
163 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
164 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
An abstract class is written when there are An interface is written when the
some common features shared by all the programmer wants to leave the
objects. implementation to third party vendors.
All the abstract methods of the abstract All the methods of the interface should be
class should be implemented in its sub implemented in its implementation classes.
classes.
Abstract class does not support multiple Interface supports multiple inheritance.
inheritance.
Abstract class can provide implementation Interface cannot provide implementation of
of interface. the abstract class
Example: Example:
abstract class Shape { public interface Shape {
public abstract void draw(); void draw();
} }
165 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Packages:
A package in Java is a special mechanism to encapsulate a group of classes, interfaces
and sub packages.Each package has its own name and organizes its top-level (that is, non-nested)
classes and interfaces into a separate namespace, or name collection.
Although same-named classes and interfaces cannot appear in the same package, they can
appear in different packages because a separate namespace assigns to each package.
Packages are useful to arrange related classes and interfaces into a group. Packages hide
the classes and interfaces in a separate sub directory, so that accidental deletion of classes and
interfaces will not take place.
The main advantage of packages is common reusability that means all the classes and
interfaces properties can be used at a time from different programs.
In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space
collisions”.
In java language every package will be treated as one folder and every sub package will
be treated as subfolder.
These are the packages already designed by the SUN micro systems and supplied as apart
of JDK (Java Development Kit) to simplify the task of java programmer.
Note:
Core packages of java starts with java. (For example: java.lang.*) and Advanced
packages ofjava starts with javax. (For example: javax.swing.*)
166 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The following are the mostly used and important packages of J2SE.
In the above syntax “java” is the main package name and “lang” is the sub
package name.
2) java.util:util stands for utility. This package is used to handle data structures, collection
frame work and also handles date and time operations.
3) java.io: io stands for input and output. This package contains streams; these are useful to
store data in the form of files and also to perform input-output operations.
4) java.awt:awt stands for abstract window toolkit. This package is used to develop GUI
based applications. It consists of an important sub package “java.awt.event”, which is
useful to provide action for components like push buttons, radio buttons, etc.
167 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
6) java.net: net stands for networking/network. This package is used to perform various
operations in the networking based applications.
7) java.applet:Applets are programs which come from a server into a client and get
executed on client machine on a network. Applet class of this package is useful to create
and use applets.
8) java.text: This package has two important classes, DateFormat to format dates and times,
NumberFormat which is useful to format numeric values.
9) java.sql: sql stands for structured query language. This package helps to connect
databases like oracle or Sybase and retrieve the data from them and use it in a java
program.
Java directory
java.io
io sub directory
awt directory
Java.awt
Package directory
168 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
User-defined packages:
If any package created by the user is called user-defined package, user-defined packages
can also be imported into other classes.
Any user-defined package can be created using a special keyword in java language called
“package”
Program:write a java program to create a package with the name pack and store Addition
class in it.
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1=a;
d2=b;
}
public void sum()
{
System.out.println("sum="+(d1+d2));
}
}
Any package program in java can be compiled with the following syntax.
169 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The –d option tells the java compiler to create a separate subdirectory with the package
name and place the .class file into it.
The directory is, on which location the java compiler creates a subdirectory and stores the
.class files into it.
In the above example, the dot(.) after –d indicates that the package should be created in
the current directory i.e., c:/> , and the above command means create a package (-d) in the
current directory (.) and store Addition.class file in the package. The package name is specified
in the above program as ‘pack’.
In the above example, the java compiler creates a new folder with the name pack in the
location of d:/sai and stores the Addition.class file into it.
Program:write a java program to create a package with the name pack and store
Subtraction class in it.
package pack;
public class Subtraction
{
public static double sub(double a,double b)
{
return(a-b);
}
}
To compile: javac –d . Subtraction.java
170 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
If we want to access any class properties of a package in the other user defined class we
must create an object with a fully qualified name.
Properties of any package also can be accessed using import statement. Import is a
keyword in java language and these statements can be used in two different ways.
1) import package.subpackage.subsubpackage.-------;
The above syntax can be used to import only one class (or) interface properties at a time.
2) import package.*;
The above syntax can be used to import all the classes and interfaces properties at a time.
Program:Write a java program to use both Addition & subtraction classes of the package
import pack.Addition;
import pack.Subtraction;
class Demo{
public static void main(String[] args) {
Addition obj=new Addition(10.0,15.0);
obj.sum();
double res=Subtraction.sub(20.0,15.0);
System.out.println("Subtraction="+res);
}
}
Output: Sum=25.0
Subtraction=5.0
171 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Interfaces in a package:
It is also possible to write interfaces in a package. But when ever, we create an interface
the implementation classes are also should be created. We cannot create an object to the interface
but we can create an object for implementation classes and use them.
package mypack;
public interface MyDate
{
void showDate();
}
To compile: javac –d . Mydate.java
Now create an implementation class to interface (MyDate) and write the body of the
method showDate(). Here, we can create an object to Date class (of java.util package) which by
default stores the system data and time.
172 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:
package mypack;
import mypack.MyDate;
import java.util.*;
public class DateImpl implements MyDate
{
public void showDate()
{
Date d=new Date();
System.out.println(d);
}
}
To compile: javac –d . DateImpl.java
Now create an object to DateImpl and call the showDate() method, it displays the system
date and time.
Program:
import mypack.DateImpl;
class DateDisplay
{
public static void main(String[] args)
{
DateImpl obj=new DateImpl();
obj.showDate();
}
}
Output: Mon Nov 16 17:46:51 IST 2015
An access specifier is a keyword that is used to specify how to access a member of a class
or the class itself. It means, we can use access specifiers with the members of a class or with the
class also. There are 4 access specifiers in java.
1) public
2) private
3) protected
4) default
173 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
We do not use default keyword for specifying the default access specifier. If no other
access specifier is used, then java compiler will take it as default access specifier.
1) public: public members of a class are available everywhere and their scope is ‘global
scope’. i.e. if we declare a class or any member preceded by ‘public’ keyword, we can
access from anywhere in the program.
2) private: Any private members scope is limited only to that class where it is defined. So
the scope of ‘private’ access specifier is ‘class scope’.
3) protected: The protected members of a class are accessed within its sub classes only, not
to the other classes. ‘protected’ specifier acts as public with respect to sub classes.
4) default: When no access specifier is used then java compiler takes a default access
specifier. The default members of a class are accessible within the same package. They
are not available to another package this means the scope of default members is package
scope.
174 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Exception Handling
Any human being may commit errors while designing the project or developing the code.
These errors are also called “bugs” and the process of removing them is called “debugging”.
1. Compile-time errors
2. Run-time errors
3. Logical errors
1. Compile-time errors: These are syntactical errors found in the code, due to which a
program fails to compile. For example, forgetting semicolon (;) at the end of a java
statement, or writing a statement without proper syntax will result in compile-time errors.
Output:
javac CErr.java
CErr.java:5: error: ';' expected
System.out.println("Hello")
^
1 error
In this program, we are not writing a semicolon at the end of the statements. This will be
detected by Java compiler. Detecting and correcting compile-time errors is easy as the java
compiler displays the list of errors with the line numbers along with their description. The
programmer can go through the statements line by line to understand where he has
committed the errors.
175 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2. Run-time errors: These errors represent inefficiency of the computer system to execute a
particular statement. For example, insufficient memory to store something or inability of the
microprocessor to execute some statement come under run-time errors.
Run-time errors are not detected by the Java compiler. They are detected by the JVM,
only at runtime.
3. Logical errors: These are the errors in the logic of the program. The programmer might be
using a wrong formula or the design of the program itself is wrong. Logical errors are not
detected either by Java compiler or by JVM. The programmer is solely responsible for them.
The programmer can detect logical errors by comparing the program output with the
manually calculated results.
176 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Exceptions:
In java, exception is an event that disrupts the normal flow of the program. Basically, an
exception is a runtime error. All exceptions occur only at run time but some exceptions are
detected at compile time and some others at run time.
The exceptions that are checked at compilation time by the Java compiler are called
“checked exceptions”.
The exceptions that are checked by the JVM are called “unchecked exceptions”.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is
a subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class. Exception Hierarchy is clearly shown in the
figure below.
177 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
java.lang
Object
Throwable
Error U Exception
U Unchecked Exceptions
Q).What is Throwable?
Answer:
Throwable is a class that represents all errors and exceptions.
178 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Please observe the output of this program. When we run the program without passing any
arguments, then n value became zero. Hence executing the following expression fails:
int a=45/n;
Here, division by zero happens and this value represents infinity. This value cannot be
stored in any variable. So there will be an exception at runtime in the above statement. In this
case, JVM displays exception details and terminates the program abnormally. The subsequent
statements in the program are not executed, due to this abnormal termination, the data in the files
may be lost or the software may be corrupted and many other problems may arise. So the
programmer should handle the exceptions.
An exception can occur for many different reasons, below given are some scenarios
where exception occurs.
Exception Handling:
If an exception is raised, which has not been handled by programmer then program
executioncan get terminated and system prints a non user friendly error message and user data
may be corrupted. To avoid this we need to handle the exceptions and this is called “Exception
handling”. We can handle exceptions in three steps:
Step 1: The programmer should observe the statements in his program where there may be a
possibility of exceptions. Such statements should be written inside a try block.
Syntax: try
{
statements;
}
179 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
“try" block prevents abnormal program termination, when there is an exception in the try
block JVM will store the exception message in a separate block of memory called “Exception
Stack” and then jumps into a catch block.
Step 2:The programmer should write the catch block where he should display the exception
details to the user. This helps the user to understand that there is an error in the program. The
programmer should also display a message regarding what can be done to avoid this error.
Step 3: Lastly, the programmer should perform clean up operations like closing files and
terminating the threads. This can be done by writing finally block.
Syntax: finally
{
statements;
}
The specialty of finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not. This ensures that all the opened files are
properly closed and all the running threads are properly terminated. So the data in the files will
not be corrupted.
Note:
If a return statement is encountered either in try or catch block. In such case also finally runs.
Control first goes to finally and then it returned back to return statement.
The finally block will not be executed if program exits (either by calling System.exit() or by
causing a fatal error that causes the process to abort).
180 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program to understand the use of try, catch and finally block.
public class Ex
{
public static void main(String args[])
{
try
{
System.out.println("Open files");
int n = args.length;
System.out.println("n= "+n);
int a = 45/n;
System.out.println("a= "+a);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println("please pass data while running this program");
}
finally
{
System.out.println("Close files");
}
}
}
Output:
javac Ex.java
java Ex
Open files
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program
Close files
In this program, the try block contains the statement where there is possibility for an
exception. When there is an exception JVM jumps into catch block. The finally block is executed
even if there is exception or not.
Note:
We can’t write a catch block without a try block. But a try block can be written without any
catch block.
JVM executes catch block only when there is an exception.
It is not possible to insert statements in between catch and try blocks.
It is possible to write a try block inside another try. This is called nested try blocks.
181 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
There is possibility to throw multiple exceptions in a single program. In this case the
programmers need to handle all those exceptions. To handle multiple exceptions we should write
multiple catch blocks.
Syntax: try
{
// Code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}
.
.
catch(Exception e) This is also called Default catch
{ block because Exception is the
//Catch block super class for all the exceptions.
}
If an exception occurs in the code, the exception is thrown to the first catch block in the
list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not,
the exception passes down to the second catch statement. This continues until the exception is
caught. If no ExceptionTypes are caught then default catch block is executed (same as default
case in switch control statement). It is not mandatory to maintain default catch block. Whenever
programmer doesn’t know which type of exception is going to rise then default catch block can
be used.
Note: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticExceptionmust come before catch for Exception.
If multiple catch blocks are present in a program then the above mentioned catch block
should be placed at the last. If you put the last catch block (catch(Exception e)) at the first place,
just after try block then in case of any exception this block will execute as it has the ability to
handle all exceptions. Hence compiler will raise an error.
182 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program which shows how to handle multiple exceptions (like
ArithmeticException and ArrayIndexOutOfBoundsException).
public class Multiple
{
public static void main(String[] args)
{
try
{
System.out.println("Open Files");
int n = args.length;
System.out.println("n= "+n);
int a = 45/n;
System.out.println("a= "+a);
int b[] = {10,20,30};
b[50] = 100;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println("Please pass data while running this program");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println(aie);
System.out.println("Please see that the array index is within the range");
}
finally
{
System.out.println("Close files");
}
}
}
Output:
javac Multiple.java
java Multiple
Open Files
n= 0
java.lang.ArithmeticException: / by zero
Please pass data while running this program
Close files
javac Multiple.java
java Multiple 10 20 30
Open Files
n= 3
a= 15
java.lang.ArrayIndexOutOfBoundsException: 50
Please see that the array index is within the range
Close files
183 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In this program, there is provision for two exceptions:
ArithmeticException: When no arguments are passed then division by zero. Hence an
exception is raised at runtime.
ArrayIndexOutOfBoundsException: Since we are creating an array b[ ] with 3 elements,
hence there are only 0,1 and 2 indices and there is no index like 50. But we are trying to store
100 in index 50 which leads to an exception.
These exceptions of handled by using two catch blocks. Observe the output. When we
didn’t pass any values while running this program, we got ArithmeticException and when we
pass some values, and then there is another exception called ArrayIndexOutOfBoundsException.
In Java SE 7 and later, a single catch block can handle more than one type of
exception. This feature can reduce code duplication.In the catch clause, specify the types of
exceptions that block can handle, and separate each exception type with a vertical bar (|) as:
Note:A Single try block can be followed by multiple catch blocks.Even though there is
possibility for several exceptions in try block, at a time only one exception will be raised and
hence only one catch block is executed.
throws Clause:
As discussed earlier there are two types of exceptions, the checked exceptions are the
exceptions which are checked at compilation time. If we don’t handle checked exceptions
compiler will display error message to avoid this, we should handle the checked exceptions or
we should throw them without handling. For this purpose we use “throws” statement.
“throwskeyword” is mainly used for handling checked exceptions. This can also be used to
handle multiple exceptions at a time.
184 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
When several exceptions are thrown out as shown in the above statement, we can simple
use “Exception”to represent several exceptions as:
Syntax: throws Exception;
Program: Write a program to understand how to throw an exception without handling it.
import java.io.*;
public class ThrowsDemo
{
static void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name:");
String name = br.readLine();
System.out.println("Hello "+name);
}
public static void main(String[] args) throws IOException
{
accept();
}
}
Output:
Enter your name:swetha
Hello swetha
In this program, the Java compiler expects the programmer to handle the IOException
given by readLine() using try catch block. But here, we are not handling the IOException. Since
it is a checked exception, we should throw it out of the method using throws clause as:
throws IOException
The throws clause is written at the side of accept() method since in this method the
readLine() is called. Also, we should write throws clause next to main() method since in this
method, the accept() is called, as shown here:
throw Clause:
There is also a throw statement available in Java to throw an exception explicitly and
catch it. We can throw either checked or unchecked exception in java by throw keyword. The
throw keyword is mainly used to throw user defined exception. We will see user defined
exceptions later. Consider the statement below:
Program: Write a program that shows the use of throw clause for throwing
NullPointerException.
class ThrowSample
{
static void demo()
{
try
{
System.out.println("inside Demo()");
throw new NullPointerException("Exception Data");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
public class ThrowDemo
{
public static void main(String[] args)
{
ThrowSample.demo();
}
}
Output:
inside Demo()
java.lang.NullPointerException: Exception Data
In this program, we are using throw NullPointerException class object. Then it is caught
and its details are displayed in catch block.
186 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Types of Exceptions:There are two types of exceptions. They are:
1) Built-in Exceptions
2) User-defined Exceptions
1. Built-in Exceptions:
Exception Class Meaning
Arithmetic Exception Thrown when an exceptional condition has occurred in
an arithmetic operation.
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed
with an illegal index. The index is either negative or
greater than or equal to the size of the array.
ClassNotFoundException This exception is raised when we try to access a close
whose definition is not found.
FileNotFoundException Raised when a file is not accessible or does not open.
IOException Thrown when an input-output operation failed or
interrupted.
NoSuchFieldException Thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException Thrown when accessing a method which is not found.
InterruptedException Thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
NullPointerException Raised when referring to the members of a null object
null represents nothing.
NumberFormatException Raised when a method could not convert a string into a
numeric format.
RuntimeException This represents any exception which occurs during
runtime.
StringIndexOutOfBoundsException Thrown by String class methods to indicate that an
index is either negative or greater than the size of the
string.
187 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2. User-defined Exceptions:
Similar to the exceptions already available in Java, the programmer can also create his
own exceptions. These exceptions are called user-defined exceptions. User defined
exceptions in java are also known as Custom exceptions.
a. Create user exception as a subclass to Exception class. Since all exceptions are subclasses
of Exception class, the programmer should also make his class a sub class to it as:
Example: class MyException extends Exception
b. The programmer can write a default constructor with empty body. It is not mandatory to
write default constructor with empty body. User can use it, if required.
c. Example: MyException()
{
}
d. The programmer can write a string parameterized constructor and call super class
constructor. He can use this to store exception details. He can call super class constructor
from this and send the string there.
Example: MyException(String str)
{
super(str);
}
e. To rise our own exception, we should create user exception class object and throw it
using throw statement
Example: MyException me = new MyException(“Exception Data”);
throw me;
188 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program to rise user-defined exception when the balance amount in
a bank account is less than 200 rupees.
public class MyException extends Exception
{
private static int accno[] = {1001,1002,1003,1004,1005};
private static String name[] = {"Sai","Bala","Balu","Sandeep","Naveen"};
private static double bal[] = {4500.00,6768.75,6799.99,1999.99,1200.50};
MyException()
{
}
MyException(String str)
{
super(str);
}
public static void main(String args[])
{
try
{
System.out.println("Accno\tName\tBalance");
for(int i=0;i<5;i++)
{
System.out.println(accno[i]+"\t"+name[i]+"\t"+bal[i]);
if(bal[i]<2000.00)
{
MyException me = new MyException("Balance amount is less");
throw me;
}
}
}
catch(MyException me)
{
System.out.println(me);
}
}
}
Output:
Accno Name Balance
1001 Sai 4500.0
1002 Bala 6768.75
1003 Balu 6799.99
1004 Sandeep 1999.99
fun.MyException: Balance amount is less
189 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Many internet applications receive data (like name, credit card number, address etc) from
users and send it to the server. According to W3C standards the data should be sent or receive on
a network in the form of objects only. In our data, ‘name’ is a String type object, but credit card
number is just an int type value, which is not an object. Hence, this primitive datatype should
also be converted into an object and then send to the server. To do this conversion we need
wrapper classes.
There is another reason why we need wrapper classes. In java, collection classes are
defined in java.util package which handle only objects, not the primitives. Hence, if we want to
use collection classes on primitives, we should convert them into objects.
Definition:
A wrapper classes is a class whose object wraps or contains a primitive data type. When
we create an object to a wrapper class, it contains a field. In this field, we can store a primitive
data type. (Or) We can wrap a primitive datatype in wrapper class object.
For Example: if we take Character class object, it contains one field of char primitive
datatype; in that field we can store a single character as shown in the figure below.
char A
Character Object
190 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Number Class:
Number is an abstract class whose subclasses are Byte, Short, Integer, Long, Float, and
Double. So the methods of Number class are commonly available in all these subclasses.
1) byte byteValue(): This method converts the calling object into byte value.
2) short shortValue(): This method converts the calling object into short value.
3) int intValue(): This method converts the calling object into int value.
4) long longValue(): This method converts the calling object into long value.
5) float floatValue(): This method converts the calling object into float value.
6) double doubleValue(): This method converts the calling object into double value.
Note: The calling object can be an object of Byte, Short, Integer, Long, Float, or Double class.
1. Character Class:
The Character class wraps a value of the primitive type char in an object. If we
create Character class object, it contains a char type field. In this field, we can store a
primitive char value like ‘A’.
191 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Constructor:
Character class has only one constructor which accepts primitive data type (char).
Character(char ch)
So, we can create Character class object and store ‘A’ there as:
Character obj = new Character(‘A’);
1) char charValue(): This method is useful to convert Character class object again into
primitive char value and returns that value.
2) int compareTo(Character obj): this method is useful to compare two Character
objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Character class objects.
If obj1 == obj2, then this method returns 0,
If obj1 < obj2, then it returns negative value,
If obj1 > obj2, the it returns positive value.
3) String toString(): This method converts Character object to String object and returns
that String object.
4) static Character valueOf(char ch):This method converts a single character ch into
Character object and returns that object.
5) static boolean isDigit(char ch): This method return true if ch is digit (0 to 9),
otherwise returns false.
6) static boolean isLetter(char ch): This method return true if ch is a letter (A to Z or a
to z), otherwise returns false.
7) static boolean isUpperCase(char ch): This method return true if ch is an upper case
letter (A to Z), otherwise returns false.
8) static boolean isLowerCase(char ch): This method return true if ch is a lower case
letter4 (a to z), otherwise returns false.
9) static boolean isSpaceChar(char ch): This method return true if ch represents a
space which is coming from spacebar.
192 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
10) static boolean isWhitespace(char ch): This method return true if ch represents a
white space. White space is a space that comes on pressing tab, enter, or backspace
buttons.
11) static boolean isLetterOrDigit(char ch): This method return true if ch is either a
letter or a digit.
12) static char toUpperCase(char ch): This method converts ch into uppercase and
returns that upper case letter.
13) static char toLowerCase(char ch): This method converts ch into lowercase and
returns that lower case letter.
Program: Write a program that accepts the Character from the keyboard and
displays its type.
import java.io.*;
public class CharTest
{
public static void main(String args[])throws IOException
{
char ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter a character: ");
ch=(char)br.read();
System.out.println("you entered");
if(Character.isDigit(ch))
System.out.println("A digit");
else if(Character.isUpperCase(ch))
System.out.println("An uppercase letter");
else if(Character.isLowerCase(ch))
System.out.println("A lowercase letter");
else if(Character.isSpaceChar(ch))
System.out.println("A Spacebar character");
else if(Character.isWhitespace(ch))
System.out.println("A whitespace Character");
else
System.out.println("Sorry I dnt know that");
return;
}
}
}
Output:
Enter a character: A
you entered
An uppercase letter
193 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2. Byte Class:
The Byte class wraps a value of the primitive type ‘byte’ in an object. The Byte class
contains a byte type field. In this field, we can store a primitive byte number.
Constructors:
Byte(byte num): This takes byte number as its parameter and converts it into Byte class
object.
For Example: Byte obj = new Byte(90);
Byte(String str): This takes String type Parameter and converts that into Byte Class
Object.
For Example: Byte obj = new Byte(“90”);
1) int compareTo(Byte b): This method is useful to compare the contents of two Byte
class objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Byte class objects.
If obj1 == obj2, then this method returns 0,
If obj1 < obj2, then it returns negative value,
If obj1 > obj2, then it returns positive value.
2) boolean equals(Object obj): This method compares the Byte object with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static byte parseByte(String str): This method returns the primitive byte number
contained in the String str.
4) String toString(): This methods converts Byte object into String object and returns
that String object.
5) static Byte valueOf(String str): This method converts a String str that contains some
byte number into Byte class object and returns that object.
6) static Byte valueOf(byte b): This method converts the primitive byte b into Byte
object.
194 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program which shows the use of Byte class objects.
import java.io.*;
public class ByteDemo
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Byte no:");
String s1=br.readLine();
Byte b1=new Byte(s1);
System.out.println("Enter a Byte no:");
String s2=br.readLine();
Byte b2=new Byte(s2);
int n=b1.compareTo(b2);
if(n==0)
System.out.println("Both bytes are same");
else if(n<0)
System.out.println(b1+" is less");
else
System.out.println(b2+" is less");
}
}
Output:
Enter a Byte no:90
Enter a Byte no:112
90 is less
3. Short Class:
The Short class wraps a value of the primitive type ‘short’ in an object. The Short class
contains a short type field. In this field, we can store a primitive short number.
Constructors:
Short(short num): This takes short number as its parameter and converts it into Short
class object.
For Example:Short obj = new Short (1500);
Short(String str): This takes String type Parameter and converts that into Short Class
Object.
For Example:Short obj = new Short (“1500”);
195 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
4. Integer Class:
The Integer class wraps a value of the primitive type ‘int’ in an object. The Integer class
contains a int type field. In this field, we can store a primitive int number.
Constructors:
Integer(int num): This takes integer number as its parameter and converts it into Integer
class object.
For Example: Integer obj = new Integer (999999);
Integer(String str): This takes String type Parameter and converts that into Integer Class
Object.
For Example: Integer obj = new Integer (“999999”);
196 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program an integer from keyboard and convert it into another
number system.
import java.io.*;
public class Convert
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Integer:");
String str=br.readLine();
int i=Integer.parseInt(str);
System.out.println("In decimal:"+i);
197 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
str=Integer.toBinaryString(i);
System.out.println("In binary:"+str);
str=Integer.toHexString(i);
System.out.println("In hexadecimal:"+str);
str=Integer.toOctalString(i);
System.out.println("In octal:"+str);
}
}
Output:
Enter a Integer:99
In decimal:99
In binary:1100011
In hexadecimal:63
In octal:143
5. Long Class:
The Long class wraps a value of the primitive type ‘long’ in an object. The Long class
contains a long type field. In this field, we can store a primitive long number.
Constructors:
Long(long num): This takes long number as its parameter and converts it into Long class
object.
For Example: Long obj = new Long (99999999);
Long(String str): This takes String type Parameter and converts that into Long Class
Object.
For Example: Long obj = new Long (“99999999”);
198 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) boolean equals(Object obj): This method compares the Long object with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static long parseLong(String str): This method returns long equivalent of the String
‘str’.
4) String toString():This methods converts Long object into String object and returns
that String object.
5) static Long valueOf(String str): This method converts a string str that contains
some long number into Long class object and returns that object.
6. Float Class:
The Float class wraps a value of the primitive type ‘float’ in an object. The Float class
contains a float type field. In this field, we can store a primitive float number.
Constructors:
Float(float num): This takes float number as its parameter and converts it into Float class
object.
For Example: Float obj = new Float (99.99f);
Float(String str): This takes String type Parameter and converts that into Float Class
Object.
For Example: Float obj = new Float (“99.99”);
199 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) boolean equals(Object obj): This method compares the Float object with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static float parseFloat(String str): This method returns float equivalent of the String
‘str’.
4) String toString():This methods converts Float object into String object and returns
that String object.
5) static Float valueOf(String str): This method converts a string str that contains
some float number into Float class object and returns that object.
7. Double Class:
The Double class wraps a value of the primitive type ‘double’ in an object. The
Doubleclass contains a doubletype field. In this field, we can store a primitive doublenumber.
Constructors:
Double(double num): This takes doublenumber as its parameter and converts it into
Doubleclass object.
For Example: Doubleobj = new Double(99.99f);
Double(String str): This takes String type Parameter and converts that into DoubleClass
Object.
For Example: Doubleobj = new Double(“99.99”);
200 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) boolean equals(Object obj): This method compares the Doubleobject with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static double parseDouble(String str): This method returns double equivalent of the
String ‘str’.
4) String toString():This methods converts Doubleobject into String object and returns
that String object.
5) static Double valueOf(String str): This method converts a string str that contains
some double number into Doubleclass object and returns that object.
8. Boolean Class:
The Boolean class wraps a value of the primitive type ‘boolean’ in an object. The
Booleanclass contains a booleantype field. In this field, we can store a primitive
booleanvalue.
Constructors:
Boolean(boolean num): This takes booleannumber as its parameter and converts it into
Booleanclass object.
For Example: Booleanobj = new Boolean(99.99f);
Boolean(String str): This takes String type Parameter and converts that into
BooleanClass Object.
For Example: Booleanobj = new Boolean(“99.99”);
Math Class:
The class Math contains for performing basic numeric operations, such as the elementary
exponential, logarithm, square root, and trigonometric methods. Note that all the methods of
Math class are ‘static’ and hence we need not create an object to Math class to call them.
1) static double sin(double arg): This method returns the sine value of the arg, where
arg is given in radians.
2) static double cos(double arg): This method returns the cosine value of arg, where
arg is given in radians.
3) static double tan(double arg): This method returns the tangent value of arg, where
arg is given in radians.
4) static double log(double arg): This method returns the natural logarithm value (base
e) of arg.
5) static double log10(double arg): This method returns the natural logarithm value
(base 10) of arg.
6) static double pow(double x, double n): This method returns the values of x to the
power n.
7) static double sqrt(double arg): This method returns the value of square root of arg.
8) static double abs(double arg): This method returns the absolute value of arg.
Absolute value represents the positive quantity of the given number.
202 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
9) static double ceil(double arg): This method raises the given arg value to the next
integer value. If integer is given to this method, it returns the same value.
10) static double floor(double arg): This method decreases the given arg value to the
previous integer value. If integer is given to this method, it returns the same value.
11) static double min(arg1, arg2): This method returns the minimum of arg1 and arg2.
12) static double max(arg1, arg2): This method returns the maximum of arg1 and arg2.
13) static longround(arg): This method returns the rounded value of arg. If the fraction
part is more or equal to 0.5, then 1 is added to the integer part; otherwise, the same
integer part is returned.
14) static double random(): This method returns a random number between 0 and 1. A
random number is a number that cannot be guessed by any one.
15) static double toRadians(double arg): This method converts the given arg value in
degrees to radians and returns arg in radians.
16) static double toDegrees(double arg): This method converts the given arg value in
radians to degrees and returns arg in degrees
Program: Write a program that generates random numbers repeatedly between ‘0’ and
‘10’. You need to also ensure that if the generated number is ‘0’ then program gets
terminated.
public class Random
{
public static void main(String args[]) throws Exception
{
System.out.println("Random numbers between 0 and 10: ");
while(true)
{
double d = 10*Math.random();
int i = (int)d;
System.out.print(i+” ”);
Thread.sleep(2000);
if(i==0)
{
System.exit(0);
}
}
}
}
Output:
Random numbers between 0 and 10:
313748168313397450
203 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q).What is boxing?
Answer:Converting a primitive datatype into an object is called ‘boxing’.
Q).What is unboxing?
Answer:Converting a object into its primitive datatype is called ‘unboxing’.
204 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Until now, we use arraysto store a group of elements or objects. But there are some
inconveniences in this mechanism. They are as follows:
We cannot store different class objects into the same array. The reason is that an array can
store only one data type of elements.
Adding the objects at the end of an array is easy. But, inserting and deleting the elements in
the middle of the array is difficult. In this case, we have to re-arrange all the elements of the
array.
Retrieving the elements from an array is easy but after retrieving the elements, if we want to
process them, then there are no methods available to carry out this.
Also arrays are not resizable.
Due to these problems, programmers want a better mechanism to store a group of objects.
The alternative is using an object to store a group of other objects. It means we can use a class
object as an array. Such an object is called ‘collection object’ or ‘container object’.
Collection Object:
A collection object or a container object is an object which can store a group of other
objects. In the figure below; we are storing 4 objects using a collection object. A collection
object has a class called ‘collection class’ or ‘container class’. All these classes are available in
java.util (util stands for utility) package. A group of collection objects is called ‘collection
framework’.
Objects
java.util
Collection class
Collection object
205 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Collection Framework:
1. Interfaces
2. Implementation classes
3. Algorithms: These are the methods that perform useful computations, such as searching,
sorting and etc.
In addition to collections, the framework defines several map interfaces and classes.
Although maps are not collections, they are fully integrated with collections.
Collection
<interface>
Stack LinkedList
HashSet LinkedHashSet
LinkedList
Map ArrayList
<interface>
Vector
HashMap<K,V> Hashtable<K,V>
All interfaces are marked with <interface> tag and other boxes represent classes.
extends implements
206 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In fact, collection object does not store the physical copies of other objects. Since the
other objects are already available in memory, storing another copy of them into the collection
object would be a more wasting of memory. So, JVM does not store copies of other objects, it
simply stores the references of other objects into a collection object.
There are 4 ways to retrieve any element from a collection object. They are:
1. for-each loop
2. Iterator interface
3. ListIterator interface
4. Enumeration interface
1. for-each loop:
for-each loop is like for loop which repeatedly executes a group of statements for
each element of the collection. The format is:
Syntax:for(variable: collection-object)
{
statements;
}
Here, the variable assumes each element of the collection-object and the loop is
executed as many times as there are number of elements in the collection-object. If
collection-object has n elements the loop is executed exactly n times and the variable stores
each element in each step.
2. Iterator interface:
Iterator is an interface that contains methods to retrieve the elements one by one
from a collection object. It has 3 methods:
boolean hasNext(): This method returns true if the Iterator has more elements.
element next(): This method returns the next element in the Iterator.
void remove(): This method removes from the collection the last element returned by the
Iterator.
207 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
3. ListIterator interface:
ListIterator is an interface that contains methods to retrieve the elements one by one
from a collection object, both in forward and reverse directions. It has the following
important methods:
boolean hasNext(): This method returns true if the ListIterator has more elements when
traversing in forward direction.
boolean hasPrevious(): This method returns true if the ListIterator has more elements
when traversing in reverse direction.
element next(): This method returns the next element in the list.
element previous(): This method returns the previous element in the list.
void remove(): This method removes from the list the last element returned by the
next() or previous() methods.
4. Enumeration interface:
This interface is useful to retrieve one by one element like the Iterator. It has 2
methods:
Sets:
A set represents a group of elements arranged just like an array. The set will grow
dynamically when the elements are stored into it. A set will not allow duplicate elements. If we
try to pass the same element that is already available in the set, then it is not stored into the set.
Set has mainly two types of classes. They are:
a. HashSet Class
b. LinkedHashSet Class
208 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
a. HashSet Class:
A HashSet represents a set of elements (objects). It does not guarantee the order of
elements. Also it does not allow the duplicate elements to be stored. HashSet allows null
values however if you insert more than one nulls it would still return only one null value. We
can write HashSet class as: class HashSet<T>
Here, <T> represents the generic type parameter. It represents which typeof
elements are being stored into the HashSet.
The preceding statement constructs aHashSet which stores String type objects.
We can also mention the capacity at the time of creating ArrayList object as:
1) boolean add(obj): This method adds an element obj to the HashSet. It returns true if
the element is added to the HashSet, else it returns false. If the same element is
already available in the HashSet, then the present element is not added.
2) void clear():This removes all the elements from the HashSet.
3) boolean remove(obj):This method removes the element obj from the HashSet, if it is
present. It returns true if the element is removed successfully otherwise false.
209 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
4) boolean contains(obj):This returns true if the HashSet contains the specified element
(obj) else returns false.
5) boolean isEmpty():This returns true if HashSet contains no elements.
Program: Write a program which shows the use of HashSet and Iterator.
import java.util.*;
public class HS
{
public static void main(String[] args)
{
HashSet<String> hs=new HashSet<String>();
hs.add("India");
hs.add("America");
hs.add("Japan");
hs.add("China");
System.out.println("Hash Set="+hs);
Iterator it=hs.iterator();
System.out.println("Elements using Iterator:");
while(it.hasNext())
{
System.out.println((String)it.next());
}
}
}
Output:
Hash Set=[America, China, Japan, India]
Elements using Iterator:
America
China
Japan
India
b. LinkedHashSet Class:
210 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program which shows the difference between HashSet and
LinkedHashSet based on the order in which elements are stored in them.
import java.util.*;
public class DiffSet
{
public static void main(String[] args)
{
HashSet<String> hs=new HashSet<String>();
hs.add("India");
hs.add("America");
hs.add("Japan");
hs.add("China");
LinkedHashSet<String> lhs=new LinkedHashSet<String>();
lhs.add("India");
lhs.add("America");
lhs.add("Japan");
lhs.add("China");
System.out.println("HashSet: "+hs);
System.out.println("LinkedHashSet: "+lhs);
}
}
Output:
HashSet: [America, China, Japan, India]
LinkedHashSet: [India, America, Japan, China]
Lists:
Lists are like sets. They store a group of elements. Despite sets, lists allow duplicate
values to be stored. Lists have mainly four types of classes. They are:
a. Stack
b. LinkedList
c. ArrayList
d. Vector
a. Stack:
A stack represents group of elements stored in LIFO (Last In First Out) order. This
means that the element which is stored as the last element into the stack will be the first
element to be removed from the stack. The following are the operations of stack:
211 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Inserting and deleting from the stack is done only from one side of the stack, called
“top” of the stack, as shown in the figure.
push
A pile of plates in a cafeteria where the lastly
pop
washed plate will be coming out first can be taken as an top 50
example for a stack. Similarly Disk holder where the
400
CDs are arranged such that the last CD is available first.
We can write Stack class as: 300
class Stack<E>
200
//E stands for type of elements stored in Stack object.
100
Suppose, we want to create a Stack object that contains Integer objects, we can do
so as shown here:
a. boolean empty(): This method checks whether the stack is empty or not. If the
stack is empty then true is returned otherwise false.
b. element peek(): This method returns top most element from the stack without
removing it.
c. element pop(): This method removes top most element from the stack and returns
it.
d. element push(obj): This method pushes a element obj on to the top of the stack
and returns that element.
e. int search(obj): This method returns position of an element obj. If the element is
not found in the stack then it returns -1.
212 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
213 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In the above program, ‘st’ is the stack object where we want to store some integer
elements. Since int is a primitive datatype, we should convert it into Integer object and then
store into the stack. Consider the statement below:
st.push (element);
Here, we passed int type element to push() method. But the method automatically
converts it into Integer object and then stores it into the stack “st”. This is called ‘auto
boxing’.
b. LinkedList class:
Node
A linked list
Linked list is very convenient to store data. Inserting the elements into the linked list
and removing the elements from the linked list is done quickly and takes the same amount of
time. A linked list class can be written as:
We can create an empty linked list for storing String type elements (objects) as:
214 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
a. boolean add(obj):This method adds an element obj to the linked list. It returns
true if the element is added successfully. (Appends the specified element to the end
of this list similar to addLast() method).
b. void add(int i, obj): This method inserts an element obj into the linked list at a
specified position ‘i’.
c. void addFirst(int i, obj): This method adds the element obj at the first position of
the linked list.
d. void addLast(int i, obj): This method appends the specified element to the end of
list.
e. element removeFirst():This method removes the first element from the list and
returns it.
f. element removeLast(): This method removes the last element from the list and
returns it.
g. element remove(int i): This removes an element at the specified position “i” in
the linked list.
h. void clear(): This method removes all the elements from the linked list.
i. element get(int i):This method returns the element at the specified position “i” in
the linked list.
j. element getFirst():This method returns the first element from the list.
k. element getLast(): This method returns the last element from the list.
215 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
l. element set(int i, obj):This method replaces the element at the specified position
in the list with the specified element obj.
m. int size(): This method returns number of elements in the linked list.
n. int indexOf(obj): This method returns the index of the first occurrence of the
specified element in the list, or -1 if the list does not contain the element.
o. int lastIndexOf(obj): This method returns the index of the last occurrence of the
specified element in the list, or -1 if the list does not contain the element.
p. Object[] toArray(): This method converts the linked list into an array of Object
class type. All the elements of the linked list will be stored the array in the same
sequence.
216 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
break;
case 2:
System.out.println("Enter position:");
position = Integer.parseInt(br.readLine());
ll.remove(position - 1);
break;
case 3:
System.out.println("Enter position:");
position = Integer.parseInt(br.readLine());
System.out.println("Which element:");
element = br.readLine();
ll.set(position - 1, element);
break;
default:
return;
}
System.out.println("List=");
Iterator it=ll.iterator();
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
}
Output:
c. ArrayList class:
An ArrayList is like an array, which can grow in memory dynamically. It means that
when we store elements into the ArrayList, depending on the number of elements, the
memory is dynamically allotted and re-allotted to accommodate all the elements. Hence,
ArrayList is also called resizable-array implementation of the List interface.
217 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
ArrayList is not synchronized. This means that when more than on thread acts
simultaneously on the ArrayList object, the results may be incorrect in some cases. The
ArrayList class can be written as:
1) boolean add(obj):This method appends the specified element to the end of the
ArrayList. If the element is added successfully then the preceding method return true.
2) void add(int i, obj): This method inserts the specified element at the specified
position, “i” in the ArrayList.
3) element remove(int i): This method removes the element at the specified position,
”i” in the ArrayList. This method also returns the element which was removed from
the ArrayList.
4) boolean remove(obj): This method removes the first occurrence of the specified
element obj from the ArrayList, if it is present.
5) void clear(): This method removes all the elements from the ArrayList.
6) element set(int i, obj): This method replaces an element at the specified position, ”i”
in the ArrayList with specified element obj.
7) boolean contains(obj): This method returns true if the ArrayList contains specified
element obj.
8) element get(int i): This method returns the element available at the specified position
in the ArrayList.
218 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
9) int indexOf(obj): This method returns the position of first occurrence of the specified
element obj in the ArrayList, or -1 if the element is not found in the list.
10) int lastIndexOf(obj): This method returns the position of last occurrence of the
specified element obj in the ArrayList, or -1 if the element is not found in the list.
11) int size(): This method returns the number of elements present in the list.
12) Object[ ] toArray(): This method returns an object class type array containing all the
elements in the ArrayList in proper sequence.
Program: Write a program to create an ArrayList with Strings and perform various
operations on it.
import java.util.*;
public class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> arl=new ArrayList<String>();
arl.add("Apple");
arl.add("Mango");
arl.add("Grapes");
arl.add("Guava");
System.out.println("Contents:"+arl);
arl.remove(3);
arl.remove("Apple");
System.out.println("Contents:"+arl);
System.out.println("Size of ArrayList:"+arl.size());
System.out.println("Extracting using Iterator:");
Iterator it=arl.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
Contents:[Apple, Mango, Grapes, Guava]
Contents:[Mango, Grapes]
Size of ArrayList:2
Extracting using Iterator:
Mango
Grapes
219 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
d. Vector class:
The Vector class implements a growable array of objects. Similar to ArrayList, but
vector is synchronized which means it is suitable for thread-safe operations (It means even if
several threads act on Vector object simultaneously, the results will be reliable.) but it gives
poor performance when used in multi-thread environment.
The preceding statement creates a Vector object v which can be used to store
Float type objects. The default capacity will be 10.
The preceding statement creates a Vector object v which can be used to store
Integer type objects. The capacity of Vector is given as 200. Another way of creating an
object for Vector is by specifying a ‘capacity increment’ which specifies how much the
capacity should be incremented when the Vector is full with elements.
Here, 200 is the capacity of the Vector and capacity increment is 50. If the
Vector is full with elements; the capacity automatically goes to 250.
220 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
1) boolean add(obj):This method appends the specified element to the end of the
Vector. If the element is added successfully then the preceding method return true.
2) void add(int i, obj): This method inserts the specified element at the specified
position, “i” in the Vector.
3) element remove(int i): This method removes the element at the specified position,
”i” in the Vector. This method also returns the element which was removed from the
ArrayList.
4) boolean remove(obj): This method removes the first occurrence of the specified
element obj from the Vector, if it is present.
5) void clear(): This method removes all the elements from the Vector.
6) element set(int i, obj): This method replaces an element at the specified position, ”i”
in the Vector with specified element obj.
7) boolean contains(obj): This method returns true if the Vector contains specified
element obj.
8) element get(int i): This method returns the element available at the specified position
in the Vector.
9) int indexOf(obj): This method returns the position of first occurrence of the specified
element obj in the Vector, or -1 if the element is not found in the list.
10) int lastIndexOf(obj): This method returns the position of last occurrence of the
specified element obj in the Vector, or -1 if the element is not found in the list.
11) int size(): This method returns the number of elements present in the Vector.
12) int capacity(): This method returns current capacity of the Vector.
13) Object[ ] toArray(): This method returns an object class type array containing all the
elements in the Vector in proper sequence.
221 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
for(int i=0;i<v.size();i++)
{
System.out.println(v.get(i));
}
System.out.println("Elements using list iterator:");
ListIterator lit=v.listIterator();
System.out.println("(In forward direction:");
while(lit.hasNext())
{
System.out.print(lit.next()+"\t");
}
System.out.println("\nIn backward direction:");
while(lit.hasPrevious())
{
System.out.print(lit.previous()+"\t");
}
}
}
Output:
vector elements:
99
90
88
80
77
70
Elements using list iterator:
(In forward direction:
99 90 88 80 77 70
In backward direction:
70 77 80 88 90 99
222 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Queues:
A queue represents arrangement of elements in FIFO (First In First Out) order. This
means that an element that is stored as a first element into the queue will be removed first from
the queue.A Queue is a collection for holding elements prior to processing. Besides
basic Collection operations, queues provide additional insertion, removal, and inspection
operations. Queueinterface can be written as:
Queue Interface
Structure
Type of Throws Returns special value
Operation exception (null or false)
The head of the queue is where the element is removed by a calling either remove() or poll()
methods.
The tail of the queue is where the element is inserted by calling either add(obj) or offer(obj)
method.
223 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Insertion:
The add(obj) method, which Queue inherits from Collection, inserts an element unless it
would violate the queue's capacity restrictions, in which case it throws IllegalStateException.
The offer(obj) method, which is used on bounded queues. It differs from add(obj) only in the
case that it returns false, when insertion failed.
Removal:
The remove() and poll() methods both remove and return the head of the queue.
The remove() and poll() methods differ in their behavior only when the queue is empty. Under
these circumstances:
Examine (Searching):
The element() and peek() methods return, but do not remove, the head of the queue.
The element() and peek() methods differ in their behavior only when the queue is empty. Under
these circumstances:
a. LinkedList:
224 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Maps:
Maps store elements in the form of key and value pairs.A key is an object that you use
to retrieve a value at a later date.Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by using its key.Map interface can be written
as: public interface Map<K, V>
Where, K is the type of key maintained by this map, V is the type of mapped value. Maps have
mainly two types of classes. They are:
a. HashMap Class
b. Hashtable Class
a. HashMap Class
HashMap is a Map based collection class that is used for storing Key & value pairs.
This class makes no guarantees as to the order of the map. Keys should be unique. This
means we cannot use duplicate data for keys in the HashMap. HashMap is not synchronized
and hence while using multiple threads on HashMap object, we may get unreliable results.
HashMap may permit null keys and values. HashMap class can be written as:
class HashMap<K, V>// K is type of keys and v is type of values allowed in HashMap.
Here, to store String objects as keys and integer objects as its values, we create
the HashMap object asshown above. We did not mention any capacity for the HashMap.
Hence, the default capacity of this HashMap will be taken as 16 and the load factor as
0.75. Load factor represents at what level this HashMap capacity should be doubled.
For example: capacity * load factor = 16 * 0.75
= 12.
This represents that after storing the 12th key-value pair into the HashMap, its
capacity will become 32.
225 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The preceding statement creates a HashMap object (hm) which can be used to
store String type keys and Integer type values. The initial capacity of HashMap object
(hm) is declared as 60.
The preceding statement creates a HashMap object (hm) which can be used to
store String type keys and Integer type values. The initial capacity of HashMap object
(hm) is declared as 60 and the load factor as 0.5.
1) value put(key, value):This method stores key-value pair into the HashMap object.
2) value get(key): This method returns the corresponding value when key is given. If
the key does not have a value associated with it, then it returns null.
3) Set<K> keyset(): This method, when applied on HashMap converts it into a Set
where only keys will be stored.
4) Collection<V> values(): This method, when applied on HashMap object returns all
the values of the HashMap into a Collection object.
5) value remove(key): This method removes the key and corresponding value from the
HashMap.
6) void clear(): This method removes all the key-value pairs from the map.
7) boolean isEmpty(): This method returns true if there are no key-value pairs in the
HashMap.
8) int size(): This method returns the number of key-value pairs in the HashMap.
226 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
b. Hashtable Class
Hashtable is similar to HashMap which can store elements in the form of key-value
pairs. The only difference between Hashtable and HashMap is that, Hashtable is
synchronized assuring proper results even if multiple threads act on it simultaneously where
as HashMap is not synchronized. We can write Hashtable class as:
class Hashtable<K, V> // K is type of keys and V is type of values allowed in Hashtable.
Here, to store String objects as keys and integer objects as its values, we create
the Hashtable object asshown above. We did not mention any capacity for the Hashtable.
Hence, the default capacity of this HashMap will be taken as 11 and the load factor as
0.75. Load factor represents at what level this HashMap capacity should be doubled.
For example: capacity * load factor = 11 * 0.75
= 8.25.
This represents that after storing the 8th key-value pair into the HashMap, its
capacity will become 22.
The preceding statement creates a Hashtable object (ht) which can be used to
store String type keys and Integer type values. The initial capacity of Hashtable object
(ht) is declared as 60.
The preceding statement creates a Hashtable object (ht) which can be used to
store String type keys and Integer type values. The initial capacity of Hashtable object
(ht) is declared as 60 and the load factor as 0.5.
228 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
1) value put(key, value):This method stores key-value pair into the Hashtable object.
2) value get(key): This method returns the corresponding value when key is given. If
the key does not have a value associated with it, then it returns null.
3) Set<K> keyset(): This method, when applied on Hashtable converts it into a Set
where only keys will be stored.
4) Collection<V> values(): This method, when applied on Hashtable object returns all
the values of the Hashtable into a Collection object.
5) value remove(key): This method removes the key and corresponding value from the
Hashtable.
6) void clear(): This method removes all the key-value pairs from Hashtable.
7) boolean isEmpty(): This method returns true if there are no key-value pairs.
8) int size(): This method returns the number of key-value pairs in the Hashtable.
9) Enumeration keys(): This method returns all the keys of the Hashtable into an
Enumeration object.
Output:
The Player names:
Ajay
Dhoni
Sachin
Gavaskar
Kapil
Enter Player name:Dhoni
Dhoni Scored: 88
Arrays Class:
Array class provides methods to perform certain operations on any one dimensional
array. This class contains various methods for manipulating arrays (such as sorting and
searching). All the methods of the Arrays class are static, so they can be called in the form of:
Arrays.methodName()
1) void sort(array):This method sorts all the elements of an array into ascending order.
This method internally uses QuickSort algorithm.
2) void sort(array, int i, int j): This method sorts all the elements in the range from ‘i’ to
‘j’ within an array into ascending order.
3) int binarySearch(array, element):This method searches for an element in the array and
returns its position number. If the element is not found in the array then it returns
negative value. This method works only when the array is in ascending order.
4) boolean equals(array1, array2): This method returns true if two arrays, array1 and
array2 are equal, otherwise false.
5) array copyOf(array1, int n): This method copies n elements from the array1 into
another array and returns an array.
6) void fill(array, value): This method fills the array with the specified value. It means that
all the elements in the array will receive that value.
230 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output:
Enter an Integer: 99
Enter an Integer: 111
Enter an Integer: 22
Enter an Integer: 88
Enter an Integer: 55
231 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
StringTokenizer Class:
StringTokenizer class is useful to break a string into pieces, called ‘tokens’. These tokens
are then stored in the StringTokenizer object from where they can be retrieved.
In the preceding statement, the actual String ‘str’ is broken into pieces at the positions
marked by a group of characters, called ‘delimiter’. For example:
In the preceding statement, the delimiter is not specified. Hence the “space” is
considered as default delimiter.
1) int countTokens(): This method counts and returns the number of tokens available in a
StringTokenizer object.
2) boolean hasMoreTokens(): This method tests if there are more tokens available in the
StringTokenizer object or not. If next token exists then it returns true else it returns false.
3) String nextToken(): This method returns next token from the StringTokenizer.
232 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output:
Given String 1: Hello,World
The Tokens for String 1 are:
Hello
World
233 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Calendar Class:
The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields. Calendar class
is useful in two ways:
Calendar cl = Calendar.getIntance();
Output:
Current date:3-2-2016
Current time:2-24-9
235 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q).What is the difference between Stack and LinkedList?
Answer:
A Stack is generally used for the purpose of evaluation of expressions. A LinkedList is
used to store and retrieve data.
Insertion and deletion of elements only from the top of the Stack is possible. Insertion
and deletion of elements from anywhere is possible in case of a LinkedList.
236 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Once a file is created the data of the file can be shared by various programs to display
various reports.
To create a file in java we need “Streams”. A stream represents flow of data from one
place to another place. Just like a water pipe carries water, a stream carries data from one place
to another place.
To write data into a file we need a stream, similarly to read data from a file we need a
stream. There are two types of streams.
1. InputStreams: It is useful to read or accept data coming from an input device or a file.
2. OutputStreams: It is useful to store or write data to an output device or to a file.
1. Text Streams: A text stream is also called character stream, text stream store data and
retrieve data in the form of characters. Text streams are useful to create text files.
2. Byte Streams: Byte represents data in the form of individual bits and bytes, they are
suitable to create text files and also to store images.
InputStream OutputStream
237 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
238 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output:
Program: write a program to open a file and read data from the file.
import java.io.*;
class Read
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("myfile.txt");
int ch;
while((ch=fr.read())!=-1)
{
System.out.print((char)ch);
}
fr.close();
}
}
Output:
239 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
fw.write(char);
Here, we call write() method on ‘fw’ which is FileWriter object, to write a character
(char) into the file. Here, the FileWriter is invoked to write character into the file.
Let us estimate how much time it takes to read 10 characters from the keyboard and write
all of them into a file.
fw
1 sec 1 sec
keyboard File
FileWriter stream reads one character from the keyboard and stores that character into the
file. Let us assume to read one character from keyboard, it will take 1second time and to write
that character into file it takes another 1 second in this way to store 10 characters it will take 20
seconds time.
To improve the speed of reading and writing operations, buffered classes are highly
useful. Java soft people have provided the following buffered classes.
1. BufferedReader
2. BufferedWriter
3. BufferedOutputStream
4. BufferedInputStream
Buffered classes use a buffer which represents a memory block via reading and writing
operations are performed. They fill the buffer with data and then perform reading or writing in a
single step. Buffered classes should be used with other streams.
240 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
bw
10 fw
1 sec 1 sec
keyboard File
Here, the BufferedReader size is declared as 1024 bytes. If the buffer size is not
specified, then a default buffer size of 512 bytes is used.
Answer: Buffered classes improve the speed of reading or writing operations by using a
buffer.
241 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Byte Streams:
1. Attach a FileOutputStream to a file to write some bytes into it.
FileOutputStream fos=new FileOutputStream(“myfile.txt”);
For append mode.
FileOutputStream fos=new FileOutputStream(“myfile.txt”, true);
2. To write a single character into the file.
fos.write(char);
3. To close the file.
fos.close();
4. Attach FileInputStream to read bytes from a file.
FileInputStream fis=new FileInputStream(“myfile.txt”);
5. To read a character and return it as an integer.
fis.read();
if this method fails then it returns -1.
6. To close the file.
fis.close();
Program: Write a java program to copy an image file bit by bit as a new image.
import java.io.*;
class Copy
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("Penguins.jpg");
FileOutputStream fos=new FileOutputStream("new.jpg");
int ch;
while((ch=fis.read())!=-1)
{
fos.write(ch);
}
fis.close();
fos.close();
}
}
Output:
It will creates a jpg image same as Penguins.jpg
242 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To decrease the size of a file, we should compress the file using softwares like “winzip,
pkzip, winrar”. These softwares use a zipping algorithm that will replace the original bit pattern
with lesser number of bits.
1. The size of the compressed file will be lesser than the original file and the original data is
replaced by lesser number of bits.
2. When a file is uncompressed unzipping algorithm will substitute the original bit pattern
in the place of lesser bits, so we will get back original file from the compressed file.
243 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
import java.io.*;
import java.util.zip.*;
class Zip
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("Myfile.txt");
FileOutputStream fos=new FileOutputStream("new.txt");
DeflaterOutputStream dos=new DeflaterOutputStream(fos);
int ch;
while((ch=fis.read())!=-1)
{
dos.write(ch);
}
dos.close();
fis.close();
}
}
Program: write a java program to get original from by uncompressing the zipped file.
import java.io.*;
import java.util.zip.*;
class Unzip
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("new.txt");
FileOutputStream fos=new FileOutputStream("file3.txt");
InflaterInputStream iis=new InflaterInputStream(fis);
int ch;
while((ch=iis.read())!=-1)
{
fos.write(ch);
}
iis.close();
fos.close();
}
}
In this program we take the compressed file ‘new.txt’ from where data is read and
uncompressed by InflaterInputStream. The output of this program is ‘file3.txt’ which contains
the original uncompressed data.
File class:
File class of java.io package provides some methods to know the properties of a file or a
directory. File class object can store a file name or a directory name.
File f=new File(filaname);
File f=new File(directoryname);
File f=new File(“path”,filename);
File f=new File(“path”,directoryname);
Here, f contains file name or directory name.
245 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
246 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: write a program to accept a file/ directory name and display the properties of file
or the contents of the directory.
import java.io.*;
publicclass FileProp
{
publicstaticvoid main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter dirpath:");
String dirpath=br.readLine();
System.out.println("Enter file name/ directory name:");
String fname=br.readLine();
File f=new File(dirpath,fname);
if(f.exists())
{
if(f.isFile())
{
System.out.println("Size of the file:"+f.length());
System.out.println("Parent directory:"+f.getParent());
System.out.println("Is writable:"+f.canWrite());
System.out.println("Is readable:"+f.canRead());
}
else
{
String s[]=f.list();
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
}
}
else
{
System.out.println("Does not exist");
}
}
}
Output:
247 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program which accepts a filename from command line argument and
displays the number of characters, words, and lines in the file.
import java.io.*;
public class Count
{
public static void main(String args[])throws IOException
{
int ch;
boolean prev = true;
int char_count = 0;
int word_count = 0;
int line_count = 0;
FileInputStream fin = new FileInputStream(args[0]);
while((ch=fin.read())!=-1)
{
if(ch!=' ')
++char_count;
if(!prev && ch ==' ')
++word_count;
if(ch==' ')
prev = true;
else
prev = false;
if(ch == '\n')
++line_count;
}
char_count -=line_count*2;
word_count += line_count;
System.out.println("No. of Characters: "+ char_count);
System.out.println("No. of Words: "+word_count);
System.out.println("No. of line: "+line_count);
fin.close();
}
}
Output:
javac Count.java
java Count java.txt
No. of Characters: 356
No. of Words: 73
No. of line: 3
248 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Threads
A thread represents flow of executing (or controlling) a group of statements. In java
program, if we write a group of statements, then these statements are executed by JVM one by
one. This execution is called Thread, because JVM uses a thread to execute these statements. It
occupies less memory space. So that is can be treated as “light-weight” process.
Program: Write a program to find the thread used by JVM to execute the statements.
public class Current
{
public static void main(String args[])
{
System.out.println("The current thread used by JVM:");
Thread t = Thread.currentThread();
System.out.println("Current thread= "+t);
System.out.println("Its name= "+t.getName());
}
}
Output:
The current thread used by JVM:
Current thread= Thread[main,5,main]
Its name= main
249 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Here, currentThread() is the static method and hence we call it directly as:
Thread.currentThread(). getName() is the method of Thread class, which gives the name of the
thread object that called it.
A thread represents execution of statements. The way the statements are executed is of two
ways. They are:
1. Single tasking
2. Multi tasking
1. Single Tasking:
A task means doing some calculations, processing etc. Generally, a task involves
execution of a group of statements. In single tasking environment, only one task is given to
the processor at a time.
Processor
jobs
time
The main disadvantage with single tasking is that it consumes more time. This means
we are wasting a lot of processor time and microprocessor has to sit idle without any job for a
long time.
2. Multi Tasking:
Whenever multiple operations performed simultaneously on a single processor is
called as “Multi Tasking”. The main advantage of multi tasking is that the processor time is
used in a better way and we can complete several tasks at a time. We are engaging most of
the processor time and it is not sitting idle. In this way, the performance will be increased and
time consumption is reduced. Multi tasking is of two types. They are:
250 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Process based multi tasking: The process of achieving multi tasking by executing multiple
programs simultaneously is known as “Process based multi tasking”. For example: playing of
audio files and playing of games can be executed simultaneously is an example for process based
multi tasking.
Processor
¼ milliseconds
1 2 3 4
Memory
Thread based multi tasking: The process of achieving multi tasking by executing multiple
threads (i.e., multiple parts of same program)simultaneously is known as “Process based multi
tasking”. For example: playing of audio files and playing of games can be executed
simultaneously is an example for process based multi tasking.
thread 1
task 1
Processor
thread 2
task 2
251 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Yield
start Not
New Thread Runnable
Runnable
sleep()
wait()
If run() terminates Blocked on I/O
Dead
252 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Step 2: In this class we write a run() method as below. By default this run() method is
recognized and executed by a thread.
Step 4: Now, create a thread and attach thread to the object (obj) as:
Step 5: Run the thread, for this purpose we should use tha start() method of thread class:
Syntax: t.start();
Now, the thread will start execution on the object of MyClass. In that object, run()
method is found. Hence it will execute the statements inside that run() method.
253 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program 1: Write a program to create MyThread class with run() method and then
attach a thread to this MyThread class object.
public class Demo {
public static void main(String args[])
{
MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start();
}
}
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=100;i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
.
.
.
100
A thread will terminate automatically when it comes out of run() method. To terminate
the thread on our own, then follow the following steps:
254 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program 2: Write a program to show how to terminate thread by pressing enter key.
public class Demo {
public static void main(String args[])
{
MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start();
}
}
Output:
1
255 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2
3
.
.
.
100
Thread priorities
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependent.
Default Priority: Normal Priority : 5
Program 3: Write a program to to get name and priority of a thread.
class tpclass1 extends Thread
{
public void run()
{
System.out.println("Thread Name = " + getName());
System.out.println("Thread Priority = " + getPriority());
}
}
class Priority1
{
public static void main(String args[])
{
tpclass1 t=new tpclass1();
t.start();
}
}
Output
Thread Name = Thread-0
256 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Thread Priority = 5
Changing priorities
Program 4: Write a java program to change priorities of a thread
class tpclass2 extends Thread
{
int i=1;
public void run()
{
while(true)
{
if(i%2==0)
System.out.println("Thread Name = " + getName() + " " + i);
System.out.println("Thread Priority = " + getPriority());
i++;
}
}
}
class pclass2 extends Thread
{
int i=1;
public void run()
{
while(true)
{
if(i%2==1)
System.out.println("Thread Name = " + getName() + " " + i);
System.out.println("Thread Priority = " + getPriority());
i++;
}
}
}
class Priority2
{
public static void main(String args[])
{
tpclass2 t=new tpclass2();
257 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
pclass2 p=new pclass2();
t.start();
p.start();
t.setPriority(10);
p.setPriority(1);
}
}
Output
Thread Priority = 10
Thread Name = Thread-1 1
Thread Name = Thread-0 2
Thread Priority = 1
Thread Priority = 10
Thread Priority = 1
Thread Priority = 10
Thread Name = Thread-1 3
Thread Name = Thread-0 4
Thread Priority = 1
Thread Priority = 10
Thread Priority = 1
Thread Priority = 10
Thread Name = Thread-1 5
Thread Name = Thread-0 6
Thread Priority = 1
Thread Priority = 10
Thread Priority = 10
Thread Name = Thread-0 8
Thread Priority = 10
.
.
.
Synchronization
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen result
due to concurrency issue. For example if multiple threads try to write within a same file then
258 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
they may corrupt the data because one of the threads can override data or while one thread is
opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block.
Following is the general form of the synchronized statement:
Program 5: Write a program for Synchronization Block
class Share extends Thread
{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname)
{
super(threadname);
}
public void run()
{
display(getName());
}
public void display(String threadN)
{
synchronized(this)
{
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try
{
this.sleep(1000);
}
catch(Exception e)
{
}
}
259 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
}
}
public class SynStatement
{
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}
Output
Thread Two: This
Thread Two: is
Thread Two: a
Thread Two: synchronized
Thread Two: variable
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized
Thread One: variable
InterThreadCommunication
Java provides a very efficient way through which multiple-threads can communicate with
each-other. This way reduces the CPU?s idle time i.e. A process where, a thread is paused
running in its critical region and another thread is allowed to enter (or lock) in the same critical
section to be executed. This technique is known as Inter thread communication which is
implemented by some methods. These methods are defined in "java.lang" package and can only
be called within synchronized code shown as:
Method Description
It indicates the calling thread to give up the monitor and go to
wait( ) sleep until some other thread enters the same monitor and calls
method notify() or notifyAll().
260 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
262 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos)throws InterruptedException
Program 7: Write a program for sleep() method.
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
output
1
1
2
2
3
3
4
4
264 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
B:2
A:3
B:4
B:6
A:5
B:8
A:7
B : 10
A:9
yield() Method:
When you want to stop current thread and switch the CPU availability to another thread,
call yield() method of Thread.
public static void yield() - This method pauses the execution of current running thread and
permits the other threads to execute.
Program 9: Write a program for yield() method
public class ThreadYield implements Runnable {
Thread thread;
public ThreadYield(String name) {
thread = new Thread(this, name);
thread.start();
}
265 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output :
Thread 1 is going to call yield() method...
Thread 2 is going to call yield() method...
Thread 1 is completed.
Thread 2 is completed.
Join Method
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Program 10: Write a program for join() method.
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
Output
266 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
267 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Networking:
Interconnection between two systems is called networking. (or) Connecting two or more
systems together is called networking. The main advantage with networking is resource sharing
of data on multiple computers.
In networking there may be several computers, some of them receiving the services and
some providing the services to others. The computer which receives service is called a ‘client’
and the computers which provide the service is called a ‘server’. Sometimes the client acts as a
server and a server acts as a client.
If any application is depends on client and server systems then that network is called as
client-server architecture or request-response architecture.
Request
Client Server
Response
Client-server architecture
Note: When the computer is not connected in a network it is called individual computer. In this
case we should use “localhost” in the place of “servers-ipaddress”. “localhost” represents that the
server is available in the same machine.
Socket:
Each socket is given an identification number, which is called ‘port number’. Port
number takes 2 bytes and can be form 0 to 65535.
269 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Socket programming is done in java using the classes and interfaces of “java.net’
package.
A socket at server side is called ‘ServerSocket’, and is created using ‘ServerSocket’ class.
A socket at client side is called ‘Socket’, and is created using ‘Socket’ class.
Both the ServerSocket and Socket classes are available in “java.net” package.
Any client system can send the input values by writing data, server receives by reading data.
Server system can send output values by writing data, client receives by reading data. Those
writing and reading operations can be done with the help of OutputStream and InputStream
classes respectively.
Request
i/p value write read
Client Server
1. At server side create a ServerSocket object with some port number, this is done using
ServerSocket class as:
ServerSocket ss=new ServerSocket(“portno”);
2. Now we should make the server wait till he client accepts connection, this is done using
accept( ) method.
Socket s=ss.accept();
3. To receive data from client, connect InputStream to the Socket.
InputStream is=s.getInputStream();
4. Perform some operations by writing some business logic based on client request.
5. To send data to the client, connect the OutputStream to the Socket.
OutputStream os=s.getOutputStream();
6. Close or terminate the connections. This can be done by closing all the streams and
sockets at server side.
270 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: Write a program to create a server for the purpose of finding square value to the client
request.
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args)
{
try
{
int portno=Integer.parseInt(args[0]);
ServerSocket ss=new ServerSocket(portno);
Socket s=ss.accept();
InputStream is=s.getInputStream();
int req=is.read();
int res=req*req;
OutputStream os=s.getOutputStream();
os.write(res);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
C:/>javac Server.java
C:/>
Do not run this program till client is also created. Once client is created and compiled then run
this program as.
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args)
{
try
{
String ipaddress=args[0];
int portno=Integer.parseInt(args[1]);
int data=Integer.parseInt(args[2]);
Socket s=new Socket(ipaddress,portno);
OutputStream os=s.getOutputStream();
os.write(data);
InputStream is=s.getInputStream();
int res=is.read();
System.out.println("Result="+res);
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
C:/>javac Client.java
C:/>
To run the Server and Client in the same system:
After compiling Server.java and Client.java, run these programs in two separate dos
windows.
272 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
It is possible to send data from the server and receive the response from the client.
Similarly, the client can also send and receive the data to-and –fro. For this purpose, we need
additional streams both at server and client. For example, to receive data into the server we use
BufferedReader as:
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
Then read() or readLine() methods of BufferedReader class can be used to read data.
To send data from client, we can take the help of DataOutputStream as:
OutputStream obj=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(obj);
Then writeBytes() method of DataOutputStream can be used to send strings in the form of group
of objects.
273 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: write a program to create a server such that the server receives data from the client
using BufferedReader and then sends reply to the client using PrintStream.
import java.net.*;
import java.io.*;
class Server2
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(9999);
Socket s=ss.accept();
System.out.println("connection established");
PrintStream ps=new PrintStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str,str1;
while((str=br.readLine())!=null)
{
System.out.println(str);
str1=kb.readLine();
ps.println(str1);
}
ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0);
}
}
}
Output:
C:/>javac Server2.java
Do not run this program till client is also created.Once client is created and compiled then run
this program as.
C:/> java Server2
274 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program:write a program to create a client which first connects to a server, then starts the
communication by sending a string to the server. The server sends response to the client. When
‘exit’ is typed at client side, the programterminates.
import java.io.*;
import java.net.*;
class Client2
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",9999);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
String str,str1;
while(!(str=kb.readLine()).equals("exit"))
{
dos.writeBytes(str+"\n");
str1=br.readLine();
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}
Output:
C:/>javac Client2.java
C:/>java Client2
275 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
AWT:
Abstract Window Toolkit (AWT) represents a class library to develop applications using
GUI. The Java.awt package got classes and interfaces to develop GUI and the user interacts in a
more friendly way with the applications. The following figure shows some important classes of
java.awt package.
276 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Components:
Now, b is the object of Button class. If we display this bon the screen, it displays a push
button. Therefore, the object b, on going to the screen is becoming a component called ‘Push
button’. In the same way, any component is a graphical representation of an object. Push buttons,
radio buttons, check boxes, etc. are all components.
Container: The Container is a component in AWT that can contain another component like
buttons, textfields, labels etc. The class that extends Container class is known as container such
as Frame, Dialog and Panel.
277 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Window: The window is the container that has no borders and menu bars. You must use frame,
dialog or another window for creating a window.
Panel: The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame: The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
Creating a Frame:
A frame becomes the basic component in AWT. The frame has to be created before any
other component. The reason is that all other components can be displayed in a frame. There are
three ways to create a frame, which are as follows.
In all these cases, a frame with initial size of 0 pixels width and 0 pixels height will be
created, which is not visible on the screen and hence we should increase its size so that it would
be visible to us. This is done by setSize() method, as:
f.setSize(400,350);
Here, the frame’s width is set to 400 px and height to 350 px. Then, we can display the
frame, using setVisible() method, as:
f.setVisible(true);
278 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
import java.awt.*;
class MyFrame
{
public static void main(String[] args)
{
Frame f=new Frame("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
}
}
Output: C:\> javac MyFrame.java
C:\> java MyFrame
Prog: Write a program to create a frame by creating an object to the subclass of Frame class.
import java.awt.*;
class MyFrame extends Frame
{
MyFrame(String str){
super(str);
}
public static void main(String[] args)
{
MyFrame f=new MyFrame("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
}
}
Output: C:\> javac MyFrame.java
C:\> java MyFrame
279 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
This frame can be minimized, maximized and resized, but cannot be closed. Even if we
click on close button of the frame, it will not perform any closing action.
We know Frame is also a component. We want to close the frame by clicking on its close
button. Let us follow these steps to see how to use event delegation model to do this:
We should attach a listener to the frame component. Remember, all listeners are available
in java.awt.event package. The most suitable listener to the frame is ‘window listener’. It
can be attached using addWindowListener() method as:
f.addWindowListener(WindowListener obj);
In the above syntax the addWindowListener() method has a parameter that is expecting
object of WindowListener interface. Since it is not possible to create an object to an interface, we
should create an object to the implementation class of the interface and pass it to the method.
Implement all the methods of the WindowListener interface. The following methods are
found in WindowListener interface.
So, when the frame is closed, the body of this method is executed and the application gets
closed. In this way, we can handle the frame closing event.
Prog: write a program which first creates a frame and then closes it on clicking the close button.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new MyClass());
}
}
class MyClass implements WindowListener
{
public void windowActivated(WindowEvent e){ }
public void windowClosed(WindowEvent e){ }
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowDeactivated(WindowEvent e){ }
public void windowDeiconified(WindowEvent e){ }
public void windowIconified(WindowEvent e){ }
public void windowOpened(WindowEvent e){ }
}
281 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In this program, we not only create a frame but also close the frame when the user clicks
on the close button. For this purpose, we use WindowListener interface.
Here, we had to mention all the methods of WindowListener interface, just for the sake of
one method. This is really cumbersome. There is another way to escape this. There is a class
WindowAdapter in java.awt.event package, which contains all the methods of the
WindowListener interface with an empty implementation. If we can extend MyClass from this
WindowAdapter class, then we need not write all the methods with empty implementation.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String[] args) {
MyFrame f=new MyFrame();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new MyClass());
}
}
class MyClass extends WindowAdapter
{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
282 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output: C:\> javac MyFrame.java
C:\> java MyFrame
CLICK ON CLOSE BUTTON, THE FRAME CLOSES
We can also close a Frame by directly copy the code of MyClass into
addWindowListener() method as:
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
In the preceding code, we cannot find the name of MyClass anywhere. It means the name
of MyClass is hidden in MyFrame class and hence MyClass is an inner class in MyFrame class
whose name is not mentioned. Such an inner class is called ‘anonymous inner class’.
Prog: Write a program to close the frame using an anonymous inner class.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new MyClass()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
283 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Uses of a Frame:
Once, the frame is created, we can use it for any of the purposes mentioned here:
To draw some graphical shapes like dots, lines, rectangles, etc. in the frame.
To display some text in the frame.
To display pictures or images in the frame.
To display components like push buttons, radio buttons, etc. In the frame.
Graphics class of java.awt package has the following methods which help to draw various
shapes.
284 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To draw any of these shapes, we need paint() method of componentclass, which refreshes
the frame contents automatically when a drawing is displayed. This method is useful whenever
we want to display some new drawing or text or images in the frame. The paint() method is
automatically called when a frame is created and displayed.
Prog: write a program to draw a smiling face using the methods of Graphics class.
import java.awt.*;
import java.awt.event.*;
class Draw extends Frame
{
Draw()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawRect(40,40,200,200); // display a rectangle to contain drawing
g.drawOval(90,70,80,80); // face
g.drawOval(110,95,5,5); // left eye
g.drawOval(145,95,5,5); // right eye
g.drawLine(130,95,130,115); // nose
g.drawArc(113,115,35,20,0,-180); // mouth
}
public static void main(String args[]){
Draw d=new Draw();
d.setSize(400,400);
d.setTitle("My Drawing");
d.setVisible(true);
}
}
285 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Output: C:\> javac Draw.java
C:\> java Draw
To fill any shape with a desired color, first of all we should set a color using setColor()
method. Then any of the following methods will draw those respective shapes by filling with the
color.
286 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog:Write a program to draw a smiling face and fill the shapes with different colors.
import java.awt.*;
import java.awt.event.*;
class Draw extends Frame
{
Draw(){
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(40,40,200,200);
g.setColor(Color.yellow);
g.fillOval(90,70,80,80);
g.setColor(Color.black);
g.fillOval(110,95,5,5);
g.fillOval(145,95,5,5);
g.drawLine(130,95,130,115);
g.setColor(Color.red);
g.fillArc(113,115,35,20,0,-180);
}
public static void main(String args[]){
Draw d=new Draw();
d.setSize(400,400);
d.setTitle("My Drawing");
d.setVisible(true);
}
}
Output:
287 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog: Write a program to draw a home with moon at back ground.
import java.awt.*;
import java.awt.event.*;
class Home extends Frame
{
Home()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
int x[]={375,275,475};
int y[]={125,200,200};
int n=3;
this.setBackground(Color.gray);
g.setColor(Color.yellow);
g.fillRect(300,200,150,100);
g.setColor(Color.blue);
g.fillRect(350,210,50,60);
g.drawLine(350,280,400,280);
g.setColor(Color.darkGray);
g.fillPolygon(x,y,n);
g.setColor(Color.cyan);
g.fillOval(100,100,60,60);
g.setColor(Color. Green);
g.fillArc(50,250,150,100,0,180);
g.fillArc(150,250,150,100,0,180);
g.fillArc(450,250,150,100,0,180);
g.drawLine(50,300,600,300);
g.drawString("My Happy Home",275,350);
}
public static void main(String[] args)
{
Home h=new Home();
h.setTitle("My Home");
h.setSize(500,400);
h.setVisible(true);
}
}
288 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To display some text or strings in the frame, we can take the help of drawstring() method
of Graphics class as:
g.drawString(“Hello”, x, y);
Here, the string “Hello” will be displayed starting from the coordinates (x, y).
If we want to set some color for the text, we can use setColor() method of Graphics class, as:
g.setColor(Color.red);
There are two ways to set a color in AWT. The first way is by directly mentioning the
needed color name for Color class, as Color.red, Color.yellow, Color.cyan, etc. all the standard
colors are declared as constants in Color class, as shown in the following table.
289 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The second way to mention any color is by combining the three primary colors: red,
green, and blue while creating Color class object, as:
Here, r, g, b values can change from 0 to 255. 0 represents no color. 10 represents low
intensity whereas 200 represents high intensity of color. Thus,
This Color class object c should be then passed to setColor() method to set the color.
To set some font to the text, we can use setFont() method of Graphics class, as:
g.setFont(Font object);
This method takes Font class object, which can be created as:
Here, “SanSerif” represents the font name, Font.BOLD represents the font style and 30
represents the font size in pixels. There are totally 3 styles that we can use:
Font.BOLD
Font.ITALIC
Font.PLAIN
We can also combine any two styles, for example, to use bold and italic, we can write
Font.BOLD + Font.ITALIC.
Prog: Write a program to display some text in the frame using drawstring() method.
import java.awt.*;
import java.awt.event.*;
class Message extends Frame
{
Message()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
290 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
public void paint(Graphics g)
{
this.setBackground(new Color(100,20,20));
Font f=new Font("Arial",Font.BOLD+Font.ITALIC,30);
g.setFont(f);
g.setColor(Color.green);
g.drawString("Hello, How are u?",100,100);
}
public static void main(String[] args)
{
Message m=new Message();
m.setSize(400,300);
m.setTitle("This is my text");
m.setVisible(true);
}
}
Output: C:\> javac Message.java
C:\> java Message
We can display images like .gif and .jpg files in the frame. For this purpose, we should
follow these steps.
Load the image into Image class object using getImage() method of Toolkit class.
Image img=Toolkit.getDefaultToolkit().getImage(“diamonds.gif”);
Here, Toolkit.getDefaultToolkit() method creates a default Toolkit class object. Using this
object, we call getImage() method and this method loads the image diamonds.gif into img object.
291 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
But, loading the image into img will take some time. JVM uses a separate thread to load
the image into img and continues with the rest of the program. So, there is a possibility of
completing the program execution before the image is completely loaded into img. In this
case, a blank frame without any image will be displayed. To avoid this, we should make
JVM wait till the image is completely loaded into img object. For this purpose, we need
MediaTracker class. Add the image to MediaTracker class and allot an identification
number to it starting from 0,1,….
MediaTracker track= new MediaTracker(this);
track.addImage(img,0);
Now, MediaTracker keeps JVM waiting till the image is loaded completely. This is done
by waitForID() method.
track.waitForID(0);
This means wait till the image with the id number 0 is loaded into img object. Similarly,
when several images are there, we can use waitForId(1), waitForId(2), etc.,
Once the image is loaded and available in img, then we can display the image using
drawImage() method of Graphics class, as:
g.drawImage(img,50,50,null);
Here, img is the image that is displayed at (50,50) coordinates and ‘null’ represents
ImageObserver class object which is not required. ImageObserver is useful to store history of
how the image is loaded into the object. Since, this is not required, we can use just null in its
place. Another alternative for drawImage() is:
g.drawImage(img,50,50,200,250,null);
Here, additional 200,250 represents the width and height of the image. They help to
increase or decrease the size of the image to fit in the area allotted fir it in the frame.
To display an image in the title bar of the frame, we can use setIconImage() method of
Frame class, as:
setIconImage(img);
292 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog: Write a program to display an image in the frame and also in the title bar of the frame.
import java.awt.*;
import java.awt.event.*;
class Images extends Frame
{
static Image img;
Images()
{
img=Toolkit.getDefaultToolkit().getImage("java.jpg");
MediaTracker track=new MediaTracker(this);
track.addImage(img,0);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawImage(img,50,50,null);
}
public static void main(String[] args)
{
Images i=new Images();
i.setSize(500,400);
i.setTitle("My Images");
i.setIconImage(img);
i.setVisible(true);
}
}
Output:
293 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
void setBounds(int x, int y, int w, int h): This method allots a rectangular area starting
at(x, y) coordinates and width w and height h. the component is resized to this area before
its display. This method is useful to specify the location of the component in the frame.
After creating a component, we should add the component to the frame. For this purpose,
add() method is used.
f.add(component);
Similarly, to remove a component from the frame, we can use remove() method, as:
f.remove(component);
Push Buttons:
Button class is useful to create Push buttons. A push button is useful to perform a
particular action
To create a push button with a label, we can create an object to Button class, as:
Button b=new Button();
Button b=new Button(“label”);
To get the label of the button, use getLabel():
String l=b.getLabel();
When, there are several buttons, naturally the programmer should know which button is
clicked by the user. For this purpose, getActionCommand() method of ActionEent class is
useful.
String s=ae.getActionCommand();
Here, s represents the label of the button clicked by the user.
To know the source object which has been clicked by the user, we can use, getSource()
method of ActionEvent class, as:
Object obj=ae.getSource();
Remember that only displaying the push buttons will not perform any actions. This
means they cannot handle any events. To handle the events, we should use event delegation
model. According to this model, an appropriate listener should be added to the push button.
When the button is clicked, the event is passed to the listener and the listener calls a method
295 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
which handles the event. With push buttons, ActionListener is suitable listener. To handle
ActionListener to the button, we can use addxxxListener() method, as:
b.addActionListener(ActionListener obj);
Similarly, to remove action listener from the button, we can use removexxxListener()
method, as:
b.removeActionListener(ActionListener obj);
First, set a layout manager using setLayout() method. In our program, we do not want to
set any layout, hence we can pass null to setLayout() as:
this.setLayout(null);
Since our class MyButtons extends Frame class, this represents MyButtons class object or
Frame class.
Prog: Write a program that helps in creating 3 push buttons bearing the name of 3 colors. When
a button is clicked, that particular color is set as background color in the frame.
import java.awt.*;
import java.awt.event.*;
class MyButtons extends Frame implements ActionListener
{
Button b1,b2,b3;
MyButtons()
{
this.setLayout(null);
b1=new Button("yellow");
b2=new Button("blue");
296 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
b3=new Button("pink");
b1.setBounds(100,100,70,40);
b2.setBounds(100,160,70,40);
b3.setBounds(100,220,70,40);
this.add(b1);
this.add(b2);
this.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("yellow")) this.setBackground(Color.yellow);
if(str.equals("blue")) this.setBackground(Color.blue);
if(str.equals("pink")) this.setBackground(Color.pink);
}
public static void main(String[] args)
{
MyButtons b=new MyButtons();
b.setSize(400,400);
b.setTitle("My Buttons");
b.setVisible(true);
}
}
Output:
297 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
For working with push buttons, ActionListener is more suitable. Similarly, for other
components, other listeners are also available. All listeners are available in java.awt.event
package. The following table summarizes the components, suitable listeners for the component,
and the methods in the listener interface to be implemented when using that listener.
298 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Check Boxes:
A check box is square shaped box which displays an option to the user. The user can
select one or more options from a group of check boxes. Let us see how to work with check
boxes.
299 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Radio Button:
A radio button represents a round shaped button, such that only one can be selected from
a group of buttons. Radio buttons can be created using CheckboxGroup class and Checkbox
classes. First of all, we should create a CheckboxGroup class object. While creating a radio
button, we should pass CheckboxGroup object to the Checkbox class. It represents the group to
which the radio button belongs. When the same CheckboxGroup object is passed to different
radio buttons, then all those radio buttons will be considered as belonging to same group and
hence the user is allowed to select only one from them.
To create a radio button, pass CheckboxGroup object to Checkbox class object:
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb=new Checkbox(“label”, cbg, state);
Here, if state is true then the radio button appears to be already selected by
default. If the state is false, then the radio button appears normal as if it is not
selected.
To know which radio button is selected by the user:
Checkbox cb=cbg.getSelectedCheckbox();
To know the selected radio button’s label:
String label=cbg.getSelectedCheckbox().getLabel();
TextField:
A Textfield represents a long rectangular box where the user can type a single line of text.
We can also display a line of text in the text field also.
To create a TextField.
TextField tf=new TextField();
TextField tf=new TextField(25);
TextField tf=new TextField(“default text”, 25);
To retrieve the text from a TextFiled:
String s= tf.getText();
To set the text to a TextField.
tf.setText(“text”);
300 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To hide the text being typed into the TextFiled by a character char:
tf.setEchoChar(‘char’);
Now, the original characters typed in the text field are not displayed. In their
place, the char is displayed. This is useful to hide important text like credit card
numbers, passwords, etc.
TextArea:
A TextArea is similar to a text field, but it can accommodate several lines of text. For
example, if the user wants to type his address which contains several lines, he can use a text area.
To create a TextArea:
TextArea ta=new TextArea();
TextArea ta=new TextArea(rows, cols);
TextArea ta=new TextArea(“String”);
To retrieve the text from a TextArea:
String s=ta.getText();
To set the text to a TextArea:
ta.setText(“text”);
To append the given text to the area’s current text:
ta.append(”text”);
To insert the specified text at the specified position in this text area:
ta.insert(“text”, position);
Label:
A Label is a constant text that is generally displayed along with a TextFiled or TextArea.
To create a label:
Label l=new Label();
Label l=new Label(“text”, alignment constant);
Here, the alignment constant may be one of the following:
Label.RIGHT, Label.LEFT, Label.CENTER
When the label is displayed, there would be some rectangular are allotted for the
label. In this area, the label is aligned towards right, left, or center as per the
alignment constant.
301 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Choice Class:
Choice class is useful to display a choice menu. It is a pop-up list of items and the user
can select only one item from the available items.
To create a Choice menu:
Choice ch=new Choice();
Once a choice menu is created, we should add items to it using add() method, as:
ch.add(“item”);
To know the name of the item selected from the Choice menu:
String s=ch.getSelectedItem();
Index of items in the Choice menu starts from 0 onwards. To know the index of the
currently selected item:
int i=ch.getSelectedIndex();
This method returns -1 if nothing is selected.
To get the item string, given the item index number.
String item=ch.getItem(int index);
To know the number of items in the Choice menu.
int n=ch.getItemCount();
To remove an item from the choice menu at a specified position.
ch.remove(int position)
To remove an item from the choice menu,
ch.remove(String item)
To remove all items from the choice menu,
ch.removeAll();
List Class:
This class is useful to create a list box which is similar to choice menu. A list box
represents the user with a scrolling list of text items. The user can select one or more items from
the list box.
302 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
This statement creates a list box, the user can select only one item from the available
items.
This statement creates a list box which displays initially 3 rows. The rest of the rows can
be seen by clicking on the scroll button.
This list box initially displays 3 items. The next parameter true represents that the user
can select more than one item from the available items. If it is false, then the user can
select only one item.
To add items to the list box, we can use add() method, as:
lst.add(“item”);
To get all the selected items from the list box:
String x[]= lst.getSelectedItems();
To get a single selected item from the list box:
String x[]=lst.getSelectedItem();
To get the selected items position numbers:
int x[]=lst.getSelectedIndexs();
To get a single selected item position number:
int x=lst.getSelectedIndex();
To get the number of visible lines in this list:
int x=lst.getRows();
To get all the items available in the list box:
String x[]=lst.getItems();
To get the item name when the position number (index) is known:
String item=lst.getItem(int index);
To know how many number of items are there in the list box:
int x=lst.getItemCount();
To remove an item at a specified position from the list:
lst.remove(int position);
303 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Scrollbar Class:
Scrollbar class is useful to create scrollbars that can be attached to a frame or text area.
Scrollbars are used to select continuous values between a specified minimum and maximum
Scrollbars can be arranged vertically or horizontally.
To create a Scrollbar we can create an object to Scrollbar class, as:
Scrollbar sb=new Scrollbar(alignment, start, step, min, max);
Here,
alignment: Scrollbar.VERTICAL, Scrollbar.HORIZONTAL
start: starting value (Ex: 0)
step: step value (Ex: 30) // represents scrollbar length
min: minimum value (Ex: 0)
max: maximum value (Ex: 300)
To know the location of a scroll bar, we can use getValue() method that gives the position
of the scrollbar in pixels, as:
int n=sb.getValue();
To update the scrollbar position to a new position, we can use setValue() method, as:
sb.setValue(int position);
To get maximum value of the scrollbar:
int x=sb.getMaximum();
To get the minimum value of the scrollbar:
int x=sb.getMinimum();
To get the alignment of the scrollbar:
int x=getOrientation();
This method returns 0 if the scrollbar is aligned HORIZONTAL and returns 1 if it
is aligned VERTICAL.
304 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog: Write a program to create a Student registration from by using Awt Component classes.
import java.awt.*;
import java.awt.event.*;
public Student()
{
addWindowListener(new myWindowAdapter());
setBackground(Color.cyan);
setForeground(Color.black);
setLayout(null);
add(l11);
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(t1);
add(t2);
add(ck1);
add(ck2);
add(course);
add(sem);
add(age);
add(b1);
305 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
b1.addActionListener(this);
add(b1);
course.add("BSc c.s");
course.add("BSc maths");
course.add("BSc physics");
course.add("BA English");
course.add("BCOM");
sem.add("1");
sem.add("2");
sem.add("3");
sem.add("4");
sem.add("5");
sem.add("6");
age.add("20");
age.add("21");
age.add("22");
age.add("23");
age.add("24");
l1.setBounds(25,65,90,20);
l2.setBounds(25,90,90,20);
l3.setBounds(25,120,90,20);
l4.setBounds(25,185,90,20);
l5.setBounds(25,260,90,20);
l6.setBounds(25,290,90,20);
l7.setBounds(25,260,90,20);
l11.setBounds(10,40,280,20);
t1.setBounds(120,65,170,20);
t2.setBounds(120,185,170,60);
ck1.setBounds(120,120,50,20);
ck2.setBounds(170,120,60,20);
course.setBounds(120,260,100,20);
sem.setBounds(120,290,50,20);
age.setBounds(120,90,50,20);
b1.setBounds(120,350,50,30);
}
public void paint(Graphics g)
{
g.drawString(msg,200,450);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("save"))
{
msg="Student details saved!";
setForeground(Color.red);
}
}
306 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
public static void main(String g[])
{
Student stu=new Student();
stu.setSize(new Dimension(500,500));
stu.setTitle("Student registration");
stu.setVisible(true);
}
}
class myWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Output: Javac Student.java
Java Student
307 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). which method of the component class is used to set the position and the size of a
component?
Answer:set Bounds().
Example:TxtName.setBounds(x, y, width, height);
308 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). How can the Checkbox class be used to create a radio button?
Answer: By associating Checkbox objects with a CheckboxGroup.
Q). Can I add the same component to more than one container?
Answer:No. Adding a component to a container automatically removes it from any previous
parent (container).
309 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Applets
When a HTML(Hyper Text Markup Language) page wants to communicate with the user
on internet, it can use a special java program called “Applet” to communicate and respond to the
user.
The user can interact by typing some details or by clicking the components available in
the applet program. The program then processes and displays the results.
We can understand an applet as a java byte code embedded in a HTML page, generally
for the purpose of achieving communication with the user, we can think of an applet as:
Creating an applet:
1. Create a user-defined class and extending that class from the Applet class.
2. Override the Applet lifecycle methods.
To create an applet, we have Applet class of java.applet package and JApplet class of
javax.swing package. These classes use the following methods, which are automatically run by
any applet program. So, these methods should be overridden in an applet program.
public void init():This method is the first method to be called by the browser and it is
executed only once. So, the programmer can use this method to initialize any variables,
creating components and creating threads, etc. when this method execution is completed,
browser looks for the next method: start().
public void start(): This method is called after init() method and each time the applet is
revisited by the user. For example, the user has minimized the web page that contains the
applet and moved to another page then this method’s execution is stopped. When the user
comes back to view the web page again, start() method execution will resume. Any
calculations and processing of data should be done in this method and the results are also
displayed.
public void stop(): This method is called by the browser when the applet is to be stopped
if the user minimizes the web page, then this method is called and when the user again
comes back to this page, then start() method is called. In this way, start() and stop()
methods can be called repeatedly. For example, an applet with some animation might
want to use the start() method to resume animation, and the stop() method to suspend the
animation.
310 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
public void destroy(): This method is called when the applet is being terminated from
memory. The stop() method will always be called before destroy(). The code related to
releasing the memory allocated to the applet and stopping any running threads should be
written in this method.
Executing init(), start(), stop() and destroy() methods in that sequence is called “life cycle of
an applet”.
Note:The“public static void main(String args[])” method is not available in case of applets.
This means, we can compile the applet code but we can’t run it using a JVM.
Once the applet is created, we compile and obtain its byte code. This byte code is embedded
in HTML page and the page is sent to the client computer. The client machine contains a browser
like Internet explorer, Netscape Navigator or Mozilla Firefox where the HTML page is viewed
by the user. The same browser will execute the applet of the HTML page. The browser contains
a small virtual machine called “applet engine” which understands and runs the applet code.
Uses of applets:
<Applet> tag:
<Applet> tag is useful to embed an applet into an HTML page. It has the following form:
</APPLET>
311 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog:Write a program to create an applet with some background color and a message “Hello
Applets”.
To display a message, we can take the help of paint() method of Component class of java.awt
package. Remember all the methods of the applet and the applet class itself should be declared
public, otherwise they are not available to the browser to execute.
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void init()
{
setBackground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawString("Hello Applet",50,100);
}
}
Output: C:\>javac MyApplet.java
Now, MyApplet.class is created. This byte code should be embedded into a HTML page
using <APPLET> tag, as shown below:
<HTML>
<applet code="MyApplet.class" height=300 width=300>
</applet>
</HTML>
Save the above code with the name: MyApp.html. this HTML page contains the applet
which can be opened in the browser, or an applet viewer supplied by the Sun micro systems Inc,
can be used to test the applet.
312 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Prog:Write a program to create an applet by overriding the applet life cycle methods with some
background color and foreground color with a message.
import java.awt.*;
import java.applet.*;
public class App1 extends Applet
{
String msg="";
public void init()
{
setBackground(Color.pink);
setForeground(Color.red);
Font f=new Font("Arial",Font.BOLD,20);
setFont(f);
msg+="init ";
}
public void start()
{
msg+="start ";
}
public void stop()
{
msg+="stop ";
}
public void destroy()
{
msg+="destroy ";
}
public void paint(Graphics g)
{
msg+="paint ";
g.drawString(msg,50,100);
}
}
<HTML>
<applet code="App1.class" height=200 width=300>
</applet>
</HTML>
313 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Minimize the applet frame and you will see stop() method executed, then maximize it to
see if the start() method is executed. Whenever the applet frame is resized paint() method is
again executed, thus showing the updated contents of the applet frame.
314 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q). what is Applet life cycle?
Answer:An applet is born with init() method and starts functioning with start() method. To
stop the applet, the stop() method is called and to terminate the applet completely from
memory, the destroy() method is called. Once the applet is terminated, we should reload
the HTML page again to get the applet start once again from init() method. This cyclic way
of executing the methods is called applet life cycle.
Q).what is the sequence for calling the methods by AWT for applets?
Answer: When an applet begins, the AWT calls the following methods, in this sequence:
1. init()
2. start()
3. paint()
When an applet is terminated, the following sequence of method calls takes place:
4. stop()
5. destroy()
Q). ShowStatus() ?
Answer:To display the message at the bottom of the browser when applet is started.
315 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD