0% found this document useful (0 votes)
559 views

MAIN Java Material

The document provides information about the Java programming language. It discusses the origins of Java, describing how it was created by James Gosling and his team at Sun Microsystems in the early 1990s. The language was originally called Oak but was later renamed to Java, taking its name from Java island in Indonesia due to the team's high consumption of coffee during development. The document outlines some of the key features of Java, including that it is simple, object-oriented, distributed, robust, secure, platform independent, portable, interpreted, high-performance, multithreaded, scalable and dynamic.

Uploaded by

Kalyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
559 views

MAIN Java Material

The document provides information about the Java programming language. It discusses the origins of Java, describing how it was created by James Gosling and his team at Sun Microsystems in the early 1990s. The language was originally called Oak but was later renamed to Java, taking its name from Java island in Indonesia due to the team's high consumption of coffee during development. The document outlines some of the key features of Java, including that it is simple, object-oriented, distributed, robust, secure, platform independent, portable, interpreted, high-performance, multithreaded, scalable and dynamic.

Uploaded by

Kalyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 315

Core java

J2SE
(Corporate Training Program)
6 Weeks/45 Days

“PRESENTED BY”

TRAINING DEVELOPMENT CONSULTING

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,

Opp. S.V. Music College, Tirupati,

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

JAVA .NET NS2 ANDROID INTERNSHIP INPLANT CORPORATE

DOMAINS DOMAINS

1. CLOUD COMPUTING 1. C & DATA STRUCTURES


2. DATA MINING 2. C++
3. NETWORKING 3. COMPLETE JAVA
4. MOBILE COMPUTING 4. .NET
5. SECURE COMPUTING 5. ANDROID
6. IMAGE PROCESSING 6. ORACLE
7. SERVICE COMPUTING 7. TESTING TOOLS
8. SOFTWARE ENGINEERING 8. PHP
9. PARALLEL & DISTRIBUTED SYSTEMS

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.

So James Goslingstarts to develop a new language which was completely system


independent. Firstly, it was called "Greentalk" by James Gosling and file extension was ‘.gt’.
After that, it was called Oak, since this name was registered by other company, later it was
changed to JAVA.

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

3) Distributed:Information is distributed on various computers on a network. Using java,


we can write programs, which capture information and distribute it to the clients. This is
possible because java can handle the protocols like TCP/IP and UDP.

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.

5) Secured:Security problems like eavesdropping, tampering, impersonation, and virus


threats can be eliminated or minimized by using java on internet.
Java is secured because:
 No explicit pointer
 Programs run inside virtual machine sandbox.
7 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

6) Platform independent:Java code can be run on multiple platforms


e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is compiled by the compiler and
converted into bytecode.This bytecode is a platform independent code because it can be
run on multiple platforms i.e. Write Once and Run Anywhere(WORA).

Class file

Windows jvm Linux jvm Mac os jvm

0 0 0
1 1 1
0 0 0

Windows Linux Mac os

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.

10) Multithreaded: A thread represents an individual process to execute a group of


statements. JVM uses several threads to execute different blocks of code. Creating
multiple threads is called “multithreaded”.

11) Scalability:Java platform can be implemented on a wide range of computers with


varying levels of resources, from embedded devices to mainframe computers. This is
possible because Java is compact and platform independent.

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.

How to set path in Java:


The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to
be set because all the tools will be available in the current directory. But if you are having your
java file outside the jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
a. Temporary
b. Permanent

a) How to set Temporary Path of JDK in Windows:


To set the temporary path of JDK, you need to follow following steps:
1) Open command prompt
2) copy the path of jdk/bin directory
3) write in command prompt: set path=copied_path
For Example:

9 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

set path=C:\Program Files\Java\jdk1.6.0_23\bin

b) How to set Permanent Path of JDK in Windows:


For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties  advanced tab  environment variables  new
tab of user variable  write ‘path’ in variable name paste path of bin folder in variable
value  ok  ok  ok.

Important Interview Questions:


Q).why pointers are eliminated from java?
Answer:
1)Pointers lead to confusion for a programmer.
2) Pointers may crash a program easily, for example, when we add two pointers, the
program crashes immediately. The same thing could also happen when we forgot to free the
memory allotted to a variable and reallot it to some other variable.
3) Pointers break security. Using pointers, harmful programs like virus and other hacking
programs can be developed.
Because of the above reasons, pointers have been eliminated from 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).How can you call the garbage collector?


Answer:Garbage collector is automatically invoked when the program is being run, it can be
also called by calling gc() method of Runtime class or system class in java.

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).what is the initial name given to java programming language?


Answer:oak is the initial name given to java programming language.

Q). Java …………… can run from a Web browser.


A. Applications
B. Servlets
C. Applets
D. Micro edition program
Answer:A

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

The Java Virtual Machine:


Java Virtual Machine (JVM) is the heart of entire Java Program execution process. It is
responsible for taking the .classfile and converting each byte code instruction into the machine
language instruction that can be executed by the microprocessor. The following diagram shows
the architecture of Java Virtual Machine.

Class loader
Class file
sub system

Method Heap Java Pc Native


area stacks registers method
stacks

Run time data areas

JIT Native method Native method


compiler interface
Interpreter libraries

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

Differences between c++ and 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

Important Interview Questions:


Q). what is JIT compiler?
Answer:JIT compiler is the part of JVM which increases the speed of execution of a java
program.

Q). what is the heart of entire java program execution process?


Answer:JVM is the heart of entire java program.

Q). Allocation of memory in java is done by which part of JVM?


Answer:Class Loader subsystem.

Q).The memory allocated by JVM to execute the program is called?


Answer:Run time data areas.

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.

Q) Allocation and Deallocation of memory in java is done by …………..


Answer:JVM

Q). Deallocation of memory is done by …………… using ……………. Algorithm?


Answer:garbage collector, mark and sweep.

15 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

First java Program


To create a simple java program, you need to create a class that contains main method. Let's
understand the requirement first.

Requirement for first java programming:

For executing any java program, you need to

 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

Creating an example java program:

import java.lang.*;
class Simple
{
Public static void main (String args [])
{
System.out.println ("Hello Java");
}
}

Save this file as Simple.java

To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

Understanding sample java program:

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.

public:keyword is an access modifier which represents visibility, it means it is visible to all.

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.

main:represents startup of the program.

string[] args:is used for command line arguments.

System.out.println():is usedfor printing a statement.

Important Interview Questions:


Q) What is the difference between #include and import statement?
Answer: #include directive makes the compiler go to the C/C++ standard library and copy
the code from the header files into the program. As a result, the program size increases,
thus wasting memory and processor’s time.
import statement makes the JVM go to the java standard library, execute the code
there, and substitute the result into the program. Here, no code is copied and hence no
waste of memory or processor’s time. So, import is an efficient mechanism than #include

Q) What happens if String args[] is not written in main() method?


Answer: When main() method is written without String args[] as:
public static void main()
the code will compile but JVM cannot run the code because it cannot recognize the main()
method as the method from where it should start execution of the java program. Remember
JVM always looks for main() method with string type array as parameter.

Q) What is the difference between print() and println() method?


Answer: Both methods are used to display the results on the monitor. Print() method
displays the result and then retains the cursor in the same line, next to the result. Println()
displays the result and then throws the cursor to the next line.

17 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Q) Do I need to import java.lang package any time? Why?


Answer:No. It is by default loaded internally by the JVM.

Q) Can I have multiple main methods in the same class?


Answer:No the program fails to compile. The compiler says that the main method is already
defined in the class.

Q) What if I write static public void instead of public static void?


Answer:Program compiles and runs properly.

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

Q) What if the main method is declared as private?


Answer:The program compiles properly but at runtime it will give "Main method not public."
message.

Q) What is the base class of all the classes?


Answer:java.lang.Object

Q) Can a .java file contain more than one java classes?


Answer:Yes, a .java file contains more than one java classes, provided at the most one of
them is a public class.

18 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Naming conventions in Java


Naming convention specify the rules to be followed by a java programmer while writing
the names of packages, classes, methods, etc.But, it is not forced to follow. So, it is known as
convention not rule.

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

CamelCase in java naming conventions:

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:

Syntax: data type variable [= value][, variable [= value] ...];

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.

There are three types of variables in Java:


1. Local variables
2. Instance variables
3. Class/static variables

1) Local variables:

 Local variables are declared in methods, constructors, or blocks.


 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
 Local variables are visible only within the declared method, constructor or block.
2) Instance 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.

Example to understand the types of 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

Data Types in 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.

There are two data types available in Java:


 Primitive Data Types
 Reference/Object Data Types

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.

For example: boolean response=true;

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.

Syntax: char <variable name> = <default value>;

ForExample: char ch=’A’;

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.

Syntax: int <variable name> = <value>;

Example: int n=1110;

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.

Syntax: byte <variable name> = < value>;

Example: byte b=10;


23 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Short datatype:A short is twice the size of a byte, Short data type is a 16-bit signed two's
complement integer.Short data type can also be used to save memory as byte data type. A short
is 2 times smaller than an int.

Syntax: short <variable name> = < value>;

Example: short s=1000;

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

Syntax: long <variable name> = < value>;

Example: long x=100000L;

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

Example: float x=2.321f;

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.

Example: double y=2.321;

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.

Examples: Object of a class Car, String, etc.

Default values of datatypes in java:

Data Type Default Value


byte 0
short 0

int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000’
String (or any object) null
boolean false

Important Interview Questions:


Q) What is a unicode system?

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.

Q) What is the difference between float and double?

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) What is the default value of the local variables?


Answer:The local variables are not initialized to any default value, neither primitives nor
object references. If you try to use these variables without initializing them explicitly, the
java compiler will not compile the code. It will complain about the local variable not being
initialized.

Q) What is the difference between declaring a variable and defining a variable?


Answer:In declaration we just mention the type of the variable and its name. We do not
initialize it. But defining means declaration + initialization. e.g. String s; is just a declaration
while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

Q) 64 bit value can be stored by using ………… or ………….. datatypes?


Answer:long or double.

Q) Default value of character in java is ……………?


Answer:‘\u0000’ (where as its null for String).

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.

Q) Java has ………….. primitive datatypes.


Answer:8 (byte, short, int, long, char, float, double and boolean).

Q) Integer data type does not include following primitive type…………?


A)byte b)double c)short d)long
Answer:B (Integer includes byte, short, int, long. Similarly double and float comes under
floating point numbers).

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

If an operator acts on a single variable, it is called unary operator; if it acts on two


variables, it is called binary operator, and if it acts on three variables it is called ternary
operator.

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.

Operator Meaning Example Result


+ Addition operator a+b 18
- Subtraction operator a -b 8
* Multiplication operator a*b 65
/ Division operator a /b 2.6
% Modulo operator a%b 3
(This gives the remainder
of division)

Addition operator (+) is also used to join two strings, as shown in the following code
snippet:

String s1=”wel”;

String s2=”come”;

String s3=s1+s2; // here, ‘+’ is joining s1 and s2.

Now, we get welcome in s3. In this case, + is called String concatenation operator.

Increment/Decrement operators:

Increment and Decrement Operators are Unary Operators.Unary Operator Operates on


One Operand. Increment operator is used to Increment value stored inside variable on which it is
operating.Decrement operator is used to decrement value of variable by 1 (default).

Types of Increment and Decrement Operator:

1. Pre Increment / Pre Decrement Operator

2. Post Increment / Post Decrement Operator

++ Increment operator: increments a value by 1

-- Decrement operator: decrements a value by 1

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.

Example: Finding the difference between pre- and post- increment of x

int x=1; int x=1;


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

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:

1. It is used to store a value into a variable,


for example:int x=5;
2. It is used to store the value of a variable into another variable,
for example:int x=y; // Here the value of y is stored into x
3. It is used to store the value of an expression into a variable,
for example: int x=y+z-4; // Here the expression y+z-4 is evaluated and its result is
stored into x.

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.

Operator Name Example Equivalent

+= Addition assignment i+=5; i=i+5

-= Subtraction assignment j-=10; j=j-10;

*= Multiplication assignment k*=2; k=k*2;

/= Division assignment x/=10; x=x/10;

%= Remainder assignment a%=4; a=a%4;

Program:Write a program to find the sum of first 10 numbers.

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

Program:Write a program to find if two values are equal or not.

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:

Logical operators are used to construct compound conditions. A compound condition is a


combination of several simple conditions.Here the operands can be constants, variables and
expressions.
Logical operators are three types.

31 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Operator Meaning of Operator Example Description


&& Logical AND If c=5 and d=2 then,((c==5) It returns true when both
&& (d>1)) returns true. conditions are true
|| Logical OR If c=5 and d=2 then, It returns true when at least
((c==5) || (d>5)) returns true. one of the condition is true
! Logical NOT If c=5 then, ! (c==5) returns If condition is true it returns
false. false

Program:Write a program to find which value is big.


class Logic
{
public static void main(String[] args)
{
int a=10,b=20,c=15;
if((a>b)&&(a>c))
{
System.out.println("a is big");
}
else if((b>a)&&(b>c))
{
System.out.println("b is big");
}
else
{
System.out.println("c is big");
}
}
}
Output:
b is big

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.

Converting Decimal values to Binary values:

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

Therefore the binary equivalent to 156 is 10011100

Types of bitwise Operators:

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:

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Consider x=40 and Y=60, the binary forms of these values are:

Bitwise AND Bitwise OR Bitwise Exclusive – OR

X = 00101000 X = 00101000 X = 00101000


Y = 01010000 Y = 01010000 Y = 01010000
------------- ------------- -------------
X&Y= 00000000 X|Y= 01111000 X^Y= 01111000
= 0(in decimal) = 120 (in decimal) = 120 (in decimal)

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

Bitwise Shift Operators:

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

Bitwise Left Shift Bitwise Right Shift

X =00101000 X =00101000
X << 1 = 01010000 X >> 1 = 00010100
= 80 = 20

Program:The following program is an example of Bit-wise operators.

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

Ternary Operator or Conditional operator (? :) :

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 :

Syntax: variable = expression1 ? expression2 : expression3;

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;

(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition,


(a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is
returned. Whichever value is returned is dependent on the conditional test, a > b. The condition
can be any expression which returns a boolean value.

35 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:Example program for conditional operator

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.

Syntax: classname.methodname; (or)


Objectname.methodname;

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

Syntax: classname obj = new classname();


Example: Employee emp = new Employee(); //emp is an object of Employee class

Cast operator:
Cast operator is used to convert one datatype into another datatype. This operator can be
used by writing datatype inside simple braces,

Example: double x=10.54;


int y=x; // error- because datatypes of x and y are different
To store x value into y, we have to first convert the datatype of x into the datatype of y. it
means double datatype should be converted into int type by writing int inside the simple braces
as;(int). this is called cast operator.
int y=(int)x; //here, x datatype is converted into int type and then stored into y.
In the preceding statement, (int) is called cast operator. cast operator is generally used
before a variable or before a method.

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.

Category Operator Associativity

Postfix () [] . (dot operator) Left toright

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >>>>><< Left to right

Relational >>= <<= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

Important Interview Questions:


Q) What is the % operator?
Answer:It is referred to as the modulo or remainder operator. It returns the remainder of
dividing the first operand by the second operand.

38 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) Which Java operator is right associative?
Answer:The = operator is right associative.

Q) Can a double value be cast to a byte?


Answer:Yes, a double value can be cast to a byte.

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 are all the Java primitive data conversion rules?


Answer:
 A boolean type may not be converted to non-boolean type.
 That is you cannot assign a boolean value to non-boolean type and vice versa.
 A non-boolean type may be converted to non-boolean type provided that the
conversion iswidening.

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)Can bitwise operators used in Boolean operations?


Answer:The Bitwise operators can also be used in Boolean operations. If applied to boolean
it uses true or false which are equivalent to 1 and 0.

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

Control Statements in java


The statements inside your source files are generally executed from top to bottom, in the
order that they appear. Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your program
toconditionally execute particular blocks of code.
This involves a kind of decision making to see whether a particular condition has
occurred or not and direct the computer to execute certain statements accordingly.

Based on application, it is necessary / essential


(i) To alter the flow of a program
(ii) Test the logical conditions
(iii) Control the flow of execution as per the selection these conditions can be placed in
the program using decision-making statements.

Types of control statements

Conditional Control statements Unconditional Control statements

Decision making statements Looping Control statements

 if – else  for loop  break


 if – else ladder  while loop  continue
 switch  do – while loop  return

40 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Decision Making Statements:

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:

True Condition False

True Block Statement False Block Statement

Rest of the Program

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

2. The else - ifLadder:

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

 The conditions are evaluated from top to bottom.


 As soon as a true condition is found, the statement associated with it is executed and the
control is transferred to the Rest of the Program Statement–X (skipping rest of the ladder).
 When all the “n” conditions become false, then the final else containing the defaultstatement
will be executed.

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

Program:Write a program to find the largest one by using “else-if” ladder.

public class Demo1 {


public static void main(String args[])
{
int a=21, b=30, c=15;
if((a>b) && (a>c))
{
System.out.println("Highest Number is:"+a);
}

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 (variable or expression)


{
Case Constantvalue-1: Block -1;
(Or)
Statement-1;
break;
Case Constantvalue-2: Block -2;
(Or)
Statement-2;
break;
_ __ _ _ _ _ _
_ __ _ _ _ _ _

Case Constant value-n: Block -n;


(Or)
Statement-n;
break;
default: default – block;
}

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

case-1 Match Statement-1 break

Unmatch

case-2 Match Statement-2 break

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.

public class Demo


{
public static void main(String args[])
{
char l='r';
switch(l)
{
case 'r':
case 'R': System.out.println("Red Light, Please Stop");
break;
case 'g':
case 'G': System.out.println("Green Light, Please Go");
break;
case 'y':
case 'Y': System.out.println("Yellow Light, Please Check and Go");
break;
default: System.out.println("There is no signal point");
break;
}
}
}
Output:
Red Light, Please Stop

46 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Loop control statements:

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.

The 3 actions are


“Initialize expression”, “Test Condition expression” and “updationexpression”
Syntax:

for (initialize expression; test condition; updation )


{
Statement-1;
Statement-2;
}

47 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Flow chart: Entry

Initialization

False
Condition

True

Statements

Incr/decr

Out of for loop

for loop can be specified by different ways as shown

Syntax Output Remarks


for (; ; ) Infinite to loop No arguments
for (a=0; a< =20;) Infinite loop “a”is neither increased nor decreased.
for (a=0; a<=10; a++) Displays value “a” is increased from 0 to 10 curly braces
printf(“%d”, a) from 1 to 10 are not necessary default scope of for loop
is one statement after loop.
for (a=10; a>=0; a--) Displays value “a” is decreased from 10 to 0.
printf(“%d”, a); from 10 to 0

Program:Print the first five numbers starting from one together with their squares.

public class Demo {


public static void main(String args[])
{
for(int i=1;i<6;i++)
{
System.out.println("value="+i+"\tSquare="+(i*i));
}
}
}

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

Out of while loop

Program:Write a program to perform sum of 10 numbers (1 to 10) using while loop


public class Fun {
public static void main(String args[])
{
int sum=0, i=1;
while(i<11)
{
sum+=i;
i++;
}
System.out.println("Sum: "+sum);
}
}
Output:
Sum: 55

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 do-while is an exit-controlled loop statement. Because, in do-while, the condition is


checked at the end of the loop.
 The do-while loop executes until the condition becomes false. The Java programming
language also provides a do-while statement, which can be expressed as follows:
Syntax: Initialization Expression;
do {
statement(s)
updation expression;
} while(test condition);

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

Program:Write a program to find whether a number is prime or not.

public class Demo {


public static void main(String args[])
{
int p=21, i=2;
do
{
if(p%i==0)
{
System.out.println(p+" Not a prime number");
System.exit(0);
}
i++;
}while(i<p/2);
System.out.println(p+" is a prime number");
}
}
Output:
21 Not a prime number
51 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:Program to display even numbers up to 20

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

Unconditional Control Statements

1. The “break” Statement:

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

True Condition with break


in loop

False

Program:Example for break statement


public class Fun {
public static void main(String args[])
{
for(int i=1;i<10;i++)
{
if(i==5)
break;
System.out.print(i);
}
}
}

Output:
1234

2. The “continue” Statement:

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

The jump statement can be while, do while and for loop.

Flowchart: Entry

Condition Continue
with in loop True

Remaining part of loop

Program: Example for continue statement

public class Fun


{
public static void main(String args[])
{
for(int i=1;i<10;i++)
{
if(i==5)
continue;
System.out.print(” ”+i);
}
}
}

Output:
12346789

The continue statement can be used along with a label.


Continue label;
The label after continue represents the name of the loop to where the flow of execution should
jump. This is also called labeled continue statement.

54 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:The following program is an example of labeled continue statement.


public class Cont
{
public static void main(String args[])
{
int i=1,j;
lb1: while(i<=3)
{
System.out.print(i);
lb2: for(j=1; j<=5; j++)
{
System.out.println("\t"+j);
if(j==3)
{
i++;
continue lb1;
}
}
i++;
System.out.println("-----------");
}
}
}
Output:
1 1
2
3
2 1
2
3
3 1
2
3

3. The “return” statement:

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

return x; //return x value


return (x+y); //calculate x+y and return that value

Program: Example program for return statement

public class Return {


public static void main(String args[])
{
int res = Square(5);
System.out.println("Square is: "+res);
}
static int Square(int num)
{
return num*num;
}
}
Output:
Square is: 25

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.

Q) What are the programming constructs?


Answer: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop

Q) Out of do…while and while – which loop is efficient?


Answer:In a do…while loop the statements are executed without testing the condition, the
first time. From the second time the condition is observed. This means that the programmer
does not have control right from the beginning of its execution. In a while loop, the
condition is tested first and then only the statements are executed. This means it provides
better control right from the beginning. Hence, while loop is more efficient than do…while
loop.

Q) Why goto statements are not available in java?

Answer:goto statements lead to confusion for a programmer. Especially, in a large program,


if several goto statements are used, the programmer would be perplexed while
understanding the flow from where to where the control is jumping.

Q).What is the difference between return and System.exit(0)?


Answer:return statement is used inside a method to come out of it. System.exit(0) is used
in any method to come out of the program.

57 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Q).What is the difference between System.exit(0) and System.exit(1)?


Answer:System.exit(0) terminates the program normally, whereas System.exit(1)
terminates the program because of some error encountered in the program.

Q) What are difference between break and continue?


Answer:The break keyword halts the execution of the current loop and forces control out of
the loop.
Continue is similar to break, except that instead of halting the execution of the loop,
it starts the next iteration.

Q) Which of these statement is correct?


a) switch statement is more efficient than a set of nested ifs.
b) two case constants in the same switch can have identical values.
c) switch statement can only test for equality, whereas if statement can evaluate any
type of boolean expression.
d) it is possible to create a nested switch statements.
Answer:b
Explanation: No two case constants in the same switch can have identical values.

Q). Can a for statement loop indefinitely?


Answer:Yes.

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

Input and Output


Input represents data given to a program and output represents data displayed as a result
of a program. Java I/O (Input and Output) is used to process the input and produce the output
based on the input. Java uses the concept of stream to make I/O operation fast.

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.

A stream can carry data:

 From keyboard to memory or


 From memory to printer or
 From memory to a file.

Basically there are two types of streams:

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

 System.in: This represents InputStream object, which by default represents standard


input device, i.e. keyboard.
 System.out: This represents PrintStream object, which by default represents standard
output device, i.e. monitor.
 System.err: This represents PrintStream object, which by default represents monitor.

59 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Accepting input from the keyboard:


This can be done by two ways in java:
1. By using BufferedReader
2. By using Scanner
1. BufferedReader:
BufferedReader is a type of input stream; we are using BufferedReader as it has get
methods to read data properly coming from the streams.

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.

InputStreamReader obj=new InputStreamReader (System.in);

ii. Connect InputStreamReader to BufferedReader.

BufferedReader br=new BufferedReader (obj);

The above two statements can be combined and re-written in a single statement as:

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

60 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Now, we can read the data coming from the keyboard using methods available in
BufferedReader:

 read() – to read a character


 readLine() – to read a string

Accepting a character from the keyboard:

Now, follow these steps in order to accept a single character from the keyboard.

 Create a BufferedReader class object (br).


 Then, read a single character from the keyboard using read() method as:
char ch = br.read();

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:

char ch = (char) br.read();

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

Accepting a String from the keyboard:

String str = br.readLine ();

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.

Program: Accepting a name (String) from the keyboard.

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

Accepting other type of values from the keyboard:

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.

Program:Accepting and displaying employee details.


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();
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:
id: 99
gender: M
name:

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.

There are two solutions for this problem.

1) We should skip ‘\n’ characters from BufferedReader using


br.skip(2); //2 represents 2 characters
2) By using “readLine()” method to accept the gender as shown below.

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

Output: Enter year no:2016


It is 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

Displaying Output with System class:


There are 3 methods to display output. They are:

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

The following format characters can be used in printf():

 %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

Program:To understand the use of printf(), let us write a java program.


import java.util.*;
publicclassPrint
{
publicstaticvoid main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter id, sex, name, salary: ");
int id = sc.nextInt();
char sex = sc.next().charAt(0);
String name = sc.next();
float sal = sc.nextFloat();
System.out.printf("Id=%d%nSex=%c%nName=%s%nSalary=%8.2f",id,sex,
name,sal);
}
}
Output:
Enter id, sex, name, salary: 99 F swetha 20000
Id=99
Sex=F
Name=swetha
Salary=20000.00

Displaying formatted output with String.format():


If we want only a string that consists of formatted output, then we can take the help of
format() method of String class. The format characters supported by System.out.printf() are also
usable with format() method. Since, format() is a static method, we can call it as: String.format().
This method returns a string that contains the formatted output which can be processed and used
as the programmer wants it.

Program:Understanding format() method.


publicclass Format
{
publicstaticvoid main(String[] args) throws Exception
{
int age = 24;
String name = "sai";
char ch = 'M';
String str;
str = String.format("Age: %d%nName: %s%nGender: %c", age, name, ch);
System.out.println(str);
}
}
Output:
Age: 24
Name: sai
Gender: M

67 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Important Interview Questions:


Q).What is the difference between System.out and System.err?
Answer:System.out and System.err both represent the monitor by default and hence can be
used to send data or results to the monitor. But System.out is used to display normal
messages and results whereas System.err is used to display error messages.

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 are the methods in BufferedReader class?


Answer:BufferedReader class have two methods.
1. read() and
2. readLine() methods.

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.

Advantages of java arrays:

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

Arrays are generally categorized into two types:


1. Single dimensional arrays (or 1D arrays)
2. Multi dimensional arrays (or 2D, 3D,… arrays)

1. Single dimensional arrays (or 1D arrays)

A one dimensional array or a single dimensional array represents either a row or a


column of the elements. Example: Marks obtained by a student in 5 different subjects can be
represented by a 1D array because these marks can be written as a row or a column.

Syntax for creating 1D array:

There are different ways of creating arrays as shown below:

Case 1:We can declare a one dimensional array and can directly store elements at the time of
declaration only as below:

Syntax:int marks[] = {50,60,55,67,70};

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[0] marks[1] ……. marks[4]

marks[i]

Now, we want to access the elements of an array by using a for loop as shown below:

Syntax: for(int i=0;i<5;i++)


{
System.out.println(marks[i]);
}

Program 1:Write a program to create a 1D array and display its elements one by one by
using a loop.

public class Array


{
public static void main(String[] args)
{
int arr[] = {50,60,75,66,87};
for(int i=0;i<5;i++)
{
System.out.println(arr[i]);
}
}
}

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:

Example: for(int i=0;i<5;i++)


{
br is object of
marks[i] = Integer.parseInt(br.readLine());
BufferedReader
}

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:

o Stringnames[ ] = new String[10];


o float[ ] salary = {10.0f, 20.0f, 30.0f, 40.0f, 50.0f};

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

2. Multi dimensional arrays (or 2D, 3D,… arrays)

Multidimensional arrays are actually arrays of arrays. Multi dimensional arrays


represents 2D, 3D,… arrays which are combination of several earlier types of arrays. For
example, a two dimensional array is the combination of two or more 1D arrays. Similarly, a
three dimensional array is the combination of two or more 2D arrays.

73 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Two dimensional arrays (2D arrays):

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.

Syntax for creating 2D array:

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

j=0 j=1 j=2 j=3 j=4


i=0 50 65 70 75 80
i=1 80 90 98 99 35
i=2 45 55 65 86 77

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:

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

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

Three dimensional arrays (3D array):

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:

j=0 j=1 j=2 j=3 j=4


i=0 50 65 70 75 80
k=0 i=1 80 90 98 99 35
i=2 45 55 65 86 77

j=0 j=1 j=2 j=3 j=4


i=0 20 30 40 50 60
k=1 i=1 35 40 45 50 55
i=2 60 65 70 75 80

77 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program 2: Write a program in which we take a 3D array which consists of department


wise student marks. There are 3 departments and in each department, there are 2 students
and each student has marks in 3 subjects. Calculate total marks of each student.
import java.util.*;
public class Array
{
public static void main(String[] args)
{
int dept, student, marks, tot = 0;
int arr[][][] = {{{ 50, 60, 70, 75, 80 }, { 80, 90, 98, 99, 35 },{ 45, 55, 65, 86, 77 } },
{{ 20, 30, 40, 50, 60 },{ 35, 40, 45, 50, 55 },{ 60, 65, 70, 75, 80 } } };
for (dept = 0; dept < 2; dept++)
{
System.out.println("Department " + (dept + 1) + ": ");
for (student = 0; student < 3; student++)
{
System.out.println("student " + (student + 1) + "marks: ");
for (marks = 0; marks < 5; marks++)
{
System.out.print(arr[dept][student][marks] + " ");
tot += arr[dept][student][marks];
}
System.out.println("total: " + tot);
tot = 0;
}
System.out.println();
}
}
}

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.

Single dimensional array

For example, take the array arr[ ] with the size 10 and there are five elements in it, as:

Example: int arr[ ] = new int[10];


arr[0] = 50, arr[1] = 60, arr[2] = 70;

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.

Multi dimensional array

But, in case of a two or three dimensional array, ‘length’ property gives the number of rows of
the array, as given here:

Example: int arr[ ][ ] = new int[5][10];


int arr[ ][ ][ ] = new int[5][7][12];

In this case, arr.length returns 5.

Command Line Arguments:

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:

C:/> java prog 11 99 sai

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,

 11 is stored as args[0], C:/> java prog 11 99 sai

 99 is stored as args[1],
args[0] args[1] args[2]
 Sai is stored as args[2].

Command line arguments

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

Important Interview Questions:


Q).On which memory, arrays are created in java?
Answer:Arrays created on dynamic memory by JVM. There is no question of static memory
in Java: everything (variable, array, object etc.) is created on dynamic memory only.

Q). Can we re-size an array after it is created?


Answer:No, we can’t re-size an array after its creation. But in case of re initialization,
whatever data that is stored in the array before re initialization will be lost.

Q). Difference between a[] and []a in Java?


Answer:You can declare an array in Java by either prefixing or suffixing [] with variable.
There is not much difference between them if you are not creating more than one variable
in one line, but if you do then it creates different types of variables, as shown in following
example:
int a[], b; // first is int array, second is just int variable
int[] c, d; // both c and d are integer array

Q). Is it legal to initialize an array int i[] = {1, 2, 3, 4, 5};


Answer:Yes, it is perfectly legal. You can create and initialize array in same line in Java.

Q). How to get length of an array?


Answer:By using arrayname.length property to know the size/ length of an array.

Q). Can you pass the negative number as an array size?


Answer:No. You can’t pass the negative integer as an array size. If you pass, there will be
no compile time error but you will get NegativeArraySizeException at run time.

Q). what is ArrayIndexOutOfBoundsException in java? When it occurs?


Answer:ArrayIndexOutOfBoundsException is a run time exception which occurs when your
program tries to access invalid index of an array i.e negative index or index higher than the
size of the array.

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) What is ArrayStoreException in java? When you will get this exception?


Answer:ArrayStoreException is a run time exception which occurs when you try to store
non-compatible element in an array object. The type of the elements must be compatible
with the type of array object. For example, you can store only string elements in an array of
strings. if you try to insert integer element in an array of strings, you will get
ArrayStoreException at run time.

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

Q).What are the drawbacks of the arrays in java?


Answer:The main drawback of the arrays is that arrays are of fixed size. You can’t change
the size of the array once you create it. Therefore, you must know how many elements you
want in an array before creating it. You can’t insert or delete the elements once you create
an array. Only you can do is change the value of the elements.

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:

Syntax: String s =”Java”;

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:

There are three ways of creating strings in java. They are:


1. String Literal
2. Using new keyword
3. Using character array

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:

Syntax: String s = new String(“Hello”);


Here, we are doing two things:
 we are creating object using new operator.
 Storing string “Hello” into that object.

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:

Syntax: char arr[ ] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};


Now, create a string by passing this array name to is as:
String s = new String(arr);
Now, the String object ‘s’ contains the string: “Hello”. If we do not want all the
characters of the array into the String, then we can also mention which characters we
need as:
String s = new String(arr, 0, 4);
Here, starting from 0th character a total of 4characters are copied into the String
s. Hence, the string object ‘s’ in this case contains the string: “Hell”.

String Class Methods:

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.

Example: String str1 = “Hello ”;


String str2 = “welcome”;
System.out.println(str1.concat(str2));

In the above statements “str1.concat(str2)” method concatenates “Hello ”


and“welcome” into a single string “Hello welcome”.

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.

Example: String str1 = “Hello“;


System.out.println(str.length());
Output: 5

3) char charAt(int i): This method returns a character at specified location ‘i’.

Example: String str1 = “Hello“;


System.out.println(str1.charAt(2));
Output: l

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

7) String[] split(delimiter):This method is useful to break a string into pieces at places


represented by delimiter.
Example: String str1 = “hello, welcome. “;
String a[] = str1.split(“ ”);
for(int i=0; i<a.length; i++)
System.out.println(a[i]);
Output: hello,
welcome.
85 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
8) int compareTo(String s):This method is useful to compare two strings and to know
which string is bigger/smaller.
Example: String str1 = “ANT”;
String str2 = “AXE”;
System.out.println(str1.compareTo(str2));
Output: -10

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.

public class StringMethods


{
public static void main(String args[]){
String s1 = "A book on java";
String s2 = new String("I Like it");
char arr[] = {'T','a','k','e','o','f','f'};
String s3 = new String(arr);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println("Length of s1 : "+s1.length());
System.out.println("s1 and s2 joined : "+s1.concat(s2));
System.out.println(s1+" from "+s3);
boolean x = s1.startsWith("A");
if(x)
System.out.println("s1 starts with \'A\'");
else
System.out.println("s1 does not start with \'A\'");
String p = s2.substring(0,7);
String q = s3.substring(0,6);
System.out.println(p+q);
System.out.println("Upper s1 : "+s1.toUpperCase());
System.out.println("Lower s3 : "+s3.toLowerCase());
String[] s;
s = s2.split(" ");
System.out.println("Split of s2");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
}
}
Output:
A book on java
I Like it
Takeoff
Length of s1: 14
s1 and s2 joined : A book on javaI Like it
A book on java from Takeoff
s1 starts with 'A'
I Like Takeof
Upper s1 : A BOOK ON JAVA
Lower s3 : takeoff
Split of s2
I
Like
It

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:

The compareTo() method is used to compare two stringslexicographically, and


to know which string is bigger or smaller. Each character of both the strings is converted into
a Unicode value for comparison.This should be used as: s1.compareTo(s2). The character
sequence represented by this String object (s1) is compared lexicographically to the character
sequence represented by the argument string (s2).This method returns integer value like:

 Zero: if s1 is equal to s2, then this method returns zero.


 Positive value: if s1 is greater than s2, then this method returns positive integer value.
 Negative value: if s1 is smaller than s2, then this method returns negative value.

Program:Write a program to compare two strings using compareTo() method.


public class StrCompare
{
public static void main(String args[]){
String s1 = new String("Hello");
String s2 = new String("hello");
if(s1.compareTo(s2)==0)
System.out.println("Both are same");
else if(s1.compareTo(s2)<0)
System.out.println("s1 is smaller than s2 ");
else
System.out.println("s1 is bigger than s2 ");
}
}
Output:
s1 is smaller than s2

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.

Program:Write a program to compare two strings using ‘= =’ operator.


public class StrCompare1
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String("Hello");
if(s1==s2)
System.out.println("Both are same");
else
System.out.println("Not same");
}
}
Output:
Not same

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,

String s2 = new String(“Hello”);

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

Figure 1 Comparing the strings using == and equals()

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.

Program:Write a program to compare two strings using equals().

public class StrEquals


{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = “Hello";
if(s1.equals(s2))
{
System.out.println("Both are same");
}
else
{
System.out.println("Not same");
}
}
}
Output:
Both are same
91 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
The first statement in the program is:String s1 = “Hello”;here, JVM creates a String
object and stores “Hello” in it. Observe that we are not using new operator to create the string.
We are using assignment operator(=) for this purpose. So, after creating the String object, JVM
uses a separate block of memory which is called string constant pool and stores the object there.

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.

Program:Write a program to test the immutability of strings.


public class StrCompare {
public static void main(String args[])
{
String s1 = "Young";
String s2 = "minds";
s1 = s1+s2;
System.out.println(s1);
}
}
Output:Youngminds

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

Figure 3 Immutability of string blocks

Important Interview Questions:


Q). Is String a class or data type?
Answer:String is a class in java.lang package. But in Java, all classes are also considered as
data types. So we can take String as a data type also.

Q). Can we call a class as a data type?


Answer:Yes, a class is also called ‘user-defined’ data type. This is because a user can create
a class.

Q). How many objects will be created in the following code?


String s = new String("Welcome");
Answer:Two objects, one in string constant pool and other in non-pool(heap).

Q). What is the purpose of toString() method in java ?


Answer:The toString() method returns the string representation of any object. If you print
any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.

93 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Q). Can we use string for switch statement?


Answer:Yes to version 7. From JDK 7, we can use string as switch condition. Before version
6, we can not use string as switch condition.
switch (str.toLowerCase()) // java 7 only!
{
case "a": value = 1;
break;
case "b": value = 2;
break;
}

Q).What is a string constant pool?


Answer:String constant pool is a separate block of memory where the string objects are
held by JVM. If a string object is created directly, using assignment operator as:
String s1= “Hello”, then it is stored in string constant pool.

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.

Q). What is the meaning of immutable in terms of String?


Answer:The simple meaning of immutable is unmodifiable or unchangeable. Once string
object has been created, its value can't be changed.

Q). Explain the difference between following statement


String s=”World”;
String s=new String (“world”);
Answer:In First Statement assignment operator is used to assign the string .In this case
Jvm first check the String pool whether the same vale already available in the String
container or not and notify if available, if it is not available then it create another reference
to it.
In Second case each and every time it creates a new object of string.

Q). There are any other classes in java that is immutable?


Answer:All the wapper classes in java are immutable like. Integer, Flot.Double, etc

94 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

StringBuffer And StringBuilder


In the previous chapter it is clearly explained that the Strings are immutable and cannot
be modified. To overcome this, we got few more classes which represent strings in such a way
that their data can be modified and these classes are:

a. StringBuffer class
b. StringBuilder class

StringBufferclass:

The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters.


Following are the important points about StringBuffer:

 A string buffer is similar to a String, but can be modified.


 It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
 They are safe for use by multiple threads.
 Every string buffer has a capacity.

Creating StringBuffer Objects:

There are different ways to create a StringBuffer object based on the constructors it is having.
They are:

1. StringBuffer(String str): creates a string buffer with the specified string.


Syntax: StringBuffer sb = new StringBuffer(“Hello”);

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

4) StringBuffer reverse( ):This reverses the character sequence in the StringBuffer.


Example: StringBuffer sb = new StringBuffer(“abc”);
sb.reverse();
System.out.println(sb);
Output: cba

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

6) String toString():This converts the StringBuffer object into a string object.


Example: StringBuffer sb = new StringBuffer(“abc”);
String s = sb.toString();
System.out.println(s);
Output: abc

Some common methods in String and StringBuffer are:

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)

Program:Write a program to test whether a string is palindrome or not.


import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter string to check palindrome or not?");
String r=sc.next();
StringBuffer sd=new StringBuffer(r);
String temp=r;
r=sd.reverse().toString();
if(r.equals(temp))
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
Output:
Enter string to check palindrome or not? dad
Palindrome

97 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:Write a program to learn how to use some of StringBuffer class methods.


import java.io.*;
public class Fun
{
public static void main(String args[]) throws Exception
{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter surname: ");
String sur = br.readLine();
System.out.println("Enter first name: ");
String first = br.readLine();
System.out.println("Enter last name: ");
String last = br.readLine();
sb.append(sur);
sb.append(last);
System.out.println("Name: "+sb);
int n = sur.length();
sb.insert(n, first);
System.out.println("Full name: "+sb);
}
}
Output:
Enter surname: Allu
Enter first name: Arjun
Enter last name: Bunny
Name: Allu Bunny
Full name: Allu Arjun Bunny

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.

Important Interview Question:


Q).What is the difference between String and StringBuffer classes?
Answer:String class objects are immutable and hence their contents cannot be modified.
StringBuffer class objects are mutable, so they can be modified. Moreover the methods that
directly manipulate data of the object are not available in String class. Such methods are
available in StringBuffer class.

Q).Are there any other classes whose objects are immutable?


Answer:Yes, classes like Character, Byte, Integer, Float, Double, Long... called ‘wrapper
classes’ are created as ‘immutable’. Classes like Class, BigInteger, BigDecimal are also
immutable.

Q).What is the difference between StringBuilder and StringBuffer classes?


Answer:StringBuffer class is synchronized and StringBuilder is not. When the programmer
wants to use several threads, he should use StringBuffer as it gives reliable results. If only
one thread is used, StringBuilder is preferred, as it improves execution time.

Q) Which of the two "StringBuilder" or "StringBuffer" is faster and Why ?


Answer: StringBuilder is not synchronized and hence faster than StringBuffer.

Q) Special operations those we can only perform on StringBuffer and StringBuilder:


Answer: append
insert
delete
reverse
Since string is immutable we cannot perform these operations on String.

Q) Advantage and disadvantage of StringBuffer or StringBuilder:


Answer: Advantage: It given high performance because consumes less memory as all
modifications stored in same memory.
Disadvantage: Original value will not be preserved.

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

main task method1


sub task3

Procedure oriented approach

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

main task class3 data


methods
modules
tasks

Object oriented approach

100 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Differences between Procedure oriented approach and Object oriented approach:

Procedure Oriented Programming (POP) Object Oriented Programming(OOP)

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 follows Top Down approach. OOP follows Bottom Up approach.

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.

In POP, Overloading is not possible. In OOP, overloading is possible in the form of


Function Overloading and Operator Overloading.

Examples of POP are: C, VB, FORTRAN, Examples of OOP are: C++, JAVA, VB.NET,
and Pascal. C#.NET.

Features of object oriented approach:


There are many features of Object oriented approach, some of them are:

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

Properties: variables Properties: variables

name Raju
age 25
sex M

Actions: methods Actions: methods

talking talk()
walking walk()
eating eat()

Class: Person Object: Raju

Person class and Raju object

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 java language encapsulation can be achieved by class concept. A class is a container


which is collection of data members and methods. Encapsulation protects the inner
implementation of the members of the class from outside environment.

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.

To achieve encapsulation in Java:


 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.

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.

Important Interview Question:


Q) What is the difference between object oriented programming languages and object based
programming languages?
Answer:Object oriented programming languages follow all the features of Object Oriented
Programming System (OOPS). Smalltalk, Simula-67, C++, Java are examples for OOPS
languages.
Object based programming languages follow all the features of OOPS, except
inheritance. For example, JavaScript and VBScript will come under object based
programming languages.

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 the difference between a class and an object?


Answer:A class is a model for creating objects and does not exist physically. An object is
anything that exists physically. Both the class & objects contain variables and methods.

Q) What are the principle concepts of OOPS?


Answer:There are four principle concepts upon which object oriented design and
programming rest. They are:
Abstraction
Polymorphism
Inheritance
Encapsulation
Q) What is Abstraction?
Answer:Abstraction refers to the act of representing essential features without including the
background details or explanations.

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.

Q) What's singleton class ?


Answer:In object-oriented programming, a singleton class is a class that can have only one
object (an instance of the class) at a time.

105 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Classes and objects:


A class is a model for creating objects. This means the properties and actions of the
objects are written in the class. Properties are represented by variables and actions of the object
are represented by methods. So a class contains variables and methods. The same variables and
methods are also available in the objects because they are created from the class. These variables
are also called “instance variables” because they are created inside the object (instance).

A class is a group of objects that has common properties. It is a template or blueprint


from which objects are created. The keyword “class” is used to declare a class.

Syntax: class <class_name>


{
data member;
method;
}
If we take a person class, we can write code in the class that specifies the properties and
actions performed by person. For example, a person has properties like name, age, etc. Similarly
a person can perform actions like talking, walking, etc. So, the class Person can contains these
properties and actions, as shown below:
class Person
{
String name;
int age;
void talk()
{
System.out.println(“Hello I am”+name);
System.out.println(“My Age is”+age);
}
}

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

Syntax: class_name objectname=new class_name();

Example: Person p=new Person();

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.

Program: Write a java program to create a Person class with object


class Person
{
String name;
int age;
void talk()
{
System.out.println("Hello I am "+name);
System.out.println("My age is "+age);
}
}
publicclass PersonDemo
{
publicstaticvoid main(String args[])
{
Person p=new Person();
p.talk();
}
}

Output: Hello I am null


My age is 0

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

Initializing the instance variables:

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.

Example: Person p=new Person();


p.name=”sai”;
p.age=25;

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.

Example: private String name=”sai”;


Private int age=25;

Type3: we can initialize the instance variables using constructors.

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.

1) System-defined default constructor:If a class has not declared any user-defined


constructor then java compiler generates a constructor at the time of compilation known
as system-defined default constructor. This constructor will be executed defaultly.
2) User-defined default constructor:whenever a developer creating a constructor with in a
class without any parameters on its signature is known as user-defined default
constructor.

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
{

publicstaticvoid main(String[] args)


{
Takeoff tf=new Takeoff();
tf.display();
Takeoff tf2=new Takeoff();
tf2.display();
}
}
Output: Name=sai
Salary=20000.0
Name=sai
Salary=20000.0
110 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In the above program the two objects are initialized with same data.Parameterized
constructor is used to provide different values to the distinct objects.

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 {

publicstaticvoid main(String[] args){

Takeoff tf=new Takeoff();


tf.display();
Takeoff tf2=new Takeoff("vinay",30000.00f);
tf2.display();
}
}
Output: Name=sai and Salary=20000.0
Name=vinay and Salary=30000.0

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

this keyword can be used in two different ways:

1. this.
2. this( )

1. this. : Whenever datamembers of a class and formal parameters of a method or


constructor is existing with same name then system will get confused to overcome this
problem “this.” can be useful.

If any data member is preceded by ‘this.’ then that must be data member of class only.

 this can be used to refer to current class instance variable as:


this.variable
 this can be used to refer to current class method as:
this.methodname

112 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program: The following one is an example program to this.

class This
{
int id;
String name;

This(int id,String name)


{
this.id=id;
this.name=name;
}
void display()
{
System.out.println("Id="+id);
System.out.println("Name="+name);
}
}
publicclass ThisEx
{
publicstaticvoid main(String[] args)
{
This t=new This(1110,"sai");
t.display();
}

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

 this( ): this is used to referdefault constructor from another constructor.


 this(parameter1, parameter2 ,…): this is used to refer parameterized constructor from
another constructor.

113 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:The following one is an example program to this( ).

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

Important Interview Questions:

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.

Q) Can we declare a class as ‘private’?


Answer:No, if we declare a class as private, then it is not available to java compiler and
hence a compile time error occurs. But, inner classes can be declared as private.

Q) Does constructor return any value?


Answer:yes, that is current class instance (You cannot use return type yet it returns a
value).
114 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Q) When is a constructor called, before or after creating the object?
Answer:A constructor is called concurrently when the object creation is going on. JVM first
allocates memory for the object and then executes the constructor to initialize the instance
variables. By the time, object creation is completed; the constructor execution is also
completed.

Q) What is constructor overloading?


Answer:Writing two or more constructors with same name but difference in the parameters
is called constructor overloading. Such constructors are used to perform different tasks.

Q) What is the purpose of default constructor?


Answer:Default constructor provides the default values to the object like 0, null etc.
depending on the type.

Q) Can constructor perform other tasks instead of initialization?


Answer:Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

Q) What is difference between default constructor and parameterized constructor?


Answer:
Default constructor Parameterized constructor
It is useful to initialize all objects with It is useful to initialize each object
same data. with different data.
Default constructor does not have any Parameterized constructor will have 1
parameters. or more parameters.
When data is not passed at the time of When data is passed at the time of
creating an object, default constructor creating an object, parameterized
is called. constructor is called.

Q) What is difference between a constructor and a method?

Answer: Constructors Methods


A constructor is used to initialize the A method is used for any general
instance variables of a class. purpose processing or calculations.
A constructor’s name and class name A method’s name and class name can
should be same. be same or different.
A constructor is called at the time of A method can be called after creating
creating the object. the object.
A constructor is called only once per A method can be called several times
object. on the object.
A constructor is called and executed A method is executed only when we
automatically. call it.

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:

 Method header or Method prototype.


 Method body.

Method header or Method prototype:

It contains method name, method parameters and method return data type. Method
prototype is written in the form.

Syntax: returndatatype methodname(parameter1, parameter2,….)

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

Some examples of method declaration:

o double sum(double a, double b)


o void sum()In this example, the void keyword denotes that a method does not have a
return type. Methods must have a return type.
Method body:
Below the method header, we should write the method body. Method body contains a
group of statements which consists logic to perform the task. Method body can be written in the
following format.

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:

return x; // return x value


return (x+y); // return sum of x and y
return -1; // return -1
return obj; // return object obj
return arr; // return array arr

Example:

{
double c=a+b;
return c;
}

Note: A method can never return more than one value.

 return x,y; // invalid - returning two values


 return x; return y; // invalid – two executable return statements

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.

A static method cannot refer to “this” or “super” keywords in anyway.

Syntax: static returntype methodname(parameter1, parameter2,…..)

119 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:Write a java program for static method.

class Test
{
staticintx=55;
staticvoid access()
{
System.out.println("x="+x);
}
}
publicclass StaticDemo
{
publicstaticvoid main(String[] args)
{
Test.access();
}
}

Output: x=55

Static block:

A static block is a block of statements declared as static.

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

publicstaticvoid main(String[] args)


120 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
{
System.out.println("Inside main method");
}
}

Output: Inside static block


Inside main method

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.

There are two types of instance methods.

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

Employee e=new Employee();


e.setId(1110);
e.setName("sai");
e.setSal(20000.00);
System.out.println("Id:"+e.getId());
System.out.println("Name:"+e.getName());
System.out.println("Salary:"+e.getSal());
123 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
}
}
Output:Id:1110
Name:sai
Salary:20000.0

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.

Program: write a program to calculate factorial value by using Recursion.

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.

Important interview question:


Q) In how many ways can you create an object in java?

Answer: there are 4 ways of creating objects in java.

1. Using new operator.

Employee obj=new Employee();

Here we are creating Employee class object ‘obj’ using new operator.

2. Using factory methods:

NumberFormat obj=NumberFormat.getNumberInstance();

Here, we are creating NumberFormat class object using factory method

getNumberInstance().

3. Using newInstance() method. Here, we should follow two steps, as:

a. First, store the class name ‘Employee’ as a String into a object. For this purpose,

factory method forName() of the class ‘Class’ will be useful.

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 obj1=new Employee();

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

not available to static methods.

Q) Is it possible to compile and run a java program without writing main( ) method?

Answer: Yes, it is possible by using a static block in the java program.

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

Syntax: class Subclass-name extends Superclass-name


{
//methods and fields
}

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

Program:Example program showing single inheritance.


class A
{
void display()
{
System.out.println("Super class method");
}
}
class B extends A
{
void show()
{
System.out.println("sub class method");
}
}
public class SingleInheritance
{
public static void main(String args[])
{
B b = new B();
b.display();
b.show();
}
}
Output:
Super class method
sub class method

2. Multi-level inheritance: Whenever multiple classes are participating in inheritance in


sequential order, then such inheritance is called as “Multi-level Inheritance”. Inheritance
flow for the below figure can be represented as: “A B  C”.

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

Program:Example program showing Multi-level inheritance.


import java.util.*;
class A{
int x;
int y;
void read(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter two values:");
x = sc.nextInt();
y = sc.nextInt();
}
void sum(){
read();
System.out.println("Addition: "+(x+y));
}
}
class B extends A{
void sub(){
read();
System.out.println("Subtraction: "+(x-y));
}
}
class C extends B{
void mul(){
read();
System.out.println("Multiplication: "+(x*y));
}
}
public class Multilevel {
public static void main(String args[]){
C c = new C();
c.sum();
c.sub();
c.mul();
}
}
Output:
Enter two values:10 20
Addition: 30
Enter two values:20 10
Subtraction: 10
Enter two values:10 10
Multiplication: 100

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

Program:Example program showing Hierarchical inheritance.


class A
{
void display(){
System.out.println("Method of super class A");
}
}
class B extends A
{
void show(){
System.out.println("Method of sub class B\n");
}
}
class C extends A
{
void show(){
System.out.println("Method of sub class C");
}
}
public class HierarchicalInheritance
{
public static void main(String args[]){
B b = new B();
b.display();
b.show();
C c = new C();
c.display();
c.show();
}
}

Output:
Method of super class A
Method of sub class B

Method of super class A


Method of sub class C
129 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
4. Hybrid inheritance:The combination of multi-level and hierarchical inheritance is known as
“HybridInheritance”. Inheritance flow for the below figure can be represented as: “A  B,
A  C E, and A  D”.
Class A Class E is inherited from class C
which intern inherited from class
A (Multi-level inheritance).
Class B Class C Class D +
Classes B, C, D are inherited from
the same class A (Hierarchical
Class E inheritance).

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, BD, and C D”.

Class A Class B Class C


Class D inherits the all the
properties of multiple classes
like A, B, C.
Class 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

What is not possible using java class Inheritance?


1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses
in other packages, as these members are only accessible by their simple names in subclasses
within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by
a subclass.
4. A subclass can extend only one superclass

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.

Program:Write a Java program for illustrating about default constructors in inheritance.


class One
{
One()
{
System.out.println("Super class constructor");
}
}
class Two extends One
{
Two()
{
System.out.println("Sub class constructor");
}
}
public class InheritConstructor
{
public static void main(String[] args)
{
Two t = new Two();
}
}
Output:
Super class constructor
Sub class constructor
But, if we want to call parameterized constructor of base class, then we can call it using
the keyword super.

131 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

The Keyword “super”:

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:

1. super can be used to refer to super class variables, as:


Syntax: super.variable

2. super can be used to refer to super class methods, as:


Syntax: super.method( )

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)

Program:Write a Java program to understand that the parameterized constructors of


the super class can be called from sub class using super().
class Takeoff
{
int i;
Takeoff(int i){
this.i=i;
}
}
class Youngminds extends Takeoff
{
int i;
Youngminds(int a, int b){
super(a);
i=b;
}
void show(){
System.out.println("Sub class i= "+i);
System.out.println("Super class i= "+super.i);
}
}
public class Main
{
public static void main(String args[]){
Youngminds ym = new Youngminds(11,22);
ym.show();
}
}
Output:
Sub class i= 22
Super class i= 11
The final Keyword:

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 protected Specifier:

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

}
}

Output: Area of Square=30.25


Area of Rectangle=33.0

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.

Polymorphism using Methods:

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

Polymorphism is mainly classified into two types. They are:

1. Dynamic Polymorphism
2. Static Polymorphism

Dynamic Polymorphism:

The polymorphism exhibited at runtime is called “dynamic polymorphism” (or) the


process of binding method call with method body at run time is known as “dynamic
polymorphism”.This means when a method is called, the method call is bound to the method
body at the time of running the program, dynamically. In this case, Java compiler does not know
which method is called at the time of compilation. Only JVM knows at runtime which method is
to be executed. Hence, this is also called “runtime polymorphism’ or ‘dynamic binding’.

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.

Important Interview Question:


Q).What is method signature?
Answer:
Method signature represents the method name along with method parameters.

Let us take a class “Sample” with two instance method having same name as:

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

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:

s.add(10,15); //s is the object of Sample class


137 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

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:

1. There may be a difference in the number of parameters passed to the methods.


Example: void add(int a, int b)
void add(int a, int b, int c)
In this case, if we call add(10,15) then JVM executes the first method and if we call
add(10,15,22) then it runs the second method.

2. There may be a difference in the data types of parameters.


Example: void add(int a, float b)
void add(double a, double b)
In this case, if we call add(10,15.5f) then JVM executes the first method and if we call
add(10.5 ,15.5) then it runs the second method.

3. There may be a difference in the sequence (orderliness) of the parameters


Example: void add(int a, float b)
void add(float a, int b)
In this case, if we call add(10,15.5f) then JVM executes the first method and if we call
add(10.5f ,20) then it runs the second method.

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.

Syntax: class <base class name>


{
return_type method()
{
---------
}
}
class <sub class name>
{
return_type method()
{
---------
}
}

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.

Program:Write a Java program for method overriding.


class One
{
void calculate(double x)
{
System.out.println("Square value: "+(x*x));
}
}
class Two extends One
{
void calculate(double x)
{
System.out.println("Square Root: "+Math.sqrt(x));
}
}
public class Poly
{
public static void main(String args[])
{
Two t=new Two();
t.calculate(25);
}
}
Output:
Square Root: 5.0

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:

The polymorphism exhibited at compilation time is called “static polymorphism” (or)


whenever method call binds with method body at the time of compilation is known as “static
polymorphism”. This is also known as “static binding” or “compile time polymorphism” or
“earlier binding”.

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

Program:Write a Java program for static polymorphism.


class One
{
static void calculate(double x)
{
System.out.println("Square value: "+(x*x));
}
}
class Two extends One
{
static void calculate(double x)
{
System.out.println("Square root value: "+Math.sqrt(x));
}
}
public class Static
{
public static void main(String[] args)
{
One o = new Two();
o.calculate(25);
}

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

2. Method overloading is done in same Method overriding is done in super and


class. sub classes.
3. In method overloading, method return In method overriding, method return
type can be same or different. types should also be same.
4. Method overloading is done when the Method overriding is done when the
programmer wants to extend the programmer wants to provide a
already available features. different implementation (body) for the
same feature.
5. Method overloading is code Method overriding is code replacement.
refinement. Same method is refined to The sub class method overrides
perform a different task. (replaces) the super class method.

142 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Polymorphism with Private Methods:

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.

Important Interview Question:


Q).Can you override private methods?
Answer:
No. Private methods are not available in the sub classes, so they cannot be
overridden.

Polymorphism with Final Methods:

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

Important Interview Question:


Q). what is final?
Answer:
‘final’ is a keyword is used in two ways:
 It is used to declare constants as: final double PI = 3.14159;
 It is used to prevent inheritance as:
final class A //sub class to A cannot be created.

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.

Types of data types:

In java there are two types of data types.

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:

any array, any class (String, StringBuffer, Employee, Manager etc.)

Important interview question:


Q) What is the difference between primitive data types and advanced 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

types, methods are available to perform various operations.

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.

Casting primitive data types:

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.

byte, short, char, int, long, float, double


lower --------------------------------------------------------higher

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.

Widening in primitive data types:

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

Important interview question:


Q) What is automatic 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.

Narrowing in primitive data types:


Converting a higher data type into a lower data type is called ‘narrowing’. Take the
example:

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

Important interview question:


Q) What is explicit casting?

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.

Casting Referenced data types:

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.

University Super class

College Sub class

Department Sub – sub class

Relationship of classes by the way of inheritance

Generalization and specialization:

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.

Important interview question


Q) What is generalization and specialization?

Answer: Generalization is a phenomenon when a sub class is promoted to a super class, and hence

becomes more general. Generalization needs widening or up-casting. Specialization is phenomenon

where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.

Widening in Referenced data types:


We can convert sub class type into super class type is called widening. For example: take
class One as super class and class Two as sub class. We do widening by using super class
reference to refer to sub class object. In this case, we convert the sub class object type as super
class type.

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 {

publicstaticvoid main(String[] args) {


One o;
o=(One)new Two(); // (or) o=new Two();
o.show();
}
}

Output: super class method

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:

Cast.java:22: error: cannot find symbol


o.show2( );
^
symbol: method show2( )
location: variable o of type One
1 error

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 in Referenced data types:

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 {

publicstaticvoid main(String[] args) {


Two t;
t=(Two) new One();
t.show();
}

Exception in thread "main" java.lang.ClassCastException:


One cannot be cast to Two
at NarrowCast.main(Cast.java:20)
150 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
By observing the output f the above program, we can understand that the method call t.show()is not
executing the super class method. Similarly, write another statement and call the sub class method
show2() as:

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 {

publicstaticvoid main(String[] args) {

One o;
o=new Two();
Two t=(Two)o;
t.show();
t.show2();
}
}

Output: super class method


Sub class method

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.

The following program is an example for illustrating the need of abstraction.

Program:
class Demo
{
void calculate(double x)
{
System.out.println("Square="+(x*x));
}
}
publicclass Abs
{

publicstaticvoid main(String[] args)


{
Demo d1=new Demo();
Demo d2=new Demo();
Demo d3=new Demo();
d1.calculate(3);
d2.calculate(4);
d3.calculate(5);
}
}
Output: Square=9.0
Square=16.0
Square=25.0

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

calculate calculate calculate


square square root cube

obj1 Obj2 Obj3

Defining a method in sub classes to suit the objects

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

Abstract method and abstract class:

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.

Syntax:abstract returntype methodname( parameter1, parameter2,…….);

 If any class contains atleast one abstract method that class becomes abstract class.

Syntax: abstract class <class name>


{
abstract returntype methodname(parameter1, parameter2,……..);
.
.
.
returntype methodname(parameter1, parameter2,…….)
{
Statements;
}
}
 abstract class contains abstract methods, concrete methods and also instance variables.
 All the abstract methods of the abstract class should be implemented in its subclasses.
The programmer can create objects to those subclasses only.
 We cannot create an object to abstract class but we can create a reference variable to it,
this reference variable of abstract class can be used to refer the objects of its subclasses.

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.

Car abstract class

Maruti Santro sub classes

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

class Maruti extends Car


{
Maruti(int regno)
{
super(regno);
}
void steering(int direction, int angle)
{
System.out.println("Maruti uses manual steering");
System.out.println("Take a turn");
}
void braking(int force)
{
System.out.println("Maruti uses hydraulic brakes");
System.out.println("Apply brakes and stop the car");
}
}

class Santro extends Car


{
Santro(int regno)
{
super(regno);
}
void steering(int direction, int angle)
{
System.out.println("Santro uses power steering");
System.out.println("Take a turn");
}
void braking(int force)
{
System.out.println("Santro uses gas brakes");
System.out.println("Apply brakes and stop the car");
}
}

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

In the preceding program, if reference is used to refer to Santro object, as

ref=s;

Please take car key


And fill fuel into the tank
Santro uses power steering
Take a turn
Santro uses gas brakes
Apply brakes and stop the car

We cannot declare a class as both abstract and final, For example:

abstract final class A // invalid

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.

Important interview question:


Q) Can you declare a class as abstract and final also?
Answer:No. abstract class needs sub classes. final keyword represents sub classes which
cannot be created. So, both are quite contradictory and cannot be used for same 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:

1. It is used to achieve fully abstraction.


2. By interface, we can support the functionality of multiple inheritance.
3. The main advantage is common reusability.

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

Object of class1 Object of class2

Figure 1 Interface and its implementation classes.

Implementing interface:

If a class implements an interface, indicate that the class is signing a contract,agreeing to


perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract. Implementing an interface is done by using
“implements”keyword.

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

Figure 2 Interface communicating with databases

Relationship between Interfaces and Classes:

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

Multiple Inheritance using Interfaces:

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
}

And there is an implementation class MyClass as:

class MyClass implements A,B //Now there is no confusion to refer to any member of interface

Important Interview Question:


Q). Can you implement one interface from another?
Answer:
No, we cannot. Implementing an interface means writing body for the methods. This
cannot be done again in an interface, since none of the methods of the interface can have
body.

163 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program:Write a program to illustrate how to achieve multiple inheritance using multiple


interfaces.
interface Father
{
float ht = 6.2f;
void height();
}
interface Mother
{
float ht = 5.8f;
void height();
}
class Child implements Father, Mother
{
public void height()
{
float ht = (Father.ht+Mother.ht)/2;
System.out.println("Child's height= "+ht);
}
}
public class Multi
{
public static void main(String[] args)
{
Child ch = new Child();
ch.height();
}
}
Output:
Child's height= 6.0

164 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Abstract Classes vs. Interfaces:

Abstract Class Interface


Abstract class is declared by using the Interface is declared using the keyword
keyword “abstract”. “interface”.
An abstract class may contain instance An interface cannot contain instance
variables. variables. It contains only static and final
(Constant) variables.
An abstract class can contain some abstract An interface contains only abstract
methods and also some concrete methods. methods.
A class uses “extends” keyword to extend A class uses “implements”keyword to
an abstract class. implement an interface.

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.

Packages are mainly classified into two types.

I. Built-in or predefined packages


II. User defined packages

Built-in or predefined packages:

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.

1) java.lang:It is a predefined package, which is a collection of predefined classes and


interfaces. Using these properties we can able to perform various operations like,
handling of exceptions, handling of threads, handling of printing related statements,
wrapper classes and there are String and StringBuffer classes to handle Strings. It is a
default package for every java program.

Syntax: import java.lang.*;

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.

Syntax: import java.util.*;

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.

Syntax: import java.io.*;

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.

Syntax: import java.awt.*;


import java.awt.event.*;
5) javax.swing:This package helps to develop GUI like “java.awt”. the x in javaxrepresents
that is an extended package, which means, it is a package developed from another
package by adding new features to it. “javax.swing”is an extended package of
“java.awt”
Syntax: import javax.swing.*;

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.

Syntax: import java.net.*;

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.

Syntax: import java.applet.*;

8) java.text: This package has two important classes, DateFormat to format dates and times,
NumberFormat which is useful to format numeric values.

Syntax: import java.text.*;

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.

Syntax: import java.sql.*;

Java directory
java.io
io sub directory

Java.lang lang directory

awt directory
Java.awt

Java.awt.event event sub directory

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”

Syntax:package <packagename>; // to create a package


package <packagename.subpackage>; // to create a sub package with in a package

Rules to create a package:

1) Every package statement should exist as first statement in the program.


2) Every package program should contain either one public class (or) public interface.
3) Package program should not contain any main class.
4) Every package program should create with public classname.java.

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

How to compile a java program that contains a package:

Any package program in java can be compiled with the following syntax.

Syntax:javac –d directory javafilename

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.

The javafilename is the name of the java class file to compile.

Example1:c:/> javac –d . Addition.java

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

Example2:c:/> javac d:/sai Addition.java

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

Accessing of package properties:

Package properties are mainly accessed in two different ways.

1) Using fully qualified name.


2) Using import statement.

170 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Using fully qualified name:

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.

Syntax:packagename.subpackgename.subsubpackagename.---- .classname obj =


new packagename.subpackgename.subsubpackagename.---- .classname();
Example:pack.Addition a=new pack.Addition();

Program:Write a java program to use Addition class of package pack.


class Use {
public static void main(String[] args) {
pack.Addition obj=new pack.Addition(10.0,15.0);
obj.sum();
}
}
Output: sum=25.0

Using import statement:

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

Program:Write a java program to use import statement in a different way. Remove


Addition.java & Subtraction.java from current directory and then test this program.
import pack.*;
class ImportDemo
{
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

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.

Program:Write a java program to create an interface with a single method to display


system date and time.

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

Access specifiers in java:

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.

Access within class within package outside package outside package


specifiers by subclass only
Private √ X X X
Default √ √ X X
Protected √ √ √ X
Public √ √ √ √

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

Types of Errors in java:

There are basically three types of errors in the java program:

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.

Program:Write a program to demonstrate compile-time errors.


public class CErr
{
public static void main(String args[])
{
System.out.println("Hello")//missing semicolon(;)
}
}

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.

Program: Write a program to demonstrate run-time errors.


public class RErr
{
public static void main(String args[])
{
int arr[]={1,2,3,4,5};
System.out.println(arr[50]);//there is no index 50 for the array arr.
}
}
Output:
javac RErr.java
java RErr
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50
at RErr.main(RErr.java:6)

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.

Program: Write a program to demonstrate Logical errors.


public class LErr
{
public static void main(String args[])
{
double sal = 5000.00;
sal = sal*15/100; //wrong usage. Instead use: sal += sal*15.100;
System.out.println("incremented salary: "+sal);
}
}
Output:
javac LErr.java
java LErr
incremented salary: 750.0

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

Important Interview Question:


Q).What is the difference between an exception and an error?
Answer:
An exception is an error which can be handled. It means when an exception
happens, the programmer can do something to avoid any harm. But an error is an error
which cannot be handled, it happens and the programmer cannot do anything.

Q).What are checked exceptions?


Answer:
The exceptions detected by java compiler at compilation time are called checked
exceptions.
Example: IOException, ClassNotFoundException.

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.

Important Interview Question:

Q).What is the super class for all exceptions in Java?


Answer:
Exception is the super class for all Exceptions in Java.

177 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

java.lang

Object

Throwable

Error U Exception

All errors Runtime Other


U
Exception Exception

U  Unchecked Exceptions

Important Interview Question:

Q).What is Throwable?
Answer:
Throwable is a class that represents all errors and exceptions.

Program: Write a program to understand the effect of an Exception.


public class Ex
{
public static void main(String args[]){
System.out.println("open files");
int n = args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
System.out.println("close files");
}
}
Output:
javac Ex.java
java Ex
open files
n= 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Ex.main(Ex.java:8)

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.

 A user has entered invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out
of memory.

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.

Syntax: catch(ExceptionClass ref)


Exceptiondetails
{
statements;
} Exceptionstack
The reference ref above is automatically adjusted to refer to the exception stack where the
details of the exception are available, as shown above. So, we can display the exception details
using any one of the following:
 Using print() or println(), such as System.out.println(ref);
 Using printStackTrace() method of Throwable class.

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

Handling Multiple Exceptions:

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:

Syntax: Catch(ExceptionType1 | ExceptionType2 e)


{
e.printStackTrace();
}

Example: Catch(ArithmeticException | ArrayIndexOutOfBoundsException e)


{
e.printStackTrace();
}

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

Syntax: throws exception;

Example: throws IOException; //handling single Exception


(Or)
throws IOException, ClassNotFoundException; //handling multiple Exceptions

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:

static void accept() throws IOException


public static void main(String[] args) throws IOException
185 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

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:

throw new NullPointerException(“Exception Data”);

In the above statement, NullPointerException class object is created and “Exception


Data” is stored into its object. Then it is thrown using throw statement and this can be handled by
using a catch block.

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.

Creating user-defined 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;

Important Interview Question:


Q).What is difference between throws and throw?
Answer:throws clause is used when the programmer does not want to handle the exception
and throw it out of a method. throw clause is used when the programmer wants to throw an
exception explicitly and wants to handle it using catch block. Hence, throw and throws are
contradictory.

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

The Wrapper Classes


Why wrapper classes:

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

Figure: Character class object contains char type field in it.

190 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Types of Wrapper classes:

1. Character - stores char primitive data type


2. Byte - stores byte primitive data type
3. Short - stores short primitive data type
4. Integer - stores int primitive data type
5. Long - stores long primitive data type
6. Float - stores float primitive data type
7. Double - stores double primitive data type
8. Boolean - stores boolean primitive data type

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.

Number Class Methods:

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

Character class Methods:

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 class has two constructors. They are:

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

Byte class Methods:

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 class has two constructors. They are:

 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

Short class Methods:

1) int compareTo(Shortobj): This method is useful to compare the contents of two


Short class objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Short 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 Short object with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static short parseShort(String str): This method returns int equivalent of the String
‘str’.
4) String toString():This methods converts Short object into String object and returns
that String object.
5) static Short valueOf(String str): This method converts a string str that contains
some short number into Short class object and returns that object.

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 class has two constructors. They are:

 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

Integer class Methods:

1) int compareTo(Integerobj): This method is useful to compare the contents of two


Integer class objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Integer 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 Integer object with any other
object obj. If both have same content, then it returns true, otherwise false.
3) static int parseInt(String str): This method returns int equivalent of the String ‘str’.
4) String toString():This methods converts Integer object into String object and returns
that String object.
5) static Integer valueOf(String str): This method converts a string str that contains
some int number into Integer class object and returns that object.
6) static String toBinaryString(int i):This method converts the decimal integer number
‘i’ into binary number system and returns that binary number as a String.
7) static String toHexString(int i):This method converts the decimal integer number ‘i’
into hexdecimal number system and returns that hexadecimal number as a String.
8) static String toOctalString(int i):This method converts the decimal integer number
‘i’ into octal number system and returns that octal number as a String.
9) int intValue(): This method converts Integer object into primitive int type value. This
is called unboxing.

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 class has two constructors. They are:

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

Long class Methods:

1) int compareTo(Longobj): This method is useful to compare the contents of two


Long class objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Long 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.

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:

Long class has two constructors. They are:

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

Float class Methods:

1) int compareTo(Floatobj): This method is useful to compare the contents of two


Float class objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Float 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.

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:

Doubleclass has two constructors. They are:

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

Double class Methods:

1) int compareTo(Doubleobj): This method is useful to compare the contents of two


Doubleclass objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Doubleclass 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.

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:

Booleanclass has two constructors. They are:

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

Boolean class Methods:

1) int compareTo(Booleanobj): This method is useful to compare the numerical value


of two Booleanclass objects.
For example: obj1.compareTo(obj2) //where obj1, obj2 are Booleanclass 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.
201 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
2) boolean equals(Object obj): This method compares the Booleanobject with any
other object obj. If both have same content, then it returns true, otherwise false.
3) static Boolean parseBoolean(String str): This method returns booleanequivalent of
the String ‘str’.
4) String toString():This methods converts Booleanobject into String object and returns
that String object.
5) static Boolean valueOf(String str): This method converts a string str that contains
some booleanvalue into Booleanclass object and returns that object.

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.

Math class Methods:

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

Important Interview Question:


Q). Why do we need wrapper classes?
Answer:
1. They convert primitive datatypes to objects and this id needed on internet to
communicate between two applications.
2. The classes in java.util package handle only objects and hence wrapper classes help in
this case also.

Q). Which of the wrapper class contains only one constructor?


Answer:Character.

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

Q).What happens if a string “Hello” is passed to parseInt() method?


Answer:Ideally, a string with an integer value should be passed to parseInt() method. So,
on passing “Hello” an exception called “NumberFormatException” occurs since the
parseInt() method cannot convert the given string “Hello” into an integer value.

204 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

The Collection Framework


Why collections:

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:

A collections framework is a unified architecture for representing and manipulating


collections. All collections frameworks contain the following:

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 Framework Hierarchy:

Collection
<interface>

Set List Queue


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

Retrieving elements from collections:

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:

 boolean hasMoreElements(): This method returns true if Enumeration has more


elements.
 element nextElement(): This method returns the next element in the Enumeration.

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.

Creating HashSet object:

We can create a HashSet objects in many different ways as shown below:

a. HashSet<String> hs = new HashSet<String>();

The preceding statement constructs aHashSet which stores String type objects.
We can also mention the capacity at the time of creating ArrayList object as:

b. HashSet<T> hs = new HashSet<T>(100);

The preceding statement constructs aHashSet with a initial capacity declared as


101.This capacity may increase automatically when more number of elements are being
stored.

HashSet class methods:

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.

6) int size():This returns the number of elements present in the HashSet.

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:

LinkedHashSet is also an implementation of Set interface, it is similar to the


HashSet except the below mentioned differences:
 HashSet doesn’t maintain any kind of order of its elements.
 LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence
in which they have been added to the Set.

LinkedHashSet class declaration is as follows: class LinkedHashSet<T>


Here, T is the type of elements that is stored in LinkedHashSet Object.

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:

i. push operation: Inserting elements into the stack.


ii. pop operation: Removing elements from the stack.
iii. peek operation: Searching for an element in the 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

Creating Stack Object:

Suppose, we want to create a Stack object that contains Integer objects, we can do
so as shown here:

Stack<Integer> obj = new Stack<Integer>();

Stack class methods:

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

Program: Write a program to perform different operations on a stack through a menu.


import java.io.*;
import java.util.*;
public class StackDemo
{
public static void main(String[] args) throws Exception
{
Stack<Integer> st=new Stack<Integer>();
int choice=0;
int position,element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice<4)
{
System.out.println("Stack operations");
System.out.println("1 push");
System.out.println("2 Pop");
System.out.println("3 Search");
System.out.println("4 Exit");
System.out.println("Your choice:");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:System.out.println("Enter element:");
element=Integer.parseInt(br.readLine());
st.push(element);
break;
case 2:Integer obj=st.pop();
System.out.println("popped="+obj);
break;
case 3:System.out.println("Which element:");
element=Integer.parseInt(br.readLine());
position=st.search(element);
if(position==-1)
System.out.println("Element not found");
else
System.out.println("Position="+position);
break;
default:return;
}
System.out.println("Stack contents:"+st);
}
}
}
Output:
Stack operations
1 push
2 Pop
3 Search
4 Exit
Your choice:1
Enter element:99
Stack contents:[99]

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:

LinkedList is a doubly-linked list implementation of the List interfaces. A Linked


list contains a group of elements in the form of nodes. Each node will have three fields:
i. A data field which contains data.
ii. Two link fields which contains references to previous and next nodes.

link data link


Node structure

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:

class LinkedList<E>//E stands for element type.

Creating LinkedList object:

We can create an empty linked list for storing String type elements (objects) as:

LinkedList<String> ll = new LinkedList<String>();

214 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

LinkedList class methods:

To add Elements to the List:

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.

To remove Elements from the 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.

To retrieve Elements from the 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

Remaining Methods of LinkedList Class:

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.

Program: Write a program that shows the use of linked list.


import java.io.*;
import java.util.*;
public class LLDemo
{
public static void main(String args[]) throws IOException
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("America");
ll.add("India");
ll.add("Japan");
System.out.println("List="+ll);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String element;
int position,choice=0;
while(choice<4)
{
System.out.println("\nLinkedList Operations");
System.out.println("1. Add an element");
System.out.println("2. Remove an element");
System.out.println("3. Change an element");
System.out.println("4. Exit");
System.out.println("Your choice:");
choice=Integer.parseInt(br.readLine());
switch (choice)
{
case 1:
System.out.println("Enter element:");
element = br.readLine();
System.out.println("At what position:");
position = Integer.parseInt(br.readLine());
ll.add(element);

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:

List=[America, India, Japan]


LinkedList Operations
1. Add an element
2. Remove an element
3. Change an element
4. Exit
Your choice:1
Enter element:Iraq
At what position:1
List=Iraq America India Japan

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:

class ArrayList<E> //E stands for element type.


Creating ArrayList object:
We can create a ArrayList objects in many different ways as shown below:
c. ArrayList<String> arl = new ArrayList<String>();
The preceding statement constructs an ArrayList with a default initial capacity
of 10. We can also mention the capacity at the time of creating ArrayList object as:
d. ArrayList<Double> arl = new ArrayList<Double>(101);
The preceding statement constructs an ArrayList with a default initial capacity
declared as 101.
ArrayList class methods:

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.

It is recommended to use ArrayList (it is non-synchronized, gives good


performance) in place of Vector when there is no need of thread-safe operations. Vector class
can be written as:

class Vector<E> //E stands for element type.

Creating Vector object:

We can create a Vector objects in many different ways as shown below:

a. Vector<Float> v = new Vector<Float>();

The preceding statement creates a Vector object v which can be used to store
Float type objects. The default capacity will be 10.

b. Vector<Integer> v = new Vector<Integer>(200);

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.

c. Vector<Integer> v = new Vector<Integer>(200, 50);

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

Vector class methods:

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

Program: Write a program that shows the use of Vector class.


import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector<Integer> v=new Vector<Integer>();
int x[]={99,90,88,80,77,70};
for(int i=0;i<x.length;i++)
{
v.add(x[i]);
}
System.out.println("vector elements:");

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:

public interface Queue<E> extends Collection<E>//E stands for element type.

Each Queue method exists in two forms:

a. Each Queue method exists in two forms:


b. the other returns a special value if the operation fails (either null or false, depending on
the operation)

Queue Interface
Structure
Type of Throws Returns special value
Operation exception (null or false)

Insert add(obj) offer(obj)

Remove remove() poll()

Examine element() peek()

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

It is possible for a Queue implementation to restrict the number of elements that it


holds; such queues are known as bounded.

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:

 remove() method throws NoSuchElementException.


 poll() method returns null.

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:

 element() method throws NoSuchElementException.


 peek() method returns null.

a. LinkedList:

LinkedList of Queue interface is similar to the LinkedList of Stack interface except


that if works in FIFO manner. Queue implementations generally do not allow insertion
of null elements. The LinkedList implementation is an exception. It permits null elements.

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.

Creating HashMap object:The different ways of creating HashMap objects are:

a. HashMap<String, Integer> hm = new HashMap<String, Integer>();

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

b. HashMap<String, Integer> hm = new HashMap<String, Integer>(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.

c. HashMap<String, Integer> hm = new HashMap<String, Integer>(60, 0.5);

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.

HashMap class methods:

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

Program: Write a program that shows the use of HashMap class.


import java.io.*;
import java.util.*;
public class HashMapDemo
{
public static void main(String args[]) throws IOException
{
HashMap<String, Long> hm=new HashMap<String, Long>();
String name;
Long phno;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1. Enter Phone entries");
System.out.println("2. Lookup in the book");
System.out.println("3. Display Names in book");
System.out.println("4. Exit");
System.out.println("Your Choice:");
int n=Integer.parseInt(br.readLine());
switch(n)
{
case 1:
System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter phno:");
phno=Long.parseLong(br.readLine());
hm.put(name, phno);
break;
case 2:
System.out.println("Enter name:");
name=br.readLine();
name=name.trim();
phno=hm.get(name);
System.out.println("phno:"+phno);
break;
case 3:
Set<String> set=new HashSet<String>();
set=hm.keySet();
System.out.println(set);
break;
case 4:
return;
}
}
}
}
Output:
1. Enter Phone entries
2. Lookup in the book
3. Display Names in book
4. Exit
Your Choice:1
Enter name:Swetha
Enter phno: 9849675341
227 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.

Creating Hashtable object:The different ways of creating Hashtable objects are:

a. Hashtable<String, Integer> ht = new Hashtable<String, Integer>();

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.

b. Hashtable<String, Integer> ht = new Hashtable<String, Integer>(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.

c. Hashtable<String, Integer> ht = new Hashtable<String, Integer>(80, 0.5);

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

Hashtable class methods:

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.

Program: Write a program that shows the use of Hashtable class.


import java.io.*;
import java.util.*;
public class HashTableDemo
{
public static void main(String args[]) throws IOException
{
Hashtable<String, Integer> ht=new Hashtable<String, Integer>();
ht.put("Ajay", 50);
ht.put("Sachin", 77);
ht.put("Gavaskar", 44);
ht.put("Kapil", 60);
ht.put("Dhoni", 88);
System.out.println("The Player names:");
Enumeration e=ht.keys();
while(e.hasMoreElements())
System.out.println(e.nextElement());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Player name:");
String name=br.readLine();
Integer score=ht.get(name);
if(score!=null)
{
int sc=score.intValue();
System.out.println(name+" Scored: "+sc);
}
229 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
else
{
System.out.println("Player not found");
}
}
}

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

Arrays class methods:

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

Program: Write a program that shows the use of Arrays class.


import java.io.*;
import java.util.*;
public class ArraysDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int arr[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.println("Enter an Integer:");
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("Contents of the array:");
display(arr);
Arrays.sort(arr);
System.out.println("The Sorted array:");
display(arr);
System.out.println("which element to search?");
int element=Integer.parseInt(br.readLine());
int index=Arrays.binarySearch(arr, element);
if(index<0)
System.out.println("Element not found");
else
System.out.println("Element not found at location:"+(index+1));
}
static void display(int arr[])
{
for(int i:arr)
System.out.print(i+” ”);
}
}

Output:

Enter an Integer: 99
Enter an Integer: 111
Enter an Integer: 22
Enter an Integer: 88
Enter an Integer: 55

Contents of the array: 99 111 22 88 55


The Sorted array: 22 55 88 99 111
which element to search? 99
Element not found at location: 4

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.

Creating StringTokenizer object:

Different ways of creating StringTokenizer objects are given below:

a. StringTokenizer st = new StringTokenizer(str, “delimiter”);

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:

 StringTokenizer st = new StringTokenizer(str, “,”);


 StringTokenizer st = new StringTokenizer(str, “.,:”);

b. StringTokenizer st = new StringTokenizer(str);

In the preceding statement, the delimiter is not specified. Hence the “space” is
considered as default delimiter.

StringTokenizer class methods:

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

Program: Write a program that shows the use of StringTokenizer class.


import java.util.*;

public class STDemo


{
public static void main(String args[])
{
String str1="Hello,World";
StringTokenizer st1=new StringTokenizer(str1, ",");

System.out.println("Given String 1: "+str1);


System.out.println("The Tokens for String 1 are:");
while(st1.hasMoreElements())
{
String one=st1.nextToken();
System.out.println(one);
}

String str2="Hello. How are you?";


StringTokenizer st2=new StringTokenizer(str2);
System.out.println("\nGiven String 2: "+str2);
System.out.println("The Tokens for String 2 are:");
while(st2.hasMoreElements())
{
String one=st2.nextToken();
System.out.println(one);
}
}
}

Output:
Given String 1: Hello,World
The Tokens for String 1 are:
Hello
World

Given String 2: Hello. How are You?


The Tokens for String 2 are:
Hello.
How
are
You?

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:

 It helps in knowing the system date and time.


 It helps in storing a date and time value which can be used later.

To create an object to the Calendar class, we can write:

Calendar cl = Calendar.getIntance();

Calendar class methods:

1) int get(int field):This method returns a value of given Calendar field.


2) void set(int field, int value): This method sets the given field in Calendar object to the
given value.
3) String toString(): This method converts a date into String and returns the String.

Note:The Following are the field names of Calendar class:

 Calendar.DATE - gives the date number from 1 to 31


 Calendar.MONTH - gives the month number from 0 to 11
 Calendar.YEAR - gives the year number.
 Calendar.HOUR - gives the hour number from 0 to 11.
 Calendar.MINUTE - gives the minute number from 0 to 59.
 Calendar.SECOND - gives the minute number from 0 to 59.
 Calendar.AM_PM - gives 0 if it is AM, gives 1 if it is PM.

Program: Write a program that shows the use of Calendar class.


import java.util.*;
public class CalenderDemo
{
public static void main(String args[])
{
234 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Calendar c1=Calendar.getInstance();
System.out.println("Current date:");
int dd=c1.get(Calendar.DATE);
int mm=c1.get(Calendar.MONTH);
++mm;
int yy=c1.get(Calendar.YEAR);
System.out.println(dd+"-"+mm+"-"+yy);
System.out.println("Current time:");
int h=c1.get(Calendar.HOUR);
int m=c1.get(Calendar.MINUTE);
int s=c1.get(Calendar.SECOND);
System.out.println(h+"-"+m+"-"+s);
}
}

Output:
Current date:3-2-2016
Current time:2-24-9

Important Interview Questions:


Q).Does a collection object store copies of other objects or their references?
Answer:A collection object stores references of other objects.

Q).Can you store primitive data type into a collection?


Answer:No, Collections store only objects.

Q).What is the difference between Iterator and ListIterator?


Answer:Both are useful to retrieve elements from a collection. Iterator can retrieve the
elements only in forward direction. But ListIterator can retrieve the elements in forward and
backward direction also. So the ListIterator is preferred to Iterator.

Q).What is the difference between Iterator and Enumeration?


Answer:Both are useful to retrieve elements from a collection. Iterator has methods whose
names are easy to follow and Enumeration methods are difficult to remember. Also Iterator
has an option to remove elements from the collection which is not available in Enumeration.
So Iterator is preferred to Enumeration

Q).What is auto boxing?


Answer:Converting a primitive data type into an object form automatically is called auto
boxing. Auto boxing is done in generic types.

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.

Q).What is the difference between ArrayList and Vector?


Answer:
 ArrayList is not synchronized by default hence it should not be used with multiple
threads. Vector is synchronized by default hence it can be used with single thread (or)
multiple threads.
 ArrayList works fast while working with single thread whereas Vector works slow while
working with single thread.

Q). Can you synchronize the ArrayList object?


Answer:Yes, we can use synchronizedList() method to synchronize the ArrayList as:
Collections.synchronizedList(new ArrayList());

Q).What is the load factor foe a HashMap or Hashtable?


Answer:0.75

Q).What is the difference between HashMap and Hashtable?


Answer:
 HashMap object is not synchronized by default whereas Hashtable object is synchronized
by default.
 In case of single thread, using HashMap is faster than the Hashtable, whereas in the
case of multiple threads, using Hashtable is advisable. With a single thread, Hashtable
becomes slow.
 HashMap allows null keys and null values to be stored Whereas Hashtable does not allow
null keys and null values.

Q). Can you make HashMap synchronized?


Answer: Yes, we can make HashMap object synchronized using synchronizedMap() method
as shown here:
Collections.synchrnizedMap(new HashMap());

236 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Streams and Files:


A file represents organized collection of data. The main advantage of a file is to store
data permanently. Once data is stored on Hard Disk, or CD or any other secondary storage
media, it is stored permanently. Files are useful to store data on secondary storage media.

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.

There are another two types of streams in java.

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.

Note:All streams are represented as classes in “java.io” package.


 Text streams are represented with the classes ending with “Reader or Writer”.
 Byte streams are represented with class names ending with “InputStream or OutputStream”.
Streams

InputStream OutputStream

text byte text byte

-Reader -InputStream -Writer -OutputStream

237 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

FileReader and FileWriter:

FileWriter is used to create a file by directly writing characters.

1. To open the file to write chars.


FileWriter fw=new FileWriter(“myfile.txt”);
To open a file in append mode.
FileWriter fw=new FileWriter(“myfile.txt”, true);
2. To write characters into the file.
fw.write(chars);
FileReader is useful to read text from a file.
3. To open the file for reading characters.
FileReader fr=new FileReader(“myfile.txt”);
4. To read characters and return it as integer.
fr.read(char);
It returns ‘-1’, if this method is failed.
5. To close the files.
fw.close();
fr.close();

Program: write a program to create a text file using FileWriter.


import java.io.*;
class File1
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
FileWriter fw=new FileWriter("Myfile.txt",true);
char ch;
System.out.println("Enter data (@ at end):");
while((ch=(char)dis.read())!='@')
{
fw.write(ch);
}
fw.close();
dis.close();
}
}

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

Improving efficiency using Buffered classes:


Normally, whenever we write data into a file using FileWriter as:

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

For 10 characters: 10*2=20 seconds

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

For 10 characters: 10+1=11 seconds

We can attach a FileWriter to BufferedReader as;

BufferedReader br=new BufferedReader(fr,1204);

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.

Important interview Question:

Q) What is the advantage of Buffered Classes?

Answer: Buffered classes improve the speed of reading or writing operations by using a
buffer.

Program: Write a program to read data from a file using BufferedReader.


import java.io.*;
class Read2
{
public static void main(String[] args) throws IOException
{
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name");
String fname=kb.readLine();
FileReader fr=new FileReader(fname);
BufferedReader br=new BufferedReader(fr);
int ch;
while((ch=br.read())!=-1)
{
System.out.print((char)ch);
}
br.close();
}
}
Output: Enter file name: Read.java
It will display the entire program of Read.java

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

Compress and decompress a file:

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.

1010 1010 Zipping 0


1111 0010 1
0101 1110 10
1111 0010 1
Unzipping
Original file Compressed file

When a file is compressed two things will happen.

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.

In java to compress the contents of a file “DeflaterOutputStream” is used. To uncompress the


file “InflaterInputStream” is used. These streams are available in “java.util.zip” package.

Zipping a file using DeflaterOutputStream:

By using the following steps we can compress afile.

1. Attach the input file ‘file1’ to FileInputStreamfor reading data.


2. Take the output file ‘file2’ and attach it to FileOutputStream. This will help to write
data into ‘file2’.
3. Attach FileOutputStream to DeflaterOutputStream for compressing the data.
4. Now, read data from FileInputStream and write it into DeflaterOutputStream. It will
compress the data and send it to FileOutputStream which stores the compressed data
into the output file. These steps are shown in the following figure.

243 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Program: write a java program to compress the contents of a file.

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

Unzipping a file using InflaterInputStream:

By using the following steps we can decompress a compressed file.


1. Attach the compressed file ‘file2’ to FileInputStream. This helps to read data from ‘file2’.
2. Attach the output file ‘file3’ to FileOutputStream. This will help to write uncompressed
data into ‘file3’.
3. Attach FileInputStream to InflaterInputStream so that the data read from
FileInputStream goes into InflaterInputStream. Now InflaterInputStream uncompresses
that data.
4. Now, read uncompressed data from InflaterInputStream and write it into
FileOutputStream. This will write the uncompressed data to ‘file3’. These steps are shown
in the following figure.
244 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

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

File class methods:


1. To test if f contains a file.
boolean x=f.isFile();
2. To test if f contains a directory.
boolean x=f.isDirectory();
3. To know if the file/directory is readable.
boolean x=f.canRead();
4. To know if the file/directory is writable.
boolean x=f.canWrite();
5. To know if the file is executable.
boolean x=f.canExecute();
6. To know if the file/directory is exists or not.
boolean x=f.exists();
7. To know the name the parent directory of a file/directory.
String name=f.getParent();
8. To know the directory path of a file/directory.
String pathname=f.getPath();
9. To know the absolute path of a file/directory.
String absolutepath=f.getAbsolutePath();
10. To know the size of the file/ directory.
long n=f.length();
11. To delete the file or directory.
f.delete();
12. To create a new empty file whose name is “f”, only if that file does not exist.
boolean x=f.createNewFile();
13. To create a sub directory whose name is given as “f”.
boolean x=f.mkdir();
14. To change the name of the file “f” as new name.
Boolean x=f.renameTo(filenewname);
15. To return the filenames and sub directory names of the directory in “f”.
String x[]=f.list();

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

While displaying object t, it displayed its contents as: Thread[main,5,main]. Where,


 Thread indicates that t is a Thread class object.
 main indicates the name of the thread running the current code.
 5 indicates that number representing the priority of the thread.
Note: Every thread will have a priority number associated with it. These priority numbers
will range from 1 to 10. 1 is the minimum priority, and 10 is the maximum priority of a
thread. If the priority number of a thread is more, it is given more preference while executing
by JVM. The default priority number of a thread is 5.
 Another main indicates the thread group name to which this thread belongs. A thread group
represents a group of threads as a single unit. The ‘main’ thread belongs to ‘main’ thread
group.

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:

o Process based multi tasking


o Thread based multi tasking

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

Life cycle of a Thread:

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

Above-mentioned stages are explained here:


1. New: When we create a new Thread object using new operator, thread state is New
Thread. A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
2. Runnable: When we call start() function on Thread object, it’s state is changed to
Runnable and the control is given to Thread scheduler to finish it’s execution. Whether to
run this thread instantly or keep it in runnable thread pool before running it depends on
the OS implementation of thread scheduler.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Not Runnable: Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state only
when another thread signals the waiting thread to continue executing. This is the state
when the thread is still alive, but is currently not eligible to run.
5. Dead: A thread is in terminated or dead state when its run() method exits.

252 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Creating a thread and running it:


We know that in every Java program, there is a main thread available already. Apart from
this main thread, we can also create our own thread in a program. The following steps should be
used.
Step 1: Create a class that extends ‘Thread’ class (or) implements Runnable interface. These
Thread class and Runnable interface are available in java.lang package.

Syntax: class MyClass extends Thread


(or)
class MyClass implements Runnable

Step 2: In this class we write a run() method as below. By default this run() method is
recognized and executed by a thread.

Syntax: public void run()


{
Statements;
}
Step 3: Create a object to MyClass, so that run() method is available for execution.

Syntax: MyClass obj = new MyClass();

Step 4: Now, create a thread and attach thread to the object (obj) as:

Syntax: Thread t = new Thread(obj);


(or)
Thread t = new Thread(obj, ThreadName);

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

Terminating the thread:

A thread will terminate automatically when it comes out of run() method. To terminate
the thread on our own, then follow the following steps:

Step 1: Create a boolean type variable and initailize it to false.

254 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

Syntax: boolean stop = false;


Step 2: Let us assume that we want to terminate the thread when the user press <Enter> key. So
when the user presses that button make the boolean type variable (stop) as ‘true’.
Syntax: stop = true;
Step 3: check this variable in run() method and when it is true make the thread return from the
run() method.
Syntax: public void run() {
if(stop==true){
return;
}
}

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

class MyThread extends Thread


{
public void run()
{
for(int i=1;i<=100;i++)
{
System.out.println(i);
}
}
}

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

It wakes up the first thread that called wait() on the same


notify( )
object.
notifyAll( Wakes up (Unlock) all the threads that called wait( ) on the
) same object. The highest priority thread will run first.

wait() & notify() methods:


Program 6: Write a program for wait(), notifyAll() methods.
class Demo1 extends Thread
{
DemoWait d;
Demo1(DemoWait d)
{
this.d=d;
start();
}
public void run()
{
try
{
System.out.println("Demo1 value is"+d.val);
d.valchange(40);
}
catch(Exception e)
{
}
}
}
class DemoWait extends Thread
{
int val=20;
public static void main(String args[])
{
DemoWait d=new DemoWait();
d.start();
new Demo1(d);
}
261 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
public void run()
{
try
{
synchronized(this)
{
wait();
System.out.println("value is :"+val);
}
}
catch(Exception e)
{
}
}
public void valchange(int val)
{
this.val=val;
try
{
synchronized(this)
{
notifyAll();
}
}
catch(Exception e)
{
}
}
}
Output
Demo1 value is20
value is :40
sleep method
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

The Thread class provides two methods for sleeping a thread:

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

Program 8: Write a program for sleep() method.


class sclass1 extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
if(i%2==1)
{
try
{
263 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
System.out.println("A : " + i);
Thread.sleep(1000,1);
}
catch(InterruptedException ie)
{
}
}
}
}
class sclass2 extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
if(i%2==0)
{
try
{
System.out.println("B : " + i);
Thread.sleep(1000,1);
}
catch(Exception e)
{
}
}
}
}
class smtest
{
public static void main(String args[])
{
sclass1 s1=new sclass1();
sclass2 s2=new sclass2();
s1.start();
s2.start(); }}
Output :
A:1

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

public void run() {


System.out.println(Thread.currentThread().getName()
+ " is going to call yield() method...");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " is completed.");
}
public static void main(String[] args) {
new ThreadYield("Thread 1");
new ThreadYield("Thread 2");
}
}

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

There are 3 requirements to establish a network.

1. Hardware: represents the physical components or devices. For example, on internet


we need computers, cables, modems, hubs, etc.
2. Software: includes programs to communicate between servers and clients. For
example, the software installed on client machine is called web browser(I.E, Mozilla
Firefox, Google chrome,…. ).
The software installed on internet server machine is called web server(Tomcat
Apache, Web Sphere, Web Dynamics, Jboss,… ).
3. Protocol: represents a way to establish connection and helps in sending and receiving
data in a standard format.

A protocol represents a set of rules to be followed by every computer on a network. Protocol


is useful to physically move data from one place to another place on a network. Ex: TCP/IP,
UDP.
268 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
To send data from one place to another, first of all the computers should be correctly
identified on the network. This is done with the help of IP address. An IP address is a unique
identification number given to every computer on the network. It contains four integer numbers
in the range of 0 to 255 and separated by a dot as: “192.168.1.90”.

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:

It is possible to establish connecting point between a server and a client so that


communication can be done through that point. This point is called socket. Simply, a socket is a
point of connection between the server and a client on a network.

Each socket is given an identification number, which is called ‘port number’. Port
number takes 2 bytes and can be form 0 to 65535.

Establishing communication between a server and a client using sockets is called


‘’socket programming”.

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

o/p value read write


Response

Steps to create a server program:

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.

C:/> java Server 9999

Steps to create a client program:

1. Establish a connection with server by passing ipaddress and portno as arguments to


Socket class as:
Socket s=new Socket(“ipaddress”,”portno”);
2. To send the data, connect the OutputStream to the Socket.
OutputStream os=s.getOutputStream();
3. To receive data from the server, connect InputStream to the Socket.
InputStream is=s.getInputStream();
4. Close or terminate the connections. This can be done by closing all the streams and
sockets at client side.
271 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
Program: write a program to create client side program, to send data to the server and accept
result from the server.

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

To run in different systems:


Run Server.java in a computer and Client.java in another. They should have been
connected in a network.

Two way communication between Server and Client:

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

Graphics Programming Using AWT:


Whenever an application/software is created, the user can work it in two ways. The first
way is where the user can remember some commands on which the application is built and type
those commands to achieve the respective tasks. For example, the user may have to type a
PRINT command to send a file contents to a printer. Here, the user should know the syntax and
correct usage of the PRINT command. Then only he can interact with the application properly.
This is called CUI (Character User Interface) since the user has to use characters or commands to
interact with the application. The main disadvantage in CUI is that the user has to remember
several commands and their use with correct syntax. Hence, CUI is not user-friendly. A person
who does not know anything about computers will find this CUI very difficult.
The second way is where the user need not remember any commands but interacts with
any application by clicking on some images or graphics. For example, if the user wants to print a
file, he can click on a printer image and the rest of the things will be taken care of by the
application. The user has to tell how many copies he wants and printing continues. This is very
easy for the user since the user remembers only some symbols or images, like a magnifying glass
symbol for searching, a briefcase symbol for a directory, etc. this environment where the user
can interact with an application through graphics or images is called GUI (Graphics User
Interface). GUI has the following advantages.
 It is user-friendly. The user needs not any worry about any commands. Even a layman
will be able to work with the application developed using GUI.
 It adds attraction and beauty to any application by adding pictures, colors, menus,
animation, etc.
 It is possible to simulate the real life objects using GUI. For example, a calculator
program may actually display a real calculator on the screen.
 GUI helps to create graphical components like push buttons, radio buttons, check boxes,
etc.

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:

A component represents an object which is displayed pictorially on the screen. For


example, we create an object of Button class as:

Button b=new Button();

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.

 Create a Frame class object.


Frame f=new Frame();
 Create a Frame class object and pass its title also.
Frame f=new Frame(“My Frame”);
 The third way is to create a sub class MyFrame to the Frame class and create an object to
the subclass as:
Class MyFrame extends Frame
MyFrame f=new MyFrame();

Since,MyFrame is a subclass of Frame class, is object f contains a copy of Frame class


and hence f represents the frame.

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

Prog: write a program to create a frame by creating an object to Frame class.

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

The same program can be rewritten in a different way, as:

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.

Closing the Frame:

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.

public void windowActivated(WindowEvent e)


public void windowClosed(WindowEvent e)
public void windowClosing(WindowEvent e)
public void windowDeactivated(WindowEvent e)
public void windowDeiconified(WindowEvent e)
public void windowClosing(WindowEvent e)
public void windowIconified(WindowEvent e)
public void windowOpened(WindowEvent e)
280 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java
In all the preceding methods, WindowListener interface calls the public void
windowClosing() method when the frame is being closed. So, implementing this method alone is
enough, as:
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
For the remaining methods, we can provide empty body.

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

Output: C:\> javac MyFrame.java


C:\> java MyFrame
CLICK ON CLOSE BUTTON, THE FRAME CLOSES

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.

Prog: Write a program to close the frame using WindowAdapter 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());
}
}
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.

Drawing in the frame:

Graphics class of java.awt package has the following methods which help to draw various
shapes.

 drawLine(int x1, int y1, int x2, int y2)


This method is useful to draw a line connecting (x1, y1) and (x2, y2).
 drawRect(int x, int y, int w, int h)
This method draws outline of a rectangle. The left top corner of the rectangle
starts at(x,y), the width is w, and the height is h.
 drawRoundRect(int x, int y, int w, int h, int arcw, int arch)
This method draws the outline of a rectangle with rounded corners, the rectangles
top left corner starts at (x, y), the width is w, and height is h. the rectangle will
have rounded corners. The rounding is specified by arcw and arch. arcw
represents horizontal diameter of the arc at the corner and arch represents vertical
diameter of the arc at the corner.
 drawOval(int x, int y, int w, int h)
This method draws a circle or ellipse bounded in the region of a rectangle starting
at (x,y), with width w and height h.
 drawArc(int x, int y, int w, int h, int sangle, int aangle)
Draws an arc bounded by a rectangle region of (x, y), with width w and height h.
Here, sangle represents the beginning angle measured from 3 O’clock position in
the clock. aangle represents the arc angle relative to start angle.
sangle+aangle=end angle. if the sangle is positive, the arc is drawn counter clock
wise and if it is negative, then it is drawn clockwise.

284 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD
Core java

 drawPolygon(int x[], int y[], int n)


This method draws a polygon that connects pairs of coordinates mentioned by the
arrays x[] and y[]. Here, x[] is an array which holds x coordinates of points and
y[] is an array which holds y coordinates. n represents the number of pairs of
coordinates.

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

Filling with colors:

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.

 fillRect(int x, int y, int w, int h)


This method draws a rectangle and fills it with the specified color.
 fillRoundRect(int x, int y, int w, int h, int arcw, int arch)
This method draws filled rectangle with rounded corners.
 fillOval(int x, int y, int w, int h)
This method is useful to create an oval which is filled with a specified color.
 fillArc(int x, int y, int w, int h, int sangle, int aangle)
This method draws an arc and fills it with a specified color.
 fillPolygon(int x[], int y[], int n)
This method draws and fills a polygon with a specified 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

Displaying text in the Frame:

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.

Color.black Color.blue Color.cyan


Color.pink Color.red Color.orange
Color.magenta Color.darkGray Color.gray
Color.lightGray Color. green Color.yellow
Color.white

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:

Color c=new Color(r, g, b);

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,

Color c=new Color(255,0,0); // red color


Color c=new Color(255,255,255); // white color
Color c=new Color(0,0,0); // black color

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:

Font f=new Font(“SanSerif”, Font.BOLD, 30);

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

Displaying Images in the Frame:

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

Component Class Methods:


A component is a graphical representation of an object on the screen. For example, push
buttons, radio buttons, menus, etc,. are components. Even frame is also a component. There is
Component class available in java.awt package which contains the following methods which are
applicable to any component.
 Font getFont(): This method returns the font of the component.
 void setFont(Font f): This method sets a particular font f for the text of the component.
 Color getForeground(): This method gives the foreground color of the component.
 void setForeground(Color c): This method sets a foreground color c to the component.
 Color getBackground(): Gets the background color of the component.
 void setBackground(Color c): sets the background color c of the component.
 String getName(): Returns the name of the component.
 void setName(string name): sets a new name for the component.
 int getHeight(): Returns the height of the component in pixels as an integer.
 int getWidth(): Returns the width of the component in pixels as an integer.
 Dimension getSize(): Returns the size of the component as an object of Dimension class.
Dimesion.width and Dimension.height will provide the width and height of the
component.
 int getx(): Returns the current x coordinate of the component’s origin.
 int gety(): Returns the current y coordinate of the component’s origin.
 Point getLocation(): Gets the location of the component in the form of a point specifying
the component’s top-left corner.
 void setLocation(int x, int y): Moves the component to a new location specified by (x, y).
 void setSize(int width, int height): Resizes the component so that it has new width and
height as passed to setSize() method.
 void setVisible(boolean b): Shows or hides the component depending on the value of
parameter b. setVisible(true) will display the component and setVisible(false) hides the
component.
 void setEnabled(boolean b): Enables or disables the component, depending on the value
of the parameter b. setEnabled(true) will enable the component to function and
setEnabled(false) will disable it.
294 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();

Here, the “label” is set to the button b.

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

In the two methods, addActionListener() and removeActionListener(), we are passing


ActionListener object. Since ActionListener is an interface, we cannot directly create an object to
it, we should pass object of implementation class of the interface in this case.
Let us write a program to create push buttons and also add some actions to the buttons.
The following steps can be followed.

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

 Then create the push buttons by creating objects to Button class.


 Since, we are not using any layout manager, we should specify where to attach the
buttons in the frame using setBounds() method.
 Then add the buttons to the frame using add() method.
 Add ActionListener to the button so that when we click on any button, the listener will
handle the event by calling actionPerformed() method.

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

Listeners and Listener Methods:

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.

Component Listener Listener methods


Button ActionListener public void actionPerformed(ActionEvent e)
CheckBox ItemListener public void itemStateChanged(ItemEvent e)
CheckBoxGroup ItemListener public void itemStateChanged(ItemEvent e)
TextField ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
TextArea ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
Choice ActionListener public void actionPerformed(ActionEvent e)
ItemListener public void itemStateChanged(ItemEvent e)
List ActionListener public void actionPerformed(ActionEvent e)
ItemListener public void itemStateChanged(ItemEvent e)
Scrollbar AdjustmentListener public void adjustmentValueChanged(AdjustmentEvent e)
MouseMotionListener public void MouseDragged(MouseEvent e)
public void mouseMoved(MouseEvent e)
Frame WindowListener public void windowActivated(WindowEvent e)
public void windowClosed(WindowEvent e)
public void windowClosing(WindowEvent e)
public void windowDeactivated(WindowEvent e)
public void windowDeiconified(WindowEvent e)
public void windowClosing(WindowEvent e)
public void windowIconified(WindowEvent e)
public void windowOpened(WindowEvent e)
Key board KeyListener public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
public void keyTyped(KeyEvent e)
Label No listener is needed

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.

 To create a check box, we can create an object to Checkbox class, as:


Checkbox cb=new Checkbox();
Checkbox cb=new Checkbox(“label”);
Checkbox cb=new Checkbox(“label”, state);
 To get the state of a check box:
Boolean b=cb.getState();
If the check box is selected, this method returns true, else false.
 To set the state of a checkbox:
cb.setState(true);
The check box cb will now appear as if it is selected.
 To get the label of a check box:
String s=cb.getLabel();
If cb is the check box object, then getLabel() will give its label.
 To set the label to a check box:
void setLabel(String label)
 To get the selected checkbox label into an array we can use getSelectedObject() method.
This method returns an array of size 1 only.
Object x[]=cb.getSelectedObjects();
Here, x[0] stores the label of the check box selected by the user, if selected.
Otherwise, it stores null.
For example, there are 2 check boxes as:
Checkbox c1=new Checkbox(“One”);
Checkbox c2=new Checkbox(“Two”);
x=c1.getSelectedObjects();
if(x[0]==null) System.out.println(“The check box is not selected”);
else System.out.println(“Selected check box label is: ”+x[0]);

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.

 To create a list box, we can create an object to List class:

List lst=new List();

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.

List lst=new List(3);

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.

List lst=new List(3, true);

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

 To remove an item whose name is given:


lst.remove(String item);
 To remove all items from the list:
lst.removeAll();

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 class Student extends Frame implements ActionListener


{
String msg;
Button b1=new Button("save");
Label l11=new Label("Student details",Label.CENTER);
Label l1=new Label("Name:",Label.LEFT);
Label l2=new Label("age:",Label.LEFT);
Label l3=new Label("Sex(M/F):",Label.LEFT);
Label l4=new Label("Address:",Label.LEFT);
Label l5=new Label("Course:",Label.LEFT);
Label l6=new Label("Semester:",Label.LEFT);
Label l7=new Label("",Label.RIGHT);
TextField t1=new TextField();
Choice c1=new Choice();
CheckboxGroup cbg=new CheckboxGroup();
Checkbox ck1=new Checkbox("Male",false,cbg);
Checkbox ck2=new Checkbox("Female",false,cbg);
TextArea t2=new TextArea("",180,90,TextArea.SCROLLBARS_VERTICAL_ONLY);
Choice course=new Choice();
Choice sem=new Choice();
Choice age=new Choice();

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

Important Interview Questions:


Q). what is java AWT?
Answer:AWT stands for Abstract Window Toolkit. AWT enables programmers to develop
Java applications with GUI components, such as windows, and buttons. The Java Virtual
Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the
host operating system.

Q). what is the difference between a window and a frame?


Answer:A window is a frame without any borders and title,where as a frame contains
borders and title.

Q). what is event delegation model?


Answer:Event delegation model represents that when an event is generated by the user on
a component,it is delegated to a listener interface and the listener calls a method in
response to the event.Finally,the event is handled by the method.

Q). which model is used to provide actions to AWT components?


Answer:Event delegation model.

Q). what is an adapter class?


Answer:An Adapter class in an implementation class of a listener interface which contains all
methods implemented with empty body. WindowAdapter is an adapter class of
WindowListener interface. Adapter classes reduce overhead on programming while working
with listener interfaces.

Q). what is anonymous inner class?


Answer:Anonymous inner class is an inner class whose name is not mentioned, and for
which only one object is created.

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). what is the difference between a Choice and a List?


Answer:
Choice: A Choice is displayed in a compact form that requires you to pull it down to see the
list of available choices. Only one item may be selected from a Choice.
List: A List may be displayed in such a way that several List items are visible. A List
supports the selection of one or more List items.

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

Q). what is the default layout in a frame?


Answer:Border Layout.

Q) What is the difference between a MenuItem and a CheckboxMenuItem?


Answer:The CheckboxMenuItem class extends the MenuItem class to support a menu item
that may be checked or unchecked.

Q). How to change a button from enable to disable after click?


Answer:When button is clicked an action event is fired which can be captured by
implementing ActionListener interface and actionPerformed(ActionEvent ae) method. You
can then call button.setEnable(false) to disable this button.

Q). what are the subclasses of the Container class? –


Answer:The Container class has three major subclasses. They are:
 Window
 Panel
 ScrollPane

Q). what is the difference between a Scollbar and a Scrollpane?


Answer:A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and
handles its own events and performs its own scrolling.

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:

Applet=Java byte code+ HTML page.

Creating an applet:

There are two ways to create an applet in java:

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:

1. Applets are used on Internet for creating dynamic web pages.


2. Applets are used for creating animation and games where the images can be displayed or
moved giving a visual impression that they are alive.

<Applet> tag:

<Applet> tag is useful to embed an applet into an HTML page. It has the following form:

<APPLET CODE=”name of the applet class file”

CODEBASE=”path of the applet class file”

HEIGHT= maximum height of applet in pixels

WIDTH= maximum width of applet in pixels

ALIGN= alignment (LEFT, RIGHT, TOP, BOTTOM, MIDDLE)

ALT= alternate text to be displayed >

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

C:\> appletviewer MyApp.html

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

C:\> javac App1.java


Now create a HTML page to embed the App1 applet into it, as shown below:

<HTML>
<applet code="App1.class" height=200 width=300>
</applet>
</HTML>

Open the above App1.html file in the appletviewer, as:


C:\> appletviewer App1.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.

Important Interview Questions:


Q). what is an Applet?
Answer:An applet represents java byte code embedded in a web page.

Q). where are applets executed?


Answer:Applets are executed by a program called applet engine which is similar to virtual
machine that exists inside the web browser at client side.

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 HotJava?


Answer:HotJava is the first applet-enabled browser developed in java to support running of
applets.

Q). which tag is used to embed an applet into a HTML page?


Answer:<Applet> tag is used to insert an applet into HTML page.

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). What is an Applet? Should applets have constructors?


Answer:Applets are small programs transferred through Internet, automatically installed
and run as part of web-browser. Applet implements functionality of a client. Applet is a
dynamic and interactive program that runs inside a Web page displayed by a Java-capable
browser. We don’t have the concept of Constructors in Applets. Applets can be invoked
either through browser or through Appletviewer utility provided by JDK.

Q). ShowStatus() ?

Answer:To display the message at the bottom of the browser when applet is started.

315 YOUNGMINDS
TECHNOLOGY SOLUTIONS PVT LTD

You might also like