CMP 512-Java-R
CMP 512-Java-R
Chavan
Maharashtra JAVA
Open University
JAVA
Prof. Mr. Vipin Wani Prof. Milind Bhandare Ms. Monali R. Borade Dr. Pramod Khandare
Assistant Professor, Assistant Professor, Academic Co-ordinator Director
Department of Computer Department of Computer School of Computer School of Computer
Science & Engineering, Science, Science, Y.C.M. Open Science, Y.C.M. Open
Sandip University, L.G.N. Sapkal COE University, Nashik University, Nashik
Nashik Nashik
Production
Course Objectives
The fundamental point in learning programming is to develop the critical skills of
formulating programmatic solutions for real problems.
To learn the syntax and semantics to write Java programs.
To understand the fundamentals of object-oriented programming in Java.
Learn to develop object oriented software using class encapsulation and inheritance,
packages and interfaces
To impart the basic concepts of Java Programming and to develop understanding about
Basic Object oriented Design using UML and Applet.
Design and implement Applet and event handling mechanisms in programs
Learning Outcome:
Understand the concept of OOP as well as the purpose and usage principles of
inheritance, polymorphism, encapsulation and method overloading.
Identify classes, objects, members of a class and the relationships among them needed
for a specific problem.
Create Java application programs using sound OOP practices (e.g., interfaces and APIs)
and proper program structuring (e.g., by using access control identifies, automatic
documentation through comments, error exception handling).
Use testing and debugging tools to automatically discover errors of Java programs as
well as use versioning tools for collaborative programming/editing.
Develop programs using the Java Collection API as well as the Java standard class
library.
Apply object oriented programming concepts in problem solving through JAVA.
Reference:
1. OCA/OCP Java SE 7 Programmer I and II Study Guide: Kathy Sierra and Bert Bates
2. Programming with Java, A Primer: E Balagurusamy
3. Head First Java, Second Edition: Kathy Sierra and Bert Bates
Note: This Study material is still under development and editing process. This
draft is being made available for the sole purpose of reference. Final edited
copies will be made available once ready.
CHAPTER 1
EVOLUTION OF JAVA, VARIABLES AND NAMING
RULES
1.1 BASIC INTRODUCTION
Java is a High level object oriented programming language which is designed at Sun
Microsystems (Sun) in 1991 by James Gosling. The intention behind java language was to
develop a language which allows writing a program once and executing multiple times. Java
allows to write a program once and then run this program on multiple operating systems.
1.3.1. Object oriented: Java is an OOPL that supports the construction of programs that consist
of collections of collaborating objects. These objects have a unique identity and have OOP
features such as encapsulation, abstraction, Class, inheritance and polymorphism.
1.3.2. Simple: Java was designed with a small number of language constructs so that
programmers could learn it quickly which make it simple. It eliminates several language features
that were in C/C++ that was associated with poor programming practices or rarely used such as
multiple inheritance, goto statements, header files, structures, operator overloading, and pointers,
security reason was also there for removing or not adding pointer in java.
8. Features
Architectu- 2. Simple
re Neutral
of Java
7. Dynamic 3. Secured
4. Platform
6. Portable Independe
5. Robust -nt
1.3.3. Secure: Java is designed to be secure in a networked environment. The Java run-time
environment uses a byte code verification process to ensure that code loaded over the network
does not violate Java security constraints. Absence of pointer also adds on values for java
security features.
1.3.4. Platform Independent: As we have seen on Introduction page Byte code and JVM
which plays the major role for making the java platform independent and which make it a
distinct.
1.3.5. Robust: Java is designed to eliminate certain types of programming errors. Java is
strongly typed, which allows extensive compile-time error checking. Its automatic memory
management (garbage collection) eliminates memory leaks and other problems associated with
dynamic memory allocation and deallocation. It does not support memory pointers, which
eliminates the possibility of overwriting memory and corrupting data.
1.3.6. Portable: has usually meant some work when moving an application program to another
machine. Recently, the Java programming language and runtime environment has made it
possible to have programs that run on any operating system and machine that supports
the Java standard (from Sun Microsystems) without any porting work.
1.3.7. Architecture Neutral: Java applications that are compiled to byte codes can be
interpreted by any system that implements the Java Virtual Machine. Since the Java Virtual
Machine is supported across most operating systems, this means that Java applications are able
to run on most platforms.
1.3.8. Dynamic: Java supports dynamic loading of classes class loader is responsible for
loading the class dynamically in to JVM.
1.3.9. Interpreted: Java is compiled to bytecodes, which are interpreted by a Java run-time
environment.
1.3.10. High Performance: Although Java is an interpreted language, it was designed to support
“just-in-time” compilers, which dynamically compile bytecodes to machine code.
1.3.12. Distributed: Java is designed to support various levels of network connectivity. Java
applications are network aware: TCP/IP support is built into Java class libraries. They can open
and access remote objects on the Internet.
Operating
System
Byte code: As discussed above, javac compiler of JDK compiles the java source code into byte
code so that it can be executed by JVM. The byte code is saved in a .class file by compiler.
Class Loader: The Java Class loader is a part of the Java Run-time Environment that is
responsible for dynamically loading of Java classes into the Java Virtual Machine. The Java run
time system does not need to know about files and file systems because of class loaders.
Byte Code Verifier: Is again a part of Java Run-time Environment, after loading the byte code
in JVM byte code are first inspected by a verifier. The verifier checks that the instructions
cannot perform actions that are obviously damaging.
Java Virtual Machine (JVM): This is generally referred as JVM. Before, we discuss about
JVM lets see the phases of program execution. Phases are as follows: we write the program, then
we compile the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates java byte
code as output.
3) In third phase, JVM executes the byte code generated by compiler. This is called program run
phase.
The Just-In-Time (JIT) compiler: is a component of the java runtime environment that
improves the performance of Java applications by compiling byte codes at run time to native
machine code. Java programs consists of classes, which contain platform independentbytecodes
that can be interpreted by a JVM. At run time, the JVM loads the class files, determines the
semantics of each individual byte code, and performs the appropriate computation. The
additional processor and memory usage during interpretation means that a Java application
performs more slowly than a native application. The JIT compiler helps improve the
performance of Java programs by compiling byte codes into native machine code at run time.
1.5.3Java Virtual Machine (JVM): The Java Virtual Machine (JVM) is the virtual machine
that runs the Java bytecodes. The JVM doesn't understand Java source code; that's why you need
compile your *.java files to obtain *.class files that contain the byte codes understood by the
JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere).
Indeed, there are specific implementations of the JVM for different systems. The aim is that with
the same byte codes they all give the same results.is a very important part of both JDK and JRE
because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK
goes into JVM and JVM is responsible for executing the java program line by line hence it is
also known as interpreter.
Programming languages such as Cobol, FORTRAN do not have structural principles. They use
the Goto statement to control the flow of the program. Therefore, programs using this type of
code are made up of many jumps and conditional statements that make it difficult to understand.
Therefore, “C” was invented in 1970, to replace the assembly language and to create a
structured, effective and high-level language. The development of C was the result of the
development process started with BCPL by Dennis Ritchie. BCPL is an old language developed
by Martin Richard. Ken Thompson developed a language called B, which was influenced by
BCPL.
Though C was a quite efficient and successful programming language, the complexity of the
program was seeking more efficient language to solve problems. When we write a program in C,
it has a limit, such as a maximum of 25000 lines of code, beyond which it cannot handle the
complexity. But writing and managing large programs was a demand at that time. So a new
concept came.
C ++ with OOP became quite famous but then a new problem arose, to control the software on
different machines, a separate compiler is required for that CPU. But building a C++ compiler
was quite expensive. Therefore, an efficient and easy solution was needed, and this requirement
became the reason for the creation of Java, which is a portable and platform-independent
language.
RELEASE
VERSION MAJOR CHANGES
DATE
JDK Beta 1995
JDK 1.0 January 1996 The Very first version was released on January 23, 1996. The
principal stable variant, JDK 1.0.2, is called Java 1.
JDK 1.1 February Was released on February 19, 1997. There were many additions in
1997 JDK 1.1 as compared to version 1.0 such as
A broad retooling of the AWT occasion show
Inner classes added to the language
JavaBeans
JDBC
RMI
J2SE 1.2 December “Play area” was the codename which was given to this form and
1998 was released on 8th December 1998. Its real expansion included:
strictfp keyword
the Swing graphical API was coordinated into the centre
classes
Sun‟s JVM was outfitted with a JIT compiler out of the blue
Java module
Java IDL, an IDL usage for CORBA interoperability
Collections system
J2SE 1.3 May 2000 Codename- “KESTREL”
Release Date- 8th May 2000
Additions:
Hotspot JVM included
Java Naming and Directory Interface
JPDA
JavaSound
Synthetic proxy classes
J2SE 1.4 February Codename- “Merlin”
2002 Release Date- 6th February 2002
Additions: Library improvements
Regular expressions modelled after Perl regular expressions
The image I/O API for reading and writing images in formats
like JPEG and PNG
Integrated XML parser and XSLT processor (JAXP)
(specified in JSR 5 and JSR 63)
Preferences API (java.util.prefs)
Public Support and security updates for this version ended in
October 2008.
J2SE 5.0 September Codename- “Tiger”
2004 Release Date- “30th September 2004”
Originally numbered as 1.5 which is still used as its internal
version. Added several new language features such as:
for-each loop
Generics
Autoboxing
Var-args
JAVA SE 6 December Codename- “Mustang”
2006 Released Date- 11th December 2006
Packaged with a database supervisor and encourages the utilization
of scripting languages with the JVM. Replaced the name J2SE
with ava SE and dropped the .0 from the version number.
Additions:
Upgrade of JAXB to version 2.0: Including integration of a
StAX parser.
Support for pluggable annotations (JSR 269).
JDBC 4.0 support (JSR 221)
JAVA SE 7 July 2011 Codename- “Dolphin”
Release Date- 7th July 2011
Added small language changes including strings in the switch. The
JVM was extended with support for dynamic languages.
Additions:
Compressed 64-bit pointers.
Binary Integer Literals.
Upstream updates to XML and Unicode.
JAVA SE 8 March 2014 Released Date- 18th March 2014
Language level support for lambda expressions and default
methods and a new date and time API inspired by Joda Time.
JAVA SE 9 September Release Date: 21st September 2017
2017 Project Jigsaw: designing and implementing a standard, a module
system for the Java SE platform, and to apply that system to the
platform itself and the JDK.
JAVA SE March 2018 Released Date- 20th March
10 Addition:
Additional Unicode language-tag extensions
Root certificates
Thread-local handshakes
Heap allocation on alternative memory devices
Remove the native-header generation tool – javah.
Consolidate the JDK forest into a single repository.
JAVA SE September Released Date- 25th September, 2018
11 2018 Additions-
Dynamic class-file constants
Epsilon: a no-op garbage collector
The local-variable syntax for lambda parameters
Low-overhead heap profiling
HTTP client (standard)
Transport Layer Security (TLS) 1.3
Flight recorder
JAVA SE March 2019 Released Date- 19th March 2019
12 Additions-
Shenandoah: A Low-Pause-Time Garbage Collector
(Experimental)
Microbenchmark Suite
Switch Expressions (Preview)
JVM Constants API
One AArch64 Port, Not Two
Default CDS Archives
classHelloWorld
{
int i; // Variable Declaration
public static void main(String [] args) //Main Function Declaration
{
int j;
System.out.println(” Hello World Welcome to Java”);
}
}
Output: Hello World Welcome to Java
Example 2:
class Demo
{
public static void main(String [] args) //Main Function Declaration
{
int j=10;
System.out.println(” J==>”+j);
}
}
Output: J==>10
1.7.2 Java Object − It is a basic unit of Object Oriented Programming and Object represent any real life
entity that can be considered for implementation. Objects have states and behaviours. Example: A dog has
states - colour, name, breed as well as behaviours – wagging the tail, barking, eating. An object is an
instance of a class. Class − A class can be defined as a template/blueprint that describes the
behaviour/state that the object of its type support.
State: Behaviour :
Identity:
Reading, Witting Learn, Listen
Name of Student
Studding Talk
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behaviour of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Identity: S3
Name of
Student
S1
State:Reading,
Witting ,Studding
S4
S2 Behaviour :
Learn, Listen, Talk
1.8 Instantiation in Java
1.9 Variables in Java
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory. Variables are
containers for storing data values.
Syntax:
type variable = value;
Where type is one of Java's types (such as int or String), and variable is the name of the variable
(such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
1.10.1 Class Scope:Each variable declared inside of a class's brackets ( {} ) with private access
modifier but outside of any method, has class scope. As a result, these variables can be used
everywhere in the class, but not outside of it:
publicclassClassScopeExample {
privateInteger amount = 0;
publicvoidexampleMethod() {
amount++;
}
publicvoidanotherExampleMethod() {
Integer anotherAmount = amount + 4;
}
}
We can see that ClassScopeExample has a class variable amount that can be accessed within the class's
methods.
1.10.2 Method Scope: When a variable is declared inside a method, it has method scope and it
will only be valid inside the same method:
publicclassMethodScopeExample {
publicvoidmethodA() {
Integer area = 2;
}
publicvoidmethodB() {
// compiler error, area cannot be resolved to a variable
area = area + 2;
}
}
In methodA, we created a method variable called area. For that reason, we can use area inside methodA,
but we can't use it anywhere else.
1.10.3 Loop Scope:If we declare a variable inside a loop, it will have a loop scope and will only
be available inside the loop:
publicclassLoopScopeExample {
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
publicvoiditerationOfNames() {
String allNames = "";
for(String name : listOfNames) {
allNames = allNames + " "+ name;
}
// compiler error, name cannot be resolved to a variable
String lastNameUsed = name;
}
}
We can see that method iterationOfNames has a method variable called name. This variable can be used
only inside the loop and is not valid outside of it.
publicclassBracketScopeExample {
publicvoidmathOperationExample() {
Integer sum = 0;
{
Integer number = 2;
sum = sum + number;
}
// compiler error, number cannot be solved as a variable
number++;
}
}
The main difference between primitive and non-primitive data types is Primitive types are
predefined (already defined) in Java. Non-primitive types are created by the programmer and is
not defined by Java (except for String).
In the example below, we use the +operator to add together two values:
Example
int a =10+ 20;
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
1.13.1 Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x =10;
It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
There can be only one public class per source code file.
Comments can appear at the beginning or end of any line in the source code file; they are
independent of any of the positioning rules discussed here. Java comment can be inserted
anywhere in a program code where a white space can be
If there is a public class in a file, the name of the file must match the name of the public class.
For example, a class declared as public class Dog { } must be in a source code file named
Dog.java.
If the class is part of a package, the package statement must be the first line in the source code
file, before any import statements that may be present.
If there are import statements, they must go between the package statement (if there is one) and
the class declaration. If there isn't a package statement, then the import statement(s) must be the
first line(s) in the source code file. If there are no package or import statements , the class
declaration must be the first line in the source code file.
import and package statements apply to all classes within a source code file. In other words,
there's no way to declare multiple classes in a file and have them in different packages, or use
different imports.
A file can have more than one non~public class.
Files with non~public classes can have a name that does not match any of the classes in the file
Java heavily uses Camel Case notations for naming the methods, variables etc. and TitleCase
notations for classes and interfaces.
packagecom.howtodoinjava.webapp.controller;
packagecom.company.myapplication.web.controller;
packagecom.google.search.common;
publicclassArrayList {}
publicclassEmployee {}
publicclassRecord {}
publicclassIdentity {}
publicinterfaceSerializable {}
publicinterfaceClonable {}
publicinterfaceIterable {}
publicinterfaceList {}
publicLong getId() {}
publicvoidremove(Object o) {}
publicObject update(Object o) {}
publicReport getReportById(Long id) {}
publicLong id;
publicEmployeeDao employeeDao;
privateProperties properties;
publicfinalintINITIAL_SIZE = 16;
if statement
if-else statement
if-else-if ladder
nested if statement
Syntax:
if(condition){
//code to be executed
}
Example:
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
//defining a variable
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
for loop
while loop
do-while loop
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return Boolean value either true
or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Flowchart:
Example:
Example:
Syntax:
while(condition){
//code to be executed
}
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Example:
2.10 Java for Loop vs. While Loop vs. Do While Loop
Compariso
for loop while loop do while loop
n
When to If the number of iteration is fixed, it If the number of iteration If the number of iteration
use is recommended to use for loop. is not fixed, it is is not fixed and you must
recommended to use have to execute the loop
while loop. at least once, it is
recommended to use the
do-while loop.
Points to Remember
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}
Example:
int number=20;
//Switch expression
switch(number){
//Case statements
break;
break;
break;
The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.
Syntax:
jump-statement;
break;
Example:
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.
Syntax:
1. jump-statement;
2. continue;
Example:
//for loop
for(int i=1;i<=10;i++){
if(i==5){
System.out.println(i);
Syntax:
Example:
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */
Example:
Syntax:
1. /**
2. This
3. is
4. documentation
5. comment
6. */
Example:
1. /** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*
/
2. public class Calculator {
3. /** The add() method returns addition of given numbers.*/
4. public static int add(int a, int b){return a+b;}
5. /** The sub() method returns subtraction of given numbers.*/
6. public static int sub(int a, int b){return a-b;}
7. }
CHAPTER 3
IMPLEMENTATION OF METHODS
3.1 Introduction:
3.1.1 Java Class: Class is the Entity which binds the All data members and data functions
together.
It can also be defined as class is the basic building block of an object-oriented language which is
a template that describes the data and behaviour associated with instances of that class. When
you instantiate a class you create an object that looks and feels like other instances of the
same class.
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
Example:
class HelloWorld
{
int i; // Variable Declaration
public static void main(String [] args) //Main Function Declaration
{
int j;
System.out.println(” Hello World Welcome to Java”);
}
}
Output: Hello World Welcome to Java
A method is a collection of statements that perform some specific task and return the result to
the caller. A method can perform some specific task without returning anything. Methods allow
us to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
o public: accessible in all class in your application.
o protected: accessible within the class in which it is defined and in its subclass(es)
o private: accessible only within the class in which it is defined.
o default (declared/defined without using any modifier) : accessible within same
class and package within which its class is defined.
The return type: The data type of the value returned by the method or void if does not
return a value.
Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
Parameter list: Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.
Method signature: It consists of the method name and a parameter list (number of
parameters, type of the parameters and order of the parameters). The return type and exceptions
are not considered as part of it.
Method Signature of above function:
max(int x, int y)
Calling a method
The method needs to be called for using its functionality. There can be three situations when a
method is called:
Example:
classMain{
// method call
myMethod();
System.out.println("Method was executed successfully!");
}
// method definition
privatestaticvoid myMethod(){
System.out.println("Printing from inside myMethod()!");
}
}
Output:
classSquareMain{
publicstaticvoid main(String[] args){
int result;
result = square();
System.out.println("Squared value of 10 is: "+ result);
}
publicstaticint square(){
// return statement
return10*10;
}
output :
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the object is created, and memory is allocated for the object. It is named as constructor because
it constructs the values at the time of object creation. It is not necessary to write a constructor for
a class. If your class doesn‟t have any constructor java compiler creates a default constructor for
your class. you can say It is a special type of method which is used to initialize the object.
Every time an object is created using new() keyword, at least one constructor is called. It calls a
default constructor.
3.2.2.1 Rules for Writing Java constructor
class Employee{
}
public static void main(String args[]) //main method
{
Employee b=new Employee (); //calling a default constructor
}
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
b. Java Parameterized Constructor
The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.
In this example, we have created the constructor of ConstructorDemo class that have two
parameters. We can have any number of parameters in the constructor.
class ConstrucrorDemo
{
int a;
String s;
ConstrucrorDemo()
{
System.out.println("U r in Default Constructor");
a=10;
s="Te comp";
}
ConstrucrorDemo(int a,String s)
{
System.out.println("U r in Parametric Constructor");
this.a=a;
this.s=s;
}
void display()
{
System.out.println("U r in function now");
System.out.println("The value of A is==>"+a);
System.out.println("The value of S is==>"+s);
}
public static void main(String[] args)
{
System.out.println("Hello World!");
ConstrucrorDemo c=new ConstrucrorDemo();
System.out.println("Using the ref of Default Constructor Values are==>");
c.display();
ConstrucrorDemo c1=new ConstrucrorDemo(20,"T3 Batch");
System.out.println("Using the ref of Parametric Constructor Values are==>");
c1.display();
}
}
Output:
Hello World!
U r in Default Constructor
U r in function now
U r in Parametric Constructor
U r in function now
c.Ccopy constructor:
A copy constructor is a member function which initializes an object using another object of the same
class. A copy constructor has the following general function prototype:
classComplex {
privatedoublere, im;
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class
@Override
publicString toString() {
return"("+ re + " + "+ im + "i)";
}
publicstaticvoidmain(String[] args) {
}
}
In this example, we are creating static methods so that we don't need to create instance for calling methods.
class AddOperation{
public int add(int a,int b)
{return a+b;}
public int add (int a,int b,int c
{return a+b+c;}
}
public static void main(String[] args){
System.out.println(AddOperation.add(14,10));
System.out.println(AddOperation.add(21,11,31));
}
class AddOperation {
int add(int a, int b)
{return a+b;}
double add(float a, float b)
{return a+b;}
}
public static void main(String[] args){
System.out.println(AddOperation.add(21,11));
System.out.println(AddOperation.add(12.3,12.1));
}
Like methods, constructors can also be overloaded. It allows having more than one constructor
inside one Class but with different signature.Constructor overloading is a concept of having
more than one constructor with different parameters list, in such a way so that each constructor
performs a different task. The difference in constructors parameters can be number of
parameters, data types of parameters, order of parameters
4. make sure you add no argument default constructor because once compiler will not add if you
have added any constructor in Java.
6. Its best practice to have one primary constructor and let overloaded constructor calls that. this
way your initialization code will be centralized and easier to test and maintain.
Method overriding is one of the way by which java achieve Run Time Polymorphism. The
version of a method that is executed will be determined by the object that is used to invoke it. If
an object of a parent class is used to invoke the method, then the version in the parent class will
be executed, but if an object of the subclass is used to invoke the method, then the version in the
child class will be executed. In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an overridden method will be
executed.
Example:
class OverridingDemo
5. The overriding method must have same return type (or subtype): From Java 5.0 onwards it is
possible to have different return type for an overriding method in child class, but child‟s return
type should be sub-type of parent‟s return type. This phenomenon is known as covariant return
type.
6. Invoking overridden method from sub-class: We can call parent class method in overriding
method using super keyword.
7. Overriding and constructor: We cannot override constructor as parent and child class can never
have constructor with same name(Constructor name must always be same as Class name).
8. Overriding and Exception-Handling: Below are two rules to note when overriding methods
related to exception-handling.
Rule#1: If the super-class overridden method does not throws an exception, subclass overriding
method can only throws the unchecked exception, throwing checked exception will lead to
compile-time error.
Rule#2: If the super-class overridden method does throws an exception, subclass overriding
method can only throw same, subclass exception. Throwing parent exception in Exception
hierarchy will lead to compile time error. Also there is no issue if subclass overridden method is
not throwing any exception.
9 .Overriding and abstract method: Abstract methods in an interface or abstract class are
meant to be overridden in derived concrete classes otherwise a compile-time error will be
thrown.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many contexts. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.
class BikeSpeed{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
The static keyword in Java is used mainly for memory management. It is used with variables, methods,
blocks and nested classes. It is a keyword that is used to share the same variable or method of a given
class. This is used for a constant variable or a method that is the same for every instance of a class. The
Static variable
A Static variable is used to fulfill the common requirement. For Example the Company name
of employees, the college name of students, etc. The Name of the college is common for all
students.
The static variable allocates memory only once in the class area at the time of class loading.
Using a static variable we make our program memory efficient (i.e it saves memory).
Suppose we want to a store record of all employees of any company, in this case, employee id is unique for
every employee but company name is common for all. When we create a static variable as a company
name then only once memory is allocated otherwise it allocates a memory space each time for every
employee.
static keyword always fixed the memory that means that it will be located only once in the program
whereas final keyword always fixed the value that means it makes variable values constant.
Static Method in Java
If you apply static keyword with any method, it is known as static method. A static method belongs to the
class rather than the object of a class. It can be invoked without the need for creating an instance of a class.
It can access static data member and can change the value of it.
class A
{
void fun1()
{
System.out.println("Hello I am Non-Static");
}
static void fun2()
{
System.out.println("Hello I am Static");
}
}
class Person
{
public static void main(String args[])
{
A oa=new A();
oa.fun1(); // non static method
A.fun2(); // static method
}
}
Output:
Hello I am Non-Static
Hello I am Static
The main purpose of using this keyword is to differentiate the formal parameter and data members of
class, whenever the formal parameter and data members of the class are similar then jvm get ambiguity (no
To differentiate between formal parameter and data member of the class, the data member of the class must
be preceded by "this".
Example:
The process of obtaining the data members and methods from one class to another class is known
In the inheritance the class which is give data members and methods is known as base or super
or parent class.
The class which is taking the data members and methods is known as sub or derived or child
class.
The concept of inheritance is also known as re-usability or extendable classes or sub classing
or derivation.
It's main uses are to enable polymorphism and to be able to reuse code for different classes by
putting it in a common super class
Based on number of ways inheriting the feature of base class into derived class we have five types of
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
class SuperClass
{
int i;
String s;
SuperClass()
{
System.out.println("U r in Default Constructor Of Super Class");
i=10;
s="Super Class";
}
SuperClass(int i,String s)
{
System.out.println("U r in Parametric Constructor of Super Class");
this.i=i;
this.s=s;
}
void display()
{
System.out.println("U r in function of Sper Class");
System.out.println("The Values of I==>"+i);
System.out.println("The Values of S==>"+s);
}
}
}
void display()
{
System.out.println("U r in function of Sub Class");
System.out.println("The Values of I==>"+j);
System.out.println("The Values of S==>"+s1);
}
}
Class Containing Main function which will Create object of Sub class access the Super class members.
class SperSubDemo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
SubClass s=new SubClass();
s.display();
SubClass s1=new SubClass();
s1.display();
}
}
Output:
Hello World!
U r in Default Constructor Of Super Class
U r in Default Constructor Of Sub Class
U r in function of Sub Class
The Values of I==>10
The Values of S==>Sub Class
U r in Default Constructor Of Super Class
U r in Default Constructor Of Sub Class
U r in function of Sub Class
The Values of I==>10
The Values of S==>Sub Class
3.8.3.2 Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class. In below image, the class A
serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
In Java, a class cannot directly access the grandparent‟s members.
class Student
{
int sid;
String name;
String addrs;
Student ()
{
System.out.println("U r in Default Constructor of Student Class");
sid=10;
name="Rama";
addrs="Nashik";
}
Student (int i,String s,String d1)
{
System.out.println("U r in Parametric Constructor of Student Class");
sid=i;
name=s;
addrs=d1;
}
EnggStudent ()
{
System.out.println("U r in Default Constructor of Engineering Student Class");
branch="CSE";
clg="IIT Bombay";
}
EnggStudent (int i,String s,String a,String s1, String s2)
{
super(i,s,a);
System.out.println("U r in Parametric Constructor of Engineering Student Class");
branch=s1;
clg=s2;
}
class StudentDemo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
SecondYearStudent s= new SecondYearStudent();
s.display();
SecondYearStudent s1= new
SecondYearStudent(10,"Ajay","Jalgaon","Mechanical","IIT Madras","2019-20", "First Class");
s1.display();
}
}
Output:
Hello World!
U r in Default Constructor of Student Class
U r in Default Constructor of Engineering Student Class
Student Id==>10
Student Name==>Rama
Student College==>Nashik
Student Branch==>CSE
Student Batch==>2018-19
Student Id==>10
Student Name==>Ajay
Student College==>Jalgaon
Student Branch==>Mechanical
Student Batch==>2019-20
3.8.3.3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A serves as a base class for the derived class
B,C and D.
class Student
{
int sid;
String name;
String addrs;
Student ()
{
System.out.println("U r in Default Constructor of Student Class");
sid=10;
name="Rama";
addrs="Nashik";
}
Student (int i,String s,String d1)
{
System.out.println("U r in Parametric Constructor of Student Class");
sid=i;
name=s;
addrs=d1;
}
spl="Heart";
clg="JIIM";
}
}
}
EnggStudent ()
{
System.out.println("U r in Default Constructor of Engineering Student Class");
branch="C SE";
clg="IIT Bombay";
}
EnggStudent (int i,String s,String a,String s1, String s2)
{
super(i,s,a);
System.out.println("U r in Parametric Constructor of Engineering Student Class");
branch=s1;
clg=s2;
}
class StudentDemo
{
public static void main(String[] args)
{
System.out.println("\n\n Engineering Student Details\n");
EnggStudent e= new EnggStudent();
e.display();
EnggStudent e1= new EnggStudent(10,"Ajay","Jalgaon","Mechanical","IIT Madras");
e1.display();
Output:
Engineering Student Details
Student Id==>10
Student Name==>Rama
Student Address==>Nashik
Student Branch==>CSE
Student Id==>10
Student Name==>Ajay
Student Address==>Jalgaon
Student Id==>10
Student Name==>Rama
Student Address==>Nashik
Student Specialization==>Heart
Student College==>JIIM
U r in Parametric Constructor of Student Class
U r in Parametric Constructor of Medical Student Class
Student Id==>10
Student Name==>Vijay
Student Address==>Jalgaon
Student Specialization==>Brain
Student College==>IIM
3.8.3.4 Multiple Inheritance (Through Interfaces): In Multiple inheritance ,one class can have more than
one superclass and inherit features from all parent classes. Please note that Java does not support multiple
inheritance with classes. In java, we can achieve multiple inheritance only through Interfaces. In image
below, Class C is derived from interface A and B.
Multiple inheritance in jave is not directly supported that is one class cannot extend more than one
class at a time, so to achieve multiple inheritance we need to use interface. Using which we can
obtain multiple inheritance for which class have to extend one class and can implement one or more
interfaces.
class Employee
{
int emp_no;
String e_name;
Employee()
{
System.out.println("U r in Default Constructor of Employee Class");
emp_no=10;
e_name="Abcd";
}
Employee(int i,String s)
{
System.out.println("U r in Parametric Constructor of Employee Class");
emp_no=i;
e_name=s;
}
interface CalSalary
{
void calSalary();
}
class WegEmployee extends Employee implements CalSalary
{
int hrs,hrs_rt;
String dept;
int sal;
WegEmployee()
{
System.out.println("U r in Default Constructor of WegEmployee Class");
hrs=8;
hrs_rt=200;
dept="Testing";
}
WegEmployee(int i,String s,int j,int r,String s1)
{
super(i,s);
System.out.println("U r in Parametric Constructor of WegEmployee Class");
hrs=j;
hrs_rt=r;
dept=s1;
}
public void display()
{
System.out.println("\n\t The Emp_Id==>"+emp_no);
System.out.println("\n\t The Emp_Name is==>"+e_name);
System.out.println("\n\t The Dept. of Emp is==>"+dept);
System.out.println("\n\t The Working Hours Are==>"+hrs);
System.out.println("\n\t The Hrs per Rate is==>"+hrs_rt);
calSalary();
}
public void calSalary()
{
sal=hrs*hrs_rt*25;
System.out.println("\n\t The Salary Of Employee is==>"+sal);
}
}
class EmployeeDemo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
WegEmployee s= new WegEmployee();
s.display();
WegEmployee s1= new WegEmployee(35,"Vijay",8,100,"Account");
s1.display();
}
}
Output:
Hello World
U r in Default Constructor of Employee Class
U r in Default Constructor of WegEmployee Class
The Emp_Id==>10
The Emp_Id==>35
3.8.3.5 Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of
inheritance. Since java doesn‟t support multiple inheritance with classes, the hybrid inheritance is also
not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
Same as Multiple inheritance hybrid inheritance in jave is not directly supported that is one class
cannot extend more than one class at a time, so to achieve hybrid inheritance we need to use
interface. Using which we can obtain multiple inheritance for which class have to extend one class
and can implement one or more interfaces.
3.8.4 Important Rules Regarding Inheritance:
In java programming one derived class can extends only one base class because java
programming does not support multiple inheritance through the concept of classes, but it can
be supported through the concept of Interface.
Whenever we develop any inheritance application first create an object of bottom most
derived class but not for top most base class.
When we create an object of bottom most derived class, first we get the memory space for the
data members of top most base class, and then we get the memory space for data member of
other bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top most
base classes.
If we do not want to give the features of base class to the derived class then the definition of
the base class must be preceded by final hence final base classes are not reusable or not
inheritable.
If we are do not want to give some of the features of base class to derived class than such
features of base class must be as private hence private features of base class are not inheritable
or accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but
constructors of base class can not be inherited because every constructor of a class is made for
initializing its own data members but not made for initializing the data members of other
classes.
An object of base class can contain details about features of same class but an object of base
class never contains the details about special features of its derived class (this concept is
known as scope of base class object).
For each and every class in java there exists an implicit predefined super class called
java.lang.Object. because it providers garbage collection facilities to its sub classes for
collecting un-used memory space and improved the performance of java application.
To declare an interface, use interface keyword. It is used to provide total abstraction. That means all
the methods in an interface are declared with an empty body and are public and all fields are public,
static and final by default. A class that implement interface must implement all the methods declared
in the interface. To implement interface use implements keyword.
Syntax:
interface <interface_name> {
Example:
interfacePlayer
{
finalintid = 10;
intmove();
}
A real-world example:
Let‟s consider the example of vehicles like bicycle, car, bike, etc. they have common functionalities. So
we make an interface and put all these common functionalities. And lets Bicycle, Bike, car ….etc.
implement all these functionalities in their own class in their own way.
importjava.io.*;
interfaceVehicle {
classBicycle implementsVehicle{
intspeed;
intgear;
// to change gear
@Override
publicvoidchangeGear(intnewGear){
gear = newGear;
}
// to increase speed
@Override
publicvoidspeedUp(intincrement){
// to decrease speed
@Override
publicvoidapplyBrakes(intdecrement){
publicvoidprintStates() {
System.out.println("speed: "+ speed
+ " gear: "+ gear);
}
}
classBike implementsVehicle {
intspeed;
intgear;
// to change gear
@Override
publicvoidchangeGear(intnewGear){
gear = newGear;
}
// to increase speed
@Override
publicvoidspeedUp(intincrement){
// to decrease speed
@Override
publicvoidapplyBrakes(intdecrement){
publicvoidprintStates() {
System.out.println("speed: "+ speed + " gear: "+ gear);
}
}
classGFG {
Output;
voiddisplay()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
3.10.2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use
super keyword. This code snippet helps to understand the said usage of super keyword.
/* Subclass Student */
classStudent extendsPerson
{
voidmessage()
{
System.out.println("This is student class");
}
Output:
This is Student Class
This is Person Class
3.10.3. Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, „‟super‟ can call both parametric as well as
non-parametric constructors depending upon the situation. Following is the code snippet to
explain the above concept:
/* superclass Person */
classPerson
{
Person()
{
System.out.println("Person class Constructor");
}
}
Output:
Person class Constructor
Student class Constructor
In java you may find various wrapper classes. Some of wrapper classes and their equivalent primitive
data types are as follow.
These classes “wrap” the primitive data type in a corresponding object. Often, the wrapping is
done by the compiler. If you use a primitive where an object is expected, the compiler boxes the primitive
in its wrapper class for you. Similarly, if you use a Number object when a primitive is expected, the
compiler unboxes the object for you. This is also called Autoboxing and Unboxing.
Number Methods
Following is the list of the instance methods that all the subclasses of the Number class
implements −
1 xxxValue(): Converts the value of this Number object to the xxx data type and returns it.
4 valueOf(): Returns an Integer object holding the value of the specified primitive.
5 toString(): Returns a String object representing the value of a specified int or Integer.
6 parseInt(): This method is used to get the primitive data type of a certain String.
8 ceil(): Returns the smallest integer that is greater than or equal to the argument. Returned as a
double.
9 floor(): Returns the largest integer that is less than or equal to the argument. Returned as a double.
10 rint(): Returns the integer that is closest in value to the argument. Returned as a double.
11 round(): Returns the closest long or int, as indicated by the method's return type to the argument.
12 min(): Returns the smaller of the two arguments.
14 exp(): Returns the base of the natural logarithms, e, to the power of the argument.
16 pow(): Returns the value of the first argument raised to the power of the second argument.
24 atan2(): Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
1
toString() : Returns the string corresponding to the int value.
2
valueOf() : returns the Integer object initialised with the value provided.
3
valueOf(String val,int radix): Another overloaded function which provides
function similar to new Integer(Integer.parseInteger(val,radix))
4
valueOf(String val)
Another overloaded function which provides function similar to
new Integer(Integer.parseInt(val,10))
5
getInteger(): returns the Integer object representing the value associated with the
given system property or null if it does not exist.
6
decode(): returns a Integer object holding the decoded value of string provided.
7
rotateLeft(): Returns a primitive int by rotating the bits left by given distance in
two‟s complement form of the value given.
8
rotateRight() : Returns a primitive int by rotating the bits right by given distance in
the twos complement form of the value given.
9
byteValue(): returns a byte value corresponding to this Integer Object
10
shortValue(): returns a short value corresponding to this Integer Object.
11
floatValue(): returns a float value corresponding to this Integer Object.
12
intValue(): returns a value corresponding to this Integer Object.
13
doubleValue(): returns a double value corresponding to this Integer Object.
14
hashCode(): returns the hashcode corresponding to this Integer Object.
15
bitcount(): Returns number of set bits in twos complement of the integer given.
16
equals() : Used to compare the equality of two Integer objects
17
compareTo(): Used to compare two Integer objects for numerical equality.
18
compare(): Used to compare two primitive int values for numerical equality
19
reverse(): returns a primitive int value reversing the order of bits in two‟s
complement form of the given int value.
20
static int max(int a, int b): This method returns the greater of two int values as if by
calling Math.max.
21
static int min(int a, int b): This method returns the smaller of two int values as if by
calling Math.min.
2 valueOf(): returns the Float object initialised with the value provided.
3 parseFloat(): returns float value by parsing the string. Differs from valueOf() as it
returns a primitive float value and valueOf() return Float object.
11 isNaN(): returns true if the float object in consideration is not a number, otherwise
false.
12 isInfinite(): returns true if the float object in consideration is very large, otherwise
false
15 compare(): Used to compare two primitive float values for numerical equality.
17 IntBitsToFloat(): Returns the float value corresponding to the long bit pattern of the
argument. It does reverse work of the previous two methods.
2 valueOf(): returns the Byte object initialised with the value provided.
4 decode(): returns a Byte object holding the decoded value of string provided.
14 compare(): Used to compare two primitive byte values for numerical equality.
2 valueOf(): returns the Short object initialised with the value provided.
4 decode(): returns a Short object holding the decoded value of string provided.
2 valueOf() : returns the Long object initialised with the value provided.
4 decode(): returns a Long object holding the decoded value of string provided.
14 compare(): Used to compare two primitive long values for numerical equality.
15 bitcount(): Returns number of set bits in twos complement of the long given.
2 valueOf() : returns the Double object initialised with the value provided.
4 decode() : returns a Double object holding the decoded value of string provided.
14 compare() : Used to compare two primitive double values for numerical equality.
15 toHexString() : Returns the hexadecimal representation of the argument double
value.
1
toString(char ch) : It returns a String class object representing the specified
character value(ch)
2
char toLowerCase(char ch) : It returns the lowercase of the specified char
value(ch).
3
char toUpperCase(char ch) : It returns the uppercase of the specified char
value(ch).
4
boolean isLowerCase(char ch) : It determines whether the specified char value(ch)
is lowercase or not.
5
boolean isUpperCase(char ch) : It determines whether the specified char value(ch)
is uppercase or not.
6 char charValue(): This method returns the value of this Character object.
7
static int compare(char x, char y): This method compares two char values
numerically.
8
int compareTo(Character anotherCharacter): This method compares two
Character objects numerically.
9
static int digit(char ch, int radix): This method returns the numeric value of the
character ch in the specified radix.
10
boolean equals(Object obj): This method compares this object against the specified
object.
4.10 Type conversion / Type Casting
When you assign value of one data type to another, the two types might not be compatible with
each other. If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to be casted or converted explicitly.
For example, assigning an int value to a long variable.
Widening conversion takes place when two data types are automatically converted. This happens
when:
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or Boolean. Also, char and Boolean are not
compatible with each other.
Example:
classTest
{
publicstaticvoidmain(String[] args)
{
inti = 100;
Output:
If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
Example:
Output:
Output:
20 20 20
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper
class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to
int, Long to long, Double to double etc.
Example
Output:
333
4.12.1 Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
4.12.2 Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.
arrayRefVar=new datatype[size];
Output:
10 20 70 40 50
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Output:
123
245
445
Arrays of Objects
Object[] JavaObjectArray;
Another declaration can be as follows:
Hello World
5
CHAPTER 5
STRING AND EXCEPTIONS HANDLING
Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot
grow), Strings are imm In Java programming language, strings are treated as objects. The Java platform
provides the String class to create and manipulate strings. Whenever a change to a String is made, an
entirely new String is created. Every string in java is end with “\0” symbol which is treated as last
character or end of string. This character is placed at end of every string by default by compiler.
In above diagram you can see the representation of string along with indexes and memory address and as mentioned
it ends with “\0”.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Output:
Hello
strings
Demo
5 String concat(String str): Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb): Returns true if and only if this String represents the same
sequence of characters as the specified StringBuffer.
7 static String copyValueOf(char[] data): Returns a String that represents the character sequence in the
array specified.
8 static String copyValueOf(char[] data, int offset, int count): Returns a String that represents the
character sequence in the array specified.
9 boolean endsWith(String suffix): Tests if this string ends with the specified suffix.
12 byte getBytes(): Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.
13 byte[] getBytes(String charsetName): Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters from this string into
the destination character array.
16 int indexOf(int ch): Returns the index within this string of the first occurrence of the specified
character.
17 int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
18 int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring.
19 int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
21 int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified
character.
22 int lastIndexOf(int ch, int fromIndex): Returns the index within this string of the last occurrence of the
specified character, searching backward starting at the specified index.
23 int lastIndexOf(String str): Returns the index within this string of the rightmost occurrence of the
specified substring.
24 int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last occurrence of
the specified substring, searching backward starting at the specified index.
26 boolean matches(String regex): Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len): Tests if two string regions are
equal.
29 String replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement: Replaces each substring of this string that matches
the given regular expression with the given replacement.
31 String replaceFirst(String regex, String replacement): Replaces the first substring of this string that
matches the given regular expression with the given replacement.
32 String[] split(String regex): Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit): Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix): Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset): Tests if this string starts with the specified prefix
beginning a specified index.
36 CharSequence subSequence(int beginIndex, int endIndex): Returns a new character sequence that is a
subsequence of this sequence.
37 String substring(int beginIndex): Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.
40 String toLowerCase(): Converts all of the characters in this String to lower case using the rules of the
default locale.
41 String toLowerCase(Locale locale): Converts all of the characters in this String to lower case using the
rules of the given Locale.
43 String toUpperCase(): Converts all of the characters in this String to upper case using the rules of the
default locale.
44 String toUpperCase(Locale locale): Converts all of the characters in this String to upper case using the
rules of the given Locale.
45 String trim(): Returns a copy of the string, with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x): Returns the string representation of the passed data type
argument.
Syntax:
str.append("GFG");
5.3.3 StringTokenizer: StringTokenizer class in Java is used to break a string into tokens.
Example:
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some
operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
5.3.4 StringJoiner: StringJoiner is a class in java.util package which is used to construct a sequence of
characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with
a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after
each string, StringJoiner provides an easy way to do that without much code to write.
Syntax:
public StringJoiner(CharSequence delimiter)
2) String is slow and consumes more memory StringBuffer is fast and consumes less memory when
when you concat too many strings because you cancat strings.
every time it creates new instance.
3) String class overrides the equals() method of StringBuffer class doesn't override the equals() method
Object class. So you can compare the of Object class.
contents of two strings by equals() method.
1) StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not thread
It means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Future";
s.concat(" World");//concat() method appends the string at the end
System.out.println(s);//will print Future because strings are immutable objects
}
}
Output: Future
Now it can be understood by the diagram given below. Here Future is not changed but a new object is created with
Future World. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers to "Future" not to
"Future World".
But if we explicitly assign it to the reference variable, it will refer to "Future World" object. For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Future";
s=s.concat(" World");
System.out.println(s);
}
}
In such case, s points to the "Future World". Please notice that still Future object is not modified.
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the
system generated exception below:
As shown in the exception hierarchy, a Throwable class is a superclass of all errors and
exceptions in Java. Objects those are instances of Throwable or one of its subclasses are thrown
by JVM or by Java throw statement.
5.5.1 Error:
An Error is a subclass of Throwable that represents serious errors that can‟t be handled. A
method is not required to declare throws clause for Error or any of its subclasses for the errors
thrown during execution of the method but not caught.
Error and its subclasses are unchecked exceptions. Eroors may be occurred because of
syntactical and symbolic mistakes done by the programmer .
5.5.2 Exception:
word it occurs because of the logical mistakes done by the programmer. Exception is a subclass
of Throwable. Exception and its subclasses represent the problems from which a program can
recover and should be handled by the application.Exception has two sub type:
These exception are need not be handled before compilation of the source code. Complier
doesn‟t check whether the exceptions are handled before compilation or not that‟s why they are
called as Unchecked exceptions. The classes that extends RunTimeException are called
unchecked Exception. An unchecked exception occurs at run-time, it can‟t be checked at
compile time, an application should handle these exceptions.
Checked exception are checked at compile time and application should handle these exceptions
before the compilation of program. If these exceptions are not handled it will not allow you to
even compile the source code. That‟s why they are called as Checked Exception. The classes
that extends Throwable class except RunTimeExpception and Error are called Checked
Exception.
We can also create our own exception. Here are few rules:
Try Block: The "try" keyword is used to specify a block where we should place exception code. It means we write
the The code which may cause exception (risky code) in try block. If exception occurs then suddenly compiler will
terminate the excection of try block and will start the execution of catch or finally block. The try block must be
followed by either catch or finally. It means, we can't use try block alone.
Catch: The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch block alone. If the exception is occurred in try block then only catch block will be excuted. In catch block we
write a code to handle the exception or to describe more information about exception to user. It can be followed by
finally block later.
Syntax:
try {
// Risky code
// Catch block
5.6.3 Finally: The "finally" block is used to execute the important code of the program. It is executed whether an
exception is handled or not. It guarantees that the code written in finally block will surely execute even if exception
occur or doesn‟t occur.
Syntax:
try {
// Risky code
// Catch block
finally {
5.6.4 Throw: The "throw" keyword is used to throw an Exception. It means user can manually create or generate the
exception using throw keywords.
5.6.5 Throws: The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that
there may occur an exception in the method. It informs the compiler that the specified methods may throws the
exception, in that case user doesn‟t have to handle the exception that will be handled by the compiler. It is always
used with method signature.
See the below diagram to understand the flow of the call stack.
Java Exception Handling Example
Let's see an example of Java Exception Handling by using a try-catch statement to handle the exception.
Output:
ackages in Java are a way to encapsulate a group of classes, interfaces, enumerations, annotations, and
sub-packages. Conceptually, you can think of java packages as being similar to different folders on your
computer. In this tutorial, we will cover the basics of packages in Java.
Each package in Java has its unique name and organizes its classes and interfaces into
a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same
package, they can appear in different packages. This is possible by assigning a
separate namespace to each package.
Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import
class from existing packages and use it in our program. A package is a container of a group of
related classes where some of the classes are accessible are exposed and others are kept for
internal purpose.
We can reuse existing classes from the packages as many time as we need it in our program.
Example:
import java.util.*;
import java.util.vector;
import java.util.*;
Packages
6.1.2.1 Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly
used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button ,
;menus etc).
These are the packages that are defined by the user. First we create a directory myPackage (name should
be same as the name of the package). Then create the MyClass inside the directory with the first
statement being the package names.
6.2 Creating User Defined Packages:
we will see the the following program in which we will create the user defined package we will
see how to compile to compile java package so that it can be used or imported whenever
required.
package myPackage;
System.out.println(s);
import myPackage.MyClass;
// with a value
// the package.
obj.getNames(name);
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Example-2
package package_one;
package package_two;
import package_one.ClassTwo;
import package_two.ClassOne;
a.methodClassTwo();
b.methodClassOne();
Output:
If you are not using any IDE, you need to follow the syntax given below:
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.
1. import package.*;
2. import package.classname;
3. fully qualified name.
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
Output:Hello
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.A;
class B{
obj.msg();
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the class
or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
Output:Hello
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from the
java.util package. This package also contains date and time facilities, random-number generator and other
utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will
import ALL the classes in the java.util package:
Example
import java.util.*;
To check the current setting of the CLASSPATH, issue the following command:
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath or -cp of the javac and java commands, for example,
The table below gives a real picture of which type access is possible and which is not when
using packages in Java:
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. That is the abstract class
can be extended by any other class which have to implement all the abstract method declared in
abstract class. It cannot be instantiated.
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Interface (100%)
Syntax:
//Declaration using abstract keyword
abstract class A{
void anotherMethod(){
//Does something
Example:
//abstract method
System.out.println("Woof");
obj.sound();
Output: Woof
Example-2
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
//In real scenario, implementation is provided by others i.e. unknown by end user
class TestAbstraction1{
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
Example-3
Output:
bike is created
running safely..
gear changed
6.6.2Points to Remember
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
Output:
I am a
I am b
I am c
I am d
To declare an interface, use interface keyword. It is used to provide total abstraction. That means all
the methods in an interface are declared with an empty body and are public and all fields are public,
static and final by default. A class that implement interface must implement all the methods declared
in the interface. To implement interface use implements keyword. Interface is used to implement
multiple and hybrid inheritance in java, as one class cannot extend more than one class but can
implement many classes and can extend single class.
Syntax:
interface <interface_name> {
Example:
interfacePlayer
{
finalintid = 10;
intmove();
}
A real-world example:
Let‟s consider the example of vehicles like bicycle, car, bik etc. they have common functionalities. So we
make an interface and put all these common functionalities. And lets Bicycle, Bike, car ….etc implement
all these functionalities in their own class in their own way.
importjava.io.*;
interfaceVehicle {
intspeed;
intgear;
// to change gear
@Override
publicvoidchangeGear(intnewGear){
gear = newGear;
}
// to increase speed
@Override
publicvoidspeedUp(intincrement){
// to decrease speed
@Override
publicvoidapplyBrakes(intdecrement){
publicvoidprintStates() {
System.out.println("speed: "+ speed
+ " gear: "+ gear);
}
}
classBike implementsVehicle {
intspeed;
intgear;
// to change gear
@Override
publicvoidchangeGear(intnewGear){
gear = newGear;
}
// to increase speed
@Override
publicvoidspeedUp(intincrement){
// to decrease speed
@Override
publicvoidapplyBrakes(intdecrement){
publicvoidprintStates() {
System.out.println("speed: "+ speed + " gear: "+ gear);
}
}
classGFG {
Output;
Java does not support multiple inheritances but we can achieve the effect of multiple
inheritances using interfaces. In interfaces, a class can implement more than one interface which
can‟t be done through extends keyword.Let‟s say we have two interfaces with same method
name (demo) and different return types(int and String)
publicinterfaceInterfaceX
{
publicint demo ();
}
publicinterfaceInterfaceY
{
publicString demo ();
}
Now, Suppose we have a class that implements both those interfaces:
interface Flyable {
void fly();
}
interface Eatable {
void eat();
}
// Bird class will implement both interfaces
Output:
Bird eats
Bird flying
But there are many differences between abstract class and interface that are given below.
Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
6.9.1 Generalization
Generalization is the process of extracting shared characteristics from two or more classes, and
combining them into a generalized superclass. Shared characteristics can be attributes, associations, or
methods. Generalization is the bottom-up process of abstraction, where we club the differences among entities
according to the common feature and generalize them into a single superclass. The original entities are thus
subclasses of it.
6.9.2 Specialization
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 called narrowing or down-casting. Specialization is defined as the process of
subclassing a superclass entity on the basis of some distinguishing characteristic of the entity in
the superclass.
Narrowing is not safe because the classes will become more and more specific thus giving rise
to more and more doubts. For example if we say Vehicle is a Car we need a proof.
The reason for creating such hierarchical relationship is Certain attributes of the superclass may
apply to some but not all entities of the superclass. These extended subclasses then can be used
to encompass the entities to which these attributes apply.
In contrast to generalization, specialization means creating new subclasses from an existing class.
If it turns out that certain attributes, associations, or methods only apply to some of the objects of the
class, a subclass can be created. The most inclusive class in a generalization/specialization is called the
superclass and is generally located at the top of the diagram. The more specific classes are called
subclasses and are generally placed below the superclass.
CHAPTER 7
JAVA INPUT-OUTPUT
7.1 Introduction:
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files. The File class from the
java.io package, allows us to work with files. To use the File class, create an object of the class, and
specify the filename or directory name. The File class is Java‟s representation of a file or directory path
name. Because file and directory names have different formats on different platforms, a simple string is
not adequate to name them. The File class contains several methods for working with the path name,
deleting and renaming files, creating new directories, listing the contents of a directory, and determining
several common attributes of files and directories.
boolean createNewFile() : Atomically creates a new, empty file named by this abstract
5
pathname .
static File createTempFile(String prefix, String suffix) : Creates an empty file in the default
6 temporary-file directory.
boolean delete() : Deletes the file or directory denoted by this abstract pathname.
boolean equals(Object obj) : Tests this abstract pathname for equality with the given
7
object.
boolean exists() : Tests whether the file or directory denoted by this abstract pathname
8
exists.
9 String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname.
String getName() : Returns the name of the file or directory denoted by this abstract
11
pathname.
12 String getParent() : Returns the pathname string of this abstract pathname‟s parent.
13 File getParentFile() : Returns the abstract pathname of this abstract pathname‟s parent.
15 boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
16 boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal file.
boolean isHidden() : Tests whether the file named by this abstract pathname is a hidden
17
file.
18 long length() : Returns the length of the file denoted by this abstract pathname.
19 String[] list() : Returns an array of strings naming the files and directories in the directory .
20 File[] listFiles() : Returns an array of abstract pathnames denoting the files in the directory.
Example 1:
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
*import java.io.File;
class fileProperty
System.out.println("Path: "+f.getPath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());
System.out.println("Is a directory:"+f.isDirectory());
}
Output:
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writeable:true
Is readabletrue
Is a directory:false
The two important streams are FileInputStream and FileOutputStream, which would
be discussed in this tutorial.
7.2.2 FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can
be used to write to stream or to do other operations on the stream.
1 public void close() throws IOException{} : This method closes the file output stream. Releases any
system resources associated with the file. Throws an IOException.
protected void finalize()throws IOException {}: This method cleans up the connection to the file.
2 Ensures that the close method of this file output stream is called when there are no more references to this
stream. Throws an IOException.
public void write(int w)throws IOException{} : This methods writes the specified byte to the output
3
stream.
4 public void write(byte[] w) : Writes w.length bytes from the mentioned byte array to the OutputStream.
Example:
import java.io.FileOutputStream;
try{
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
Output: Success...
The content of a text file testout.txt is set with the data Welcome to Java Files.
7.2.3 FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
Sr.No. Method & Description
public void close() throws IOException{}: This method closes the file output stream. Releases any
1
system resources associated with the file. Throws an IOException.
protected void finalize()throws IOException {}: This method cleans up the connection to the file.
2 Ensures that the close method of this file output stream is called when there are no more references to
this stream. Throws an IOException.
public int read(int r)throws IOException{}: This method reads the specified byte of data from the
3 InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the
file.
public int read(byte[] r) throws IOException{}: This method reads r.length bytes from the input
4 stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be
returned.
public int available() throws IOException{}: Gives the number of bytes that can be read from this
5
file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following
links −
ByteArrayInputStream
Java FileInputStream example 2: read all characters
package com.javatpoint;
import java.io.FileInputStream;
try{
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
Output:
Constructor Description
Class methods
Method Description
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to java Files.");
buffer.close();
System.out.println("Success");
}
}
Output:
success
The content of a text file testout.txt is set with the data Welcome to Java Files.
boolean markSupported() It is used to test the input stream support for the mark and reset method.
boolean ready() It is used to test whether the input stream is ready to be read.
It repositions the stream at a position the mark method was last called on this input
void reset()
stream.
void mark(int
It is used for marking the present position in a stream.
readAheadLimit)
It closes the input stream and releases any of the system resources associated with the
void close()
stream.
package com.mypackage;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Output:
Here, we are assuming that you have following data in "testout.txt" file:
Output:
package com.mypackage;
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:
3. Serialized Object Can be stored in File, database and can be desterilized when ever required.
Only the objects of those classes can be serialized which are implementing java.io.Serializable interface.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
7.4.3 ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only
objects that support the java.io.Serializable interface can be written to streams.
Constructor:
Constructor Description
public ObjectOutputStream(OutputStream out) creates an ObjectOutputStream that writes to the specified
throws IOException {} OutputStream.
Important Methods
Method Description
public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.
public void flush() throws IOException {} flushes the current output stream.
public void close() throws IOException {} closes the current output stream.
Constructor
Constructor Description
public ObjectInputStream(InputStream in) throws creates an ObjectInputStream that reads from the
IOException {} specified InputStream.
Important Methods
Method Description
public final Object readObject() throws IOException,
reads an object from the input stream.
ClassNotFoundException{}
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can be converted into
stream.
import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(“Student ID:”+s.id);
System.out.println("Student Name: "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Student ID: 11
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides
many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is
the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive
types such as int, long, double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(),
nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the
scanner, you can call next().charAt(0) method which returns a single character.
Java Scanner Class Constructors
SN Constructor Description
It constructs a new Scanner that produces values scanned
1) Scanner(File source)
from the specified file.
It constructs a new Scanner that produces values scanned
2) Scanner(File source, String charsetName)
from the specified file.
It constructs a new Scanner that produces values scanned
3) Scanner(InputStream source)
from the specified input stream.
Scanner(InputStream source, String It constructs a new Scanner that produces values scanned
4)
charsetName) from the specified input stream.
It constructs a new Scanner that produces values scanned
5) Scanner(Readable source)
from the specified source.
It constructs a new Scanner that produces values scanned
6) Scanner(String source)
from the specified string.
It constructs a new Scanner that produces values scanned
7) Scanner(ReadableByteChannel source)
from the specified channel.
Scanner(ReadableByteChannel source, It constructs a new Scanner that produces values scanned
8)
String charsetName) from the specified channel.
It constructs a new Scanner that produces values scanned
9) Scanner(Path source)
from the specified file.
It constructs a new Scanner that produces values scanned
10) Scanner(Path source, String charsetName)
from the specified file.
SN Method Description
It is used to get the Pattern which the Scanner class is currently using
2) pattern delimiter()
to match delimiters.
It is used to find a stream of match results that match the provided
3) Stream<MatchResult> findAll()
pattern string.
It is used to find the next occurrence of a pattern constructed from the
4) String findInLine()
specified string, ignoring delimiters.
It is used to find the next occurrence of a pattern constructed from the
5) string findWithinHorizon()
specified string, ignoring delimiters.
6) boolean hasNext() It returns true if this scanner has another token in its input.
21) BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.
22) BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.
It scans the next token of the input into a boolean value and returns
23) boolean nextBoolean()
that value.
24) byte nextByte() It scans the next token of the input as a byte.
25) double nextDouble() It scans the next token of the input as a double.
26) float nextFloat() It scans the next token of the input as a float.
27) int nextInt() It scans the next token of the input as an Int.
28) String nextLine() It is used to get the input string that was skipped of the Scanner object.
29) long nextLong() It scans the next token of the input as a long.
30) short nextShort() It scans the next token of the input as a short.
31) int radix() It is used to get the default radix of the Scanner use.
34) Scanner skip() It skips input that matches the specified pattern, ignoring delimiters
36) String toString() It is used to get the string representation of Scanner using.
38) Scanner useLocale() It is used to sets this scanner's locale object to the specified locale.
It is used to set the default radix of the Scanner which is in use to the
39) Scanner useRadix()
specified radix.
Example 1
Let's see a simple example of Java Scanner where we are getting a single input from the user.
Here, we are asking for a string through in.nextLine() method.
import java.util.*;
in.close();
Output:
Example 2
import java.util.*;
scan.close();
int i = in.nextInt();
double d = in.nextDouble();
in.close();
Output:
Name: Abhishek
Age: 23
Salary: 25000.0
CHAPTER-8
8.1 Introduction:
A thread is a thread of execution in a program. The Java Virtual Machine allows an application
to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads
with lower priority. Each thread may or may not also be marked as a daemon. When code
running in some thread creates a new Thread object, the new thread has its priority initially set
equal to the priority of the creating thread, and is a daemon thread if and only if the creating
thread is a daemon.
We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of
our new class and call start() method to start the execution of a thread. Start() invokes the run()
method on the Thread object.
// Main Class
publicclassMultithread
{
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti=0; i<8; i++)
{
MultithreadingDemo object = newMultithreadingDemo();
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
}
catch(Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
classMultithread
{
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti=0; i<n; i++)
{
Thread object = newThread(newMultithreadingDemo());
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
8.3.3 Lifecycle and States of a Thread in Java
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only
in one of the shown states at any instant:
1. Born
2. Ready
3. Running
4. Blocked
5. Waiting
6. Timed Waiting (Sleeping)
7. Suspended
8. Dead
The diagram shown below represents various states of a thread at any instant of time.
Born
start()
Ready resume()
notify()
wait() Running
Blocked
Waiting sleep(t) suspend()
Sleeping Suspended
Sleep interval
expires
Dead
stop()
Runnable State (Ready): A thread that is ready to run is moved to runnable state. In this state, a
thread might actually be running or it might be ready run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run. Thread enter in to runnable
state after calling start() function from thread class.
Running: When run() function is called from thread function is enter in to running state. A
multi-threaded program allocates a fixed amount of time to each individual thread. Each and
every thread runs for a short while and then pauses and surrenders the CPU to another thread, so
that other threads can get a chance to run. When this happens, all such threads that are ready to
run, waiting for the CPU and the currently running thread lies in runnable state.
Waiting state: When a thread is temporarily inactive, then it‟s in one of the following states:
Waiting
Blocked: When a thread is waiting for I/O to complete, it lies in the blocked state. It‟s the
responsibility of the thread scheduler to reactivate and schedule a blocked thread. A thread in
this state cannot continue its execution any further until it is moved to runnable state. Any thread
in these states does not consume any CPU cycle. When the I/O recourses get available then
thread enters into ready to run state.
A thread is in the blocked state when it tries to access a protected section of code that is
currently locked by some other thread. When the protected section is unlocked, the schedule
picks one of the thread which is blocked for that section and moves it to the runnable state.
Waiting State: a thread is in the waiting state when it waits for another thread on a condition.
Another thread may call wait() function. When this condition is fulfilled, the scheduler is
notified by notify() function and the waiting thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in the runnable
state is scheduled by the thread scheduler to run. It is the responsibility of thread scheduler to
determine which thread to run.
Timed waiting (sleeping): A thread lies in timed waiting state when it calls a method sleep(t)
with a time out parameter in nanoseconds. A thread lies in this state until the timeout is
completed or until a notification is received. For example, when a thread calls sleep or a
conditional wait, it is moved to a timed waiting state.
Suspended State: a thread is in the suspended state when it is suspended for no any reason and
no any time limit using a suspend() function. When this condition is fulfilled, resume() function
can be called and the suspended thread is moved to runnable state.
Terminated (Dead) State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed
by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
A thread that lies in a terminated state does no longer consume any cycles of CPU.
Sr.
Constructor & Descriptions
No.
Thread(): Allocates a new Thread object
1
Sr.
Method & Descriptions
No.
activeCount(): Returns an estimate of the number of active threads in the current thread‟s
1
thread group and its subgroups
checkAccess(): Determines if the currently running thread has permission to modify this
2
thread
5 dumpStack(): Prints a stack trace of the current thread to the standard error stream
getStackTrace(): Returns an array of stack trace elements representing the stack dump of
10
this thread
run():If this thread was constructed using a separate Runnable run object, then that
17
Runnable object‟s run method is called; otherwise, this method does nothing and returns
yield(): A hint to the scheduler that the current thread is willing to yield its current use of a
18
processor
toString(): Returns a string representation of this thread, including the thread‟s name,
19
priority, and thread group
start(): Causes this thread to begin execution; the Java Virtual Machine calls the run method
20
of this thread
sleep(long millis): Causes the currently executing thread to sleep (temporarily cease
21 execution) for the specified number of milliseconds, subject to the precision and accuracy of
system timers and schedulers
22 setPriority(int newPriority): j Changes the priority of this thread
24 Suspend():
25 Wait():
import java.lang.*;
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
Thread.currentThread().setPriority(10);
Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
synchronized(sync_object)
// shared resources
This synchronization is implemented in Java with a concept called monitors. Only one thread can own a
monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other
threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
Following is an example of multi-threading with synchronized.
// Driver class
class SyncDemo
ThreadedSend S1 =
ThreadedSend S2 =
S1.start();
S2.start();
try
S1.join();
S2.join();
}
catch(Exception e)
System.out.println("Interrupted");
Output:
Sending Hi
Hi Sent
Sending Bye
Bye Sent
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types
at compile time.
Generics in Java are similar to templates in C++. The idea is to allow type (Integer, String, … etc. and
user defined types) to be a parameter to methods, classes and interfaces.
Java Generics are a language feature that allows for definition and use of generic types and
methods.” Generic types are instantiated to form parameterized types by providing actual type arguments
that replace the formal type parameters. A class like LinkedList<E> is a generic type that has a type
parameter E.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time than runtime.
4) Code Reusability: it allows code reusability as you can reuse the same code for different Types of data.
publicclassGenericMethodTest{
// generic method printArray
publicstatic< E >void printArray( E[] inputArray ){
// Display array elements
for(E element : inputArray){
System.out.printf("%s ", element);
}
System.out.println();
}
Output
Array integer Array contains: 1 2 3 4 5
public T get() {
return t;
}
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
Output:
Example-2
T getob()
{
return ob;
}
V getob1()
{
return ob1;
}
These ready-to-use collection classes solve lots of very common problems where we need to
deal with group of homogeneous as well as heterogeneous objects. The common operations in
involve add, remove, update, sort, search and more complex algorithms. These collection
classes provide very transparent support for all such operations using Collections APIs.
Collection interface is at the root of the hierarchy. Collection interface provides all general
purpose methods which all collections classes must support (or
throw UnsupportedOperationException). It extends Iterable interface which adds support
for iterating over collection elements using the “for-each loop” statement.
All other collection interfaces and classes (except Map) either extend or implement this
interface. For example, List (indexed, ordered) and Set (sorted) interfaces implement this
collection.
1.2. List
Lists represents an ordered collection of elements. Using lists, we can access elements by their
integer index (position in the list), and search for elements in the list. index start with 0, just like
an array.
1.3. Set
Sets represents a collection of sorted elements. Sets do not allow the duplicate elements. Set
interface does not provides no guarantee to return the elements in any predictable order; though
some Set implementations store elements in their natural ordering and guarantee this order.
1.4. Map
The Map interface enable us to store data in key-value pairs (keys should be immutable). A map
cannot contain duplicate keys; each key can map to at most one value.
The Map interface provides three collection views, which allow a map‟s contents to be viewed
as a set of keys, collection of values, or set of key-value mappings. Some map implementations,
like the TreeMap class, make specific guarantees as to their order; others, like the HashMap
class, do not.
1.5. Stack
The Java Stack interface represents a classical stack data structure, where elements can be
pushed to last-in-first-out (LIFO) stack of objects. In Stack we push an element to the top of the
stack, and popped off from the top of the stack again later.
1.6. Queue
A queue data structure is intended to hold the elements (put by producer threads) prior to
processing by consumer thread(s). Besides basic Collection operations, queues provide
additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.
One such exception is priority queue which order elements according to a supplied Comparator,
or the elements‟ natural ordering.
In general, queues do not support blocking insertion or retrieval operations. Blocking queue
implementations classes implement BlockingQueue interface.
Some useful classes which implement Map interface are – ArrayBlockingQueue, ArrayDeque,
ConcurrentLinkedDeque, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque,
LinkedBlockingQueue, LinkedList, LinkedTransferQueue, PriorityBlockingQueue,
PriorityQueue and SynchronousQueue.
1.7. Deque
A double ended queue (pronounced “deck“) that supports element insertion and removal at both
ends. When a deque is used as a queue, FIFO (First-In-First-Out) behavior results. When a deque
is used as a stack, LIFO (Last-In-First-Out) behavior results.
This interface should be used in preference to the legacy Stack class. When a deque is used as a
stack, elements are pushed and popped from the beginning of the deque.
8.9.1ArrayList in Java:
An ArrayList in Java represent a resizable list of objects. We can add, remove, find, sort and
replace elements in this list. ArrayList is part of Java‟s collection framework and implements
Java‟s List interface.
ArrayList Features
1. Ordered – Elements in arraylist preserve their ordering which is by default the order in which
they were added to the list.
2. Index based – Elements can be randomly accessed using index positions. Index start with '0'.
3. Dynamic resizing – ArrayList grows dynamically when more elements needs to be added than
it‟s current size.
4. Non synchronized – ArrayList is not synchronized, by default. Programmer needs to use
synchronized keyword appropiately or simply use Vector class.
5. Duplicates allowed – We can add duplicate elements in arraylist. It is not possible in sets.
Methods in ArrayList
12 removeAll(Collection<?> c): Removes from this list all of its elements that are
contained in the specified collection.
13 listIterator(): Returns a list iterator over the elements in this list (in proper sequence).
14 listIterator(int index): Returns a list iterator over the elements in this list (in proper
sequence), starting at the specified position in the list.
16 void clear(): This method is used to remove all the elements from any list.
17 void add(int index, Object element): This method is used to insert a specific element at
a specific position index in a list.
18 void trimToSize(): This method is used to trim the capacity of the instance of the
ArrayLis to the list‟s current size.
19 Object[] toArray(): This method is used to return an array containing all of the elements
in the list in correct order.
21 boolean addAll(int index, Collection C): Used to insert all of the elements starting at the
specified position from a specific collection into the mentioned list
22 boolean add(Object o): This method is used to append a specificd element to the end of
a list.
23 boolean addAll(Collection C): This method is used to append all the elements from a
specific collection to the end of the mentioned list, in such a order that the values are
returned by the specified collection‟s iterator.
24 int indexOf(Object O): The index the first occurrence of a specific element is either
returned, or -1 in case the element is not in the list.
// Printing elements
System.out.println(arrli);
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
LinkedList Features:
Doubly linked list implementation which implements List and Deque interfaces. Therefore, It can
also be used as a Queue, Deque or Stack.
Permits all elements including duplicates and NULL.
LinkedList maintains the insertion order of the elements.
It is not synchronized. If multiple threads access a linked list concurrently, and at least one of the
threads modifies the list structurally, it must be synchronized externally.
Use Collections.synchronizedList(new LinkedList()) to get synchronized linkedlist.
The iterators returned by this class are fail-fast and may
throw ConcurrentModificationException.
It does not implement RandomAccess interface. So we can access elements in sequential order
only. It does not support accessing elements randomly.
We can use ListIterator to iterate LinkedList elements
1
LinkedList( ): This constructor builds an empty linked list.
2
LinkedList(Collection c)
This constructor builds a linked list that is initialized with the elements of the collection c.
Apart from the methods inherited from its parent classes, LinkedList defines following methods
−
Sr.No. Method & Description
1
void add(int index, Object element)Inserts the specified element at the specified position index in
this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 ||
index > size()).
2
boolean add(Object o)
Appends the specified element to the end of this list.
3
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they
are returned by the specified collection's iterator. Throws NullPointerException if the specified
collection is null.
4
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the specified position.
Throws NullPointerException if the specified collection is null.
5
void addFirst(Object o)
Inserts the given element at the beginning of this list.
6
void addLast(Object o)
Appends the given element to the end of this list.
7
void clear()
Removes all of the elements from this list.
8
Object clone()
Returns a shallow copy of this LinkedList.
9
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this
list contains at least one element e such that (o==null ? e==null : o.equals(e)).
10
Object get(int index)
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the
specified index is out of range (index < 0 || index >= size()).
11
Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if this list is empty.
12
Object getLast()
Returns the last element in this list. Throws NoSuchElementException if this list is empty.
13
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the list does not
contain this element.
14
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not
contain this element.
15
ListIterator listIterator(int index)
Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified
position in the list. Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >= size()).
16
Object remove(int index)
Removes the element at the specified position in this list. Throws NoSuchElementException if this
list is empty.
17
boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws NoSuchElementException
if this list is empty. Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >= size()).
18
Object removeFirst()
Removes and returns the first element from this list. Throws NoSuchElementException if this list is
empty.
19
Object removeLast()
Removes and returns the last element from this list. Throws NoSuchElementException if this list is
empty.
20
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
21
int size()
Returns the number of elements in this list.
22
Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
23
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime type of
the returned array is that of the specified array.
Example
The following program illustrates several of the methods supported by LinkedList −
import java.util.*;
publicclassLinkedListDemo{
Output
Class constructors
Sr.No. Constructor & Description
1
Vector()
This constructor is used to create an empty vector so that its internal data array has size 10 and its
standard capacity increment is zero.
2
Vector(Collection<? extends E> c)
This constructor is used to create a vector containing the elements of the specified collection, in the
order they are returned by the collection's iterator.
3
Vector(int initialCapacity)
This constructor is used to create an empty vector with the specified initial capacity and with its
capacity increment equal to zero.
4
Vector(int initialCapacity, int capacityIncrement)
This constructor is used to create an empty vector with the specified initial capacity and capacity
increment.
Class methods
Sr.No. Method & Description
1 boolean add(E e)
This method appends the specified element to the end of this Vector.
2 void add(int index, E element)
This method inserts the specified element at the specified position in this Vector.
3 boolean addAll(Collection<? extends E> c)
This method appends all of the elements in the specified Collection to the end of this Vector.
4 boolean addAll(int index, Collection<? extends E> c)
This method inserts all of the elements in the specified Collection into this Vector at the specified
position.
5 void addElement(E obj)
This method adds the specified component to the end of this vector, increasing its size by one.
6 int capacity()
This method returns the current capacity of this vector.
7 void clear()
This method removes all of the elements from this vector.
8 clone clone()
This method returns a clone of this vector.
9 boolean contains(Object o)
This method returns true if this vector contains the specified element.
10 boolean containsAll(Collection<?> c)
This method returns true if this Vector contains all of the elements in the specified Collection.
11 void copyInto(Object[ ] anArray)
This method copies the components of this vector into the specified array.
12 E elementAt(int index)
This method returns the component at the specified index.
13 Enumeration<E> elements()
This method returns an enumeration of the components of this vector.
14 void ensureCapacity(int minCapacity)
This method increases the capacity of this vector, if necessary, to ensure that it can hold at least the
number of components specified by the minimum capacity argument.
15 boolean equals(Object o)
This method compares the specified Object with this Vector for equality.
16 E firstElement()
This method returns the first component (the item at index 0) of this vector.
17 E get(int index)
This method returns the element at the specified position in this Vector.
18 int hashCode()
This method returns the hash code value for this Vector.
19 int indexOf(Object o)
This method returns the index of the first occurrence of the specified element in this vector, or -1 if
this vector does not contain the element.
20 int indexOf(Object o, int index)
This method returns the index of the first occurrence of the specified element in this vector,
searching forwards from index, or returns -1 if the element is not found.
21 void insertElementAt(E obj, int index)
This method inserts the specified object as a component in this vector at the specified index.
22 boolean isEmpty()
This method tests if this vector has no components.
23 E lastElement()
This method returns the last component of the vector.
24 int lastIndexOf(Object o)
This method returns the index of the last occurrence of the specified element in this vector, or -1 if
this vector does not contain the element.
25 int lastIndexOf(Object o, int index)
This method returns the index of the last occurrence of the specified element in this vector,
searching backwards from index, or returns -1 if the element is not found.
26 E remove(int index)
This method removes the element at the specified position in this Vector.
27 boolean remove(Object o)
This method removes the first occurrence of the specified element in this Vector If the Vector does
not contain the element, it is unchanged.
28 boolean removeAll(Collection<?> c)
This method removes from this Vector all of its elements that are contained in the specified
Collection.
29 void removeAllElements()
This method removes all components from this vector and sets its size to zero.
30 boolean removeElement(Object obj)
This method removes the first occurrence of the argument from this vector.
31 void removeElementAt(int index)
This method deletes the component at the specified index.
32 protected void removeRange(int fromIndex, int toIndex)
This method removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.
33 boolean retainAll(Collection<?> c)
This method retains only the elements in this Vector that are contained in the specified Collection.
34 E set(int index, E element)
This method replaces the element at the specified position in this Vector with the specified element.
35 void setElementAt(E obj, int index)
This method sets the component at the specified index of this vector to be the specified object.
36 void setSize(int newSize)
This method sets the size of this vector.
37 int size()
This method returns the number of components in this vector.
38 List <E> subList(int fromIndex, int toIndex)
This method returns a view of the portion of this List between fromIndex, inclusive, and toIndex,
exclusive.
39 object[ ] toArray()
This method returns an array containing all of the elements in this Vector in the correct order.
40 <T> T[ ] toArray(T[ ] a)
This method returns an array containing all of the elements in this Vector in the correct order; the
runtime type of the returned array is that of the specified array.
41 String toString()
This method returns a string representation of this Vector, containing the String representation of
each element.
42 void trimToSize()
This method trims the capacity of this vector to be the vector's current size.
Example:
In a priority queue, added objects are according to their priority. By default, the priority is
determined by objects‟ natural ordering. Default priority can be overridden by
a Comparator provided at queue construction time.
PriorityQueue Features
1. PriorityQueue is an unbounded queue and grows dynamically. The default initial capacity is '11'
which can be overridden using initialCapacity parameter in appropriate constructor.
2. It does not allow NULL objects.
3. Objects added to PriorityQueue MUST be comparable.
4. The objects of the priority queue are ordered by default in natural order.
5. A Comparator can be used for custom ordering of objects in the queue.
6. The head of the priority queue is the least element based on the natural ordering or comparator
based ordering. When we poll the queue, it returns the head object from the queue.
7. If multiple objects are present of same priority the it can poll any one of them randomly.
8. PriorityQueue is not thread safe. Use PriorityBlockingQueue in concurrent environment.
9. It provides O(log(n)) time for add and poll methods.
Class constructors
Sr.No. Constructor & Description
1
PriorityQueue()
This creates a PriorityQueue with the default initial capacity (11) that orders its elements according to
their natural ordering.
2
PriorityQueue(Collection<? extends E> c)
This creates a PriorityQueue containing the elements in the specified collection.
3
PriorityQueue(int initialCapacity)
This creates a PriorityQueue with the specified initial capacity that orders its elements according to
their natural ordering.
4
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
This creates a PriorityQueue with the specified initial capacity that orders its elements according to
the specified comparator.
5
PriorityQueue(PriorityQueue<? extends E> c)
This creates a PriorityQueue containing the elements in the specified priority queue.
6
PriorityQueue(SortedSet<? extends E> c)
This creates a PriorityQueue containing the elements in the specified sorted set.
Class methods
Sr.No. Method & Description
1 boolean add(E e)
This method inserts the specified element into this priority queue.
2 void clear()
This method removes all of the elements from this priority queue.
3 Comparator<? super E> comparator()
This method returns the comparator used to order the elements in this queue, or null if this queue is
sorted according to the natural ordering of its elements.
4 boolean contains(Object o)
This method returns true if this queue contains the specified element.
5 Iterator<E> iterator()
This method returns an iterator over the elements in this queue.
6 boolean offer(E e)
This method inserts the specified element into this priority queue.
7 E peek()
This method retrieves, but does not remove, the head of this queue, or returns null if this queue is
empty.
8 E poll()
This method retrieves and removes the head of this queue, or returns null if this queue is empty.
9 boolean remove(Object o)
This method removes a single instance of the specified element from this queue, if it is present.
10 int size()
This method returns the number of elements in this collection.
11 Object[] toArray()
This method returns an array containing all of the elements in this queue.
12 <T> T[] toArray(T[] a)
This method returns an array containing all of the elements in this queue; the runtime type of the
returned array is that of the specified array.
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
1
Comparator comparator( )
Returns the invoking sorted map's comparator. If the natural ordering is used for the invoking map,
null is returned.
2
Object firstKey( )
Returns the first key in the invoking map.
3
SortedMap headMap(Object end)
Returns a sorted map for those map entries with keys that are less than end.
4
Object lastKey( )
Returns the last key in the invoking map.
5
SortedMap subMap(Object start, Object end)
Returns a map containing those entries with keys that are greater than or equal to start and less than
end.
6
SortedMap tailMap(Object start)
Returns a map containing those entries with keys that are greater than or equal to start.
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
SortedMap<Integer, String> sm =
Set s = sm.entrySet();
Iterator i = s.iterator();
// Traversing map. Note that the traversal produced sorted (by keys) output .
while (i.hasNext())
Map.Entry m = (Map.Entry)i.next();
}
}
Output: