Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
306 views

Core Java HRP

Uploaded by

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

Core Java HRP

Uploaded by

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

JAVA

A program is simply a list of unambiguous instructions meant to be followed


mechanically by a computer.
A computer is built to carry out instructions that are written in a very simple
type of language called machine language.
Each type of computer has its own machine language, and the computer
can directly execute a program only if the program is expressed in that
language.
The operating system is the basic, essential software without which a
computer would not be able to function.
A program written in a high-level language cannot be run directly on any
computer. First, it has to be translated into machine language. This
translation can be done by a program called a compiler, which translates the
program all at once.
Instead of using a compiler, you can use an interpreter, which translates it
instruction-by-instruction, as necessary.
History

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called
Green Team.
Originally designed for small, embedded systems in electronic appliances
like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling and file extension was
.gt. After that, it was called Oak and was developed as a part of the Green
project.
In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.
According to James Gosling "Java was one of the top choices along with
Silk". Since java was so unique, most of the team members preferred java.
Java is an island of Indonesia where first coffee was produced (called java
coffee).
Notice that Java is just a name not an acronym.
Java programming language was originally developed by Sun Microsystems
which was initiated by James Gosling and released in 1995 as core
component of Sun Microsystems. (which is now a subsidiary of Oracle
Corporation)

Sun released the first public implementation as Java 1.0 in 1995. It


promised Write Once, Run Anywhere (WORA), providing no-cost run-
times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open
source software under the terms of the GNU General Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code
free and open-source, aside from a small portion of code to which Sun did
not hold the copyright.

The latest release of the Java Standard Edition is Java SE 10.0.1. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for
Enterprise Applications.

Java Platform, Enterprise Edition (Java EE) is the standard in


community-driven enterprise software. Java EE is developed using the Java
Community Process, with contributions from industry experts, commercial
and open source organizations, Java User Groups, and countless
individuals. Each release integrates new features that align with industry
needs, improves application portability, and increases developer
productivity.

Java EE continues to improve API and programming models needed for


today's applications and adds features requested by our world-wide
community. This release modernizes support for many industry standards
and continues simplification of enterprise ready APIs. Enhancements
include:

Java Servlet 4.0 API with HTTP/2 support


Enhanced JSON support including a new JSON binding API
A new REST Reactive Client API
Asynchronous CDI Events
A new portable Security API
Server-Sent Events support (Client & Server-side)
Support for Java SE new capabilities (e.g. Date & Time API, Streams API, annotations
enhancements)

Java Platform, Micro Edition (Java ME) provides a robust, flexible environment for
applications running on embedded and mobile devices in the Internet of Things: micro-
controllers, sensors, gateways, mobile phones, personal digital assistants (PDAs), TV
set-top boxes, printers and more. Java ME includes flexible user interfaces, robust
security, built-in network protocols, and support for networked and offline applications
that can be downloaded dynamically. Applications based on Java ME are portable across
many devices, yet leverage each device's native capabilities.

Popular Java Editors


To write Java programs, need a text editor. There are even more sophisticated IDEs
available in the market.

Notepad: On Windows machine, use simple text editor like Notepad.

Netbeans: A Java IDE that is open-source and free, which can be downloaded from
http://www.netbeans.org/.

Eclipse: A Java IDE developed by the eclipse open-source community and can be
downloaded from http://www.eclipse.org/.

Java 1.0.2 - slow – 250 classes – lots of bugs – applet is the big thing

Java 1.1 - little faster – 500 classes – better GUI code

Java 2 version 1.2-1.4 – much faster – 2300 classes – comes in three flavours – J2SE,
J2ME, J2EE

JAVA 5 and above – faster – 3500 classes –

What is Procedure Oriented Programming Language?


In Procedural Oriented Programming Language, the stress is laid on function rather than
data. Data may be kept floating throughout the Programming. Hence by scanning the
whole program from beginning to the end and we can rectify any error caused. E.g. of
POP based language are GW-BASIC, C, etc…
Characteristics of POP
1) Emphasis is laid on functions (Logical steps).
2) Functions share global data.
3) Data values can keep floating from one function to another.
4) Uses top down approach of programming.
Drawbacks of POP
1) As Data values are global to all the functions, you may require making necessary
changes in the functions due to change in the data values.
2) It is not suitable to solve complex problems in real situations.
What is Object Oriented Programming Language?
Object Oriented Programming Language is a modular approach to programming in which
equal stress is given to data as well as methods and it allows the data be applied within
the stipulated program area. It also provides reusability features to develop productivity
logic.
Features of OOP
1. It gives equal stress on data and function.
2. It makes the program simple by dividing it into a number of objects.
3. The objects can be used as a bridge to have data flow from one function to another.
4. Data can be easily modified without any change in the function.
Advantages of OOP
1) We can extend the use of existing class through inheritance.
2) Using the concept data hiding can generate secured program.
3) We can create different modules in our project through objects.
4) Multiple instances of an object can be generated to co-exist without any interference.
5) It is highly beneficial to solve complex problems.
6) It is easy to modified and maintain software complexity.

Object Oriented programming concepts

Encapsulation and Data abstraction: Wrapping up (combing) of data and methods into
a single unit (class) is known as encapsulation. The data is not accessible to the outside
world and only those methods which are wrapping in the class can access it. This
insulation of the data from direct access by the program is called data hiding or
information hiding.

Encapsulation makes it possible for objects to be treated like ‘black boxes’, each
performing a specific task without any concern for internal implementation.

Data abstraction refers to, providing only needed information to the outside world and
hiding implementation details.

Inheritance: inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports the concept of hierarchical
classification. Inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a
new class from the existing one.
The inheritance mechanism allows the programmer to reuse a class that is almost, but
not exactly, what he wants, and to tailor the class in such a way that it does not introduce
any undesirable side effects into the rest of the classes.
Derived class known as subclass.

Polymorphism: polymorphism means ability to take more than one form. An operation
may exhibit different behaviours in different instances. The behaviour depends upon the
types of data used in the operation.
C++ supports operator overloading and function overloading.
Operator overloading is the process of making an operator to exhibit different behaviours
in different instances is known as operator overloading.
Function overloading is using a single function name to perform different types of tasks.

Dynamic Binding: In dynamic binding, the code associated with a given procedure call
is not known until the time of the call at run time. The code to be executed in response to
procedure call is decided at runtime.

Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a method in the receiving object that generates the
desired results. Message passing involves specifying the name of the object, the name of
the method and the information to be sent.

Benefits of Object Oriented Programming


OOP offers several benefits to the program designer and users.
- Better quality of software
- Lesser maintenance cost
- Greater programmer productivity
- Using inheritance, we can eliminate redundant code and extend use of existing
class.
- Data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
- It is possible to have multiple objects to exist without any interference.
- It is easy to partition the work in a project based on objects.
- Object oriented systems can be easily upgraded from small to large systems.
- Software complexity can be easily managed.

Java is:

Compiled and Interpreted: Java combines both making it a two stage system. First java
compiler translates source code into byte code. This byte code is not machine
instructions and therefore in second stage java interpreter generates machine code that
can be executed by the machine that is running java program.

Object Oriented: In Java, everything is an Object. Java can be easily extended since it
is based on the Object model. All program code and data resides in the object only.

Platform Independent, portable: Unlike many other programming languages including


C and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Thus Java compiler generates an architecture-neutral (machine neutral) object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system. Being architecture-neutral and having no
implementation dependent aspects of the specification makes Java portable.

Simple, familiar: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master. Familiar and look like a c++, it does
not support pointer and other features of c or c++.

Robust and Secure: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking. It provides
reliable code. It is designed as garbage-collected, relieving programmers from memory
management problem. It also incorporate concept of exception handling which eliminates
any risk of crashing the system.
The absence of pointer in the java ensures that program cannot access memory location
without proper authorization, no virus communicate with applet.

Distributed: Java is designed for the distributed environment of the internet. It can share
and access remotely data and program over internet make multiple programmer to work
together on a single project.
Multithreaded: With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly. Listening audio, scrolling page
and downloading can be done simultaneously.

High Performance: java architecture is designed to reduce overheads during runtime,


Java enables high performance.

Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to


adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Java differ from c and c++

Java does not support keywords goto, sizeof, typedef.


It does not contain data types, struct, union, enum.
It does not support type modifiers auto, extern, register, signed, unsigned.
It does not support pointer.
It does not support pre-processor like #define, #include, #ifdef.
In java a function with no arguments must be declared with empty parenthesis and not
with void keyword.

It does not support operator overloading.


It does not have template classes.
It does not support multiple inheritances of classes. (New feature interface in java)
It does not support global variable.
It does not use pointers.
There are no header files in java.
It does not support destructor (finalize function)

Java and Internet


Java is strongly associated with the internet because of the first application
program is written in Java was hot Java.
A web browser to run applets on the internet.
Internet users can use Java to create applet programs & run then locally using a
Java-enabled browser such as hot Java.
Java applets have made the internet a true extension of the storage system of the
local computer.
With the help of Java WWW is capable of supporting animation graphics, games
and wide rage special effects.
Java communicates with a web page through a special tag called <applet>. The
document contains the applet tag which identifies the applet and the corresponding
applet is transferred to the user computer.
The Java enabled browser on the user's computer interprets the byte code and
provide output.

import java.applet.*;
import java.awt.*;
public class HelloworldApplet extends Applet {

public void paint ( Graphics g){


g.drawString("Hello World Applet 5th - Semester", 25, 50);
}

}
Javac HelloworldApplet.java

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloworldApplet.class" width="25" height="50">

</applet>
<hr>
</html>

Appletviewer test.html

Java Program Structure

Documentation section –comment part //, /* */


Package statement
Import statement
Interface statement
Class definition
Main method class definition

Source file means file name with extension .java

public class MyFirstJavaProgram {


public static void main(String []args) {
System.out.println("Hello World");
}
}

Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:

Open notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\JAVAPROGRAM.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line

(The path variable must set).

Setting Up the Path for Windows

Assuming you have installed Java in C:\Program Files\java\jdk directory:


Right-click on 'My Computer' and select 'Properties'.

Click the 'Environment variables' button under the 'Advanced' tab.

Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your
path to read 'C:\WINDOWS\ SYSTEM32;C:\Program Files\java\jdk\bin'.

Now, type ' java MyFirstJavaProgram ' to run your program.

You will be able to see ' Hello World ' printed on the window.

A source code file with .java extension holds one class definition. A class has one or
more methods. A method is set of statements.

In java everything must be placed inside a class.

Public: every one can access it.


Class: this is a class declaration.
MyFirstJavaProgram: name of class and name of file.
Static: which declares this method as one that belongs to the entire class and not a part
of any object of the class. The interpreter uses this method before any object are
created.
Void: Return type void means no return value.
Main: name of the method
String []args: arguments to the method. This method must be given an array of strings
and the array will be called as args.
System.out.println: this says print to standard output.
Every statement must end with ;

public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.

Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.

Style used in program

Class Names - For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaProgram
Method Names - All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.

Example: public void myMethodName()


Common Programming guidelines:

 Java identifiers must start with a letter, a currency character ($), or a connecting
character such as the underscore ( _ ). Identifiers cannot start with a number.
After first character identifiers can contain any combination of letters, currency
characters, connecting characters, or numbers. For example,
o int variable1 = 10 ; //This is valid
o int 4var =10 ; // this is invalid, identifier can’t start with digit.
 Identifiers, method names, class names are case-sensitive; tar and Tar are two
different identifiers.
 You can’t use Java keywords as identifiers,
 Below table shows a list of Java keywords.

abstract boolean break byte case catch

char class const continue default do

double else extends final finally float

for goto if implements import instanceof

int interface long native new package

private protected public return short static

strictfp super switch synchronized this throw

throws transient try void volatile while

assert enum null var

A name used which refers to data stored in memory—is called a variable. Each variable
in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable. All variables are declared before they can
be used.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.

Local Variable:

public class localvariable {

public void findAge() {


int age = 7;
System.out.println(age);
}

public static void main(String[] args) {


localvariable fa = new localvariable();
fa.findAge();
}
}

A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation. X=’A’
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these
number systems for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

Summary of Primitive Data Types


The primitive data types are not objects; they do not belong to any class; they are
defined in the language itself. Wrapper class in java provides the mechanism to convert
primitive into object and object into primitive.

Primitive Type Size Minimum Maximum Wrapper


Value Value Type

char is a single 16-bit Unicode character 16-bit Unicode 0 Unicode 2^16- Character
It is used to store any character
'\u0000' 1 =65535
'\uffff'

byte - is an 8-bit signed two's complement 8-bit -128 +127 Byte


integer. it is used to save space in large
arrays, mainly in place of integers, since a
byte is four times smaller than an integer
short is a 16-bit signed two's complement 16-bit -2^15 +2^15-1 Short
integer, It can also be used to save memory as
(-32,768) (32,767)
byte data type. A short is 2 times smaller than
an integer
Default value is 0

int is a 32-bit signed two's complement integer 32-bit -2^31 +2^31-1 Integer
Integer is generally used as the default data
(- (2,147,483,647
type for integral values unless there is a
concern about memory. 2,147,483,64 )
The default value is 0 8)

long is a 64-bit signed two's complement 64-bit -2^63 +2^63-1 Long


integer
(- (9,223,372,036
This type is used when a wider range than int
is needed 9,223,372,03 ,854,775,807)
Default value is 0L 6,854,775,80
8)

float is a single-precision 32-bit IEEE 754 32-bit Approx range 1.4e-045 to Float
floating point
3.4e+038
Float is mainly used to save memory in large
arrays of floating point numbers
Default value is 0.0f

double is a double-precision 64-bit IEEE 754 64-bit Approx range 4.9e-324 to Double
floating point
1.8e+308
This datatype is generally used as the default
data type for decimal values, generally the
default choice
Default value is 0.0d

boolean datatype represents one bit of 1-bit true or false Boolean


information
There are only two possible values: true and
false
This datatype is used for simple flags that
track true/false conditions
Default value is false
Example: boolean one = true

public class DataTypeExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
byte a = 120;
short b = 350;
int c = 56000;
long d = 565666667;
float e = (float)3233323.44;
double f = 32423443243.4444444;
boolean flag = true;
char ch1=88;
char ch2='A';
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
System.out.println(flag);
System.out.println(ch1);
System.out.println(ch2);
}
}

What is the output?

public class CastingExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
long y = 40002;
short x = (short) y;
System.out.println(x);
System.out.println(y);
}

Wrapper Classes

Java is an object-oriented language and as said everything in java is an object. What about the
primitives datatypes? As a solution to this problem, Java allows you to include the primitive
datatypes in the family of objects by using what are called wrapper classes.

Wrapper classes wrap the primitive datatypes into respective objects.

There is a wrapper class for every primitive date type in Java. This class encapsulates a single
value for the primitive data type. For instance the wrapper class for int is Integer, for float is Float,
and so on.

Wrapper classes are a part of Java’s standard default library java.lang

The wrapper classes in the Java API serve two primary purposes:

 To provide a mechanism to “wrap” primitive values in an object so that the primitives can be
included in activities reserved for objects, like as being added to Collections, or returned from a
method with an object return value.
 To provide an assortment of utility functions for primitives. Most of these functions are related to
various conversions: converting primitives to and from String objects, and converting primitives
and String objects to and from different bases (or radix), such as binary, octal, and
hexadecimal.
Wrapper Class functions / methods
The wrapper class methods that are static in nature can be directly accessed as –

Class_name.method_name (arguments) e.g. Boolean.toString(b);

Boolean Wrapper class

Function Description
booleanValue( ) Convert Boolean object to boolean primitive datatype.
valueOf( ) Convert String to Boolean object.
toString( ) Convert Boolean object to String.

Byte Wrapper class

Function Description
parseByte( ) Converts String to byte primitive datatype.
valueOf( ) Converts String to Byte object.

toString( ) Converts byte primitive to String object.

Short Wrapper class

Function Description
parseShort( ) Converts String to short primitive datatype.
valueOf( ) Converts String to Short object.
toString( ) Converts short primitive to String object.

Integer Wrapper class


Function Description
parseInt( ) Converts String to int primitive datatype.
valueOf( ) Converts String to Integer object.
toString( ) Converts int primitive to String object.

Long Wrapper class


Function Description

parseLong( ) Converts String to long primitive datatype.

valueOf( ) Converts String to Long object.

toString( ) Converts long primitive to String object.

Float Wrapper class


Function Description
parseFloat( ) Converts String to float primitive datatype.
valueOf( ) Converts String to Integer object.
toString( ) Converts int primitive to String object.

Double Wrapper class


Function Description

parseDouble( ) Converts String to double primitive datatype.


valueOf( ) Converts String to Double object.
toString( ) Converts double primitive to String object.

public class WrapperExample1 {

public static void main(String[] args) {


//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//auto boxing, now compiler will write
Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}

public class WrapperExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue()
internally

System.out.println(a+" "+i+" "+j);

Integer x = 5; // boxes int to an Integer object


x = x + 10; // unboxes the Integer to a int
System.out.println(x);

public class WrapperExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
//primitive data type to Object
Integer I1 = new Integer(12);
Float F1 = 3.45f; //boxing
System.out.println("primitive data type to Object " + I1 + " ," +
F1);

// Object to primitive
int i= I1.intValue();
System.out.println("Object to primitive "+i);
System.out.println("Object to primitive "+F1.floatValue());

//String to Object
Integer I2 = new Integer("1234");

//Object to String
String s = I2.toString();
System.out.println("Object to String "+s);

//String to primitive

String s1 ="3.56";

float f = Float.parseFloat(s1);
System.out.println("String to primitive using parse method : "+
f);

// primitive to string

String s2 = Double.toString(35.6);
System.out.println("Primitive to String using toString method : "+
s2);

// primitive to String
String s3 = String.valueOf(234);
String s4 = Integer.toString(234);
System.out.println("Primitive to String using valueOf method : "+
s3);
System.out.println("Primitive to String using toString method : "+
s4+" length "+s4.length());

Float fff = 32.5f Java think anything with a floating point is


double, unless we use f.
Convert string 8 into integer value.
String num = “8”;
Int z = Integer.parseInt(num);
Character Wrapper Class

To use objects instead of primitive data types, Java provides wrapper class
Character for primitive data type char.

isLetter() Determines whether the specified char value is a letter.

isDigit() Determines whether the specified char value is a digit.

isWhitespace() Determines whether the specified char value is white


space.

isUpperCase() Determines whether the specified char value is uppercase.

isLowerCase() Determines whether the specified char value is lowercase.

toUpperCase() Returns the uppercase form of the specified char value.


toLowerCase() Returns the lowercase form of the specified char value.

toString() Returns a String object representing the specified character value


that is, a one-character string.
public class CharArrayEx {

public static void main(String[] args) {


// TODO Auto-generated method stub
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
for(int i=0;i<charArray.length;i++) {
System.out.print(charArray[i]);
}
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));

System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));

System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));

System.out.println( Character.isUpperCase('c'));
System.out.println( Character.isUpperCase('C'));

System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));

System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C'));

System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}

Java – Strings Class

Strings are a sequence of characters. In Java programming language,


strings are treated as objects. The Java platform provides the String class to
create and manipulate strings.
Creating the string as a literal: String fname = “Parth”
A String Object can be created using a new keyword –
String str = new String (“Welcome”);

Compiler creates a String object with its value; create String objects by
using the new keyword and a constructor.
The String class is immutable; so that once it is created a String object
cannot be changed. If there is a necessity to make a lot of modifications to
Strings of characters, then String Buffer & String Builder Classes are used.

Strings, objects of type StringBuffer can be modified over and over again
without leaving behind a lot of new unused objects.

We can say that, the main difference between String and StringBuffer is
String is immutable while StringBuffer is mutable means you can modify a
StringBuffer object once you created it without creating any new object. This
mutable property makes StringBuffer an ideal choice for dealing with Strings
in Java.
public StringBuffer append(String s)
Updates the value of the object that invoked the method.

public StringBuffer reverse()


The method reverses the value of the StringBuffer object that invoked the
method.

public delete(int start, int end)


Deletes the string starting from the start index (inclusive) until the end index
(exclusive).

public insert(int offset, String str)


This method inserts a string str at the position mentioned by the offset.
replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with
characters in the specified String.

public class StringBufferExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer("JavaScript is the
programming language");
sb.append(" of HTML and the Web.");
System.out.println(sb);
StringBuffer buffer = new StringBuffer("Hello World");
buffer.reverse();
System.out.println(buffer);
sb.delete(3,7);
System.out.println(sb);
sb.insert(3,"aScr");
System.out.println(sb);
sb.insert(59, "hello");
System.out.println(sb);
sb.replace(39, 59, "of HTML and the script programming.");
System.out.println(sb);
}
}

Every string object contains a function named length that computes the
number of characters in that string. Note that this function has no parameter.

S1.length()
S1.concate(String s2)

s1.substring(N,M): where N and M are integers, returns a value of type


String. The returned value consists of the characters in s1 in positions N,
N+1,. . . , M-1. Note that the character in position M is not included. The
returned value is called a substring of s1.

s1.indexOf(s2) returns an integer. If s2 occurs as a substring of s1, then the


returned value is the starting position of that substring. Otherwise, the
returned value is -1. You can also use s1.indexOf(ch) to search for a
particular character, ch, in s1. To find the first occurrence of x at or after
position N, you can use s1.indexOf(x,N).
s1.compareTo(s2) is an integer-valued function that compares the two
strings. If the strings are equal, the value returned is zero. If s1 is less than
s2, the value returned is a number less than zero, and if s1 is greater than
s2, the value returned is some number greater than zero.

s1.toUpperCase() is a String-valued function that returns a new string that


is equal to s1, except that any lower case letters in s1 have been converted
to upper case. For example, "Cat".toUpperCase() is the string "CAT". There
is also a function s1.toLowerCase().

s1.trim() is a String-valued function that returns a new string that is equal to


s1 except that any non-printing characters such as spaces and tabs have
been trimmed from the beginning and from the end of the string. Thus, if s1
has the value "fred ", then s1.trim() is the string "fred".

char charAt(int index) Returns the character at the specified index.

public class OtherStringFuncExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
String str = new String("Every string object
contains a function named length");
int len = str.length();
String sustr = str.substring(6,12);
int ind = str.indexOf("o");
System.out.println(len);
System.out.println(sustr);
System.out.println(ind);
ind = str.indexOf("o",14);
System.out.println(ind);
String s1,s2, s3;
s1 = "Hello";
s2 = "Hello";
int cmp = s1.compareTo(s2);
System.out.println(cmp);
System.out.println(s1.toUpperCase());
System.out.println(s1.toLowerCase());
s3 = " Times of India ";
System.out.println(s3.trim());
System.out.println(s2.concat(s3));
System.out.println(str.charAt(6));
}
}

For the functions s1.toUpperCase(), s1.toLowerCase(), and s1.trim(), note


that the value of s1 is not modified. Instead a new string is created and
returned as the value of the function.
The returned value could be used, for example, in an assignment statement
such as “smallLetters = s1.toLowerCase();”. To change the value of s1, you
could use an assignment “s1 = s1.toLowerCase();”.
Here is another extremely useful fact about strings: You can use the plus
operator, +, to concatenate two strings.
-------------------------------------------------------------------------------

Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Addition +, Subtraction -, Multiplication *, Division / , Modulus (remainder) %, ++
increment, -- decrement

Relational Operators
== (equal to) , != (not equal to) , > (greater than)
< (less than) , >= (greater than or equal to)
<= (less than or equal to)

Bitwise Operators
& (bitwise and), | (bitwise or) , ^ (bitwise XOR)
~ (bitwise compliment) , << (left shift)
>> (right shift) , >>> (zero fill right shift)

Logical Operators
&& (logical and) , || (logical or) , ! (logical not)

Assignment Operators
=, += a+=c means a=a+c, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=

Precedence of Java Operators


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator:
Category Operator Associativity
Postfix () [] . (dot operator) Left toright
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= Right to left
|=

Control Structure

There may be a situation when you need to execute a block of code several number of
times. A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the programming
languages:

Loop Type Description


while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
for loop Execute a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
do...while loop Like a while statement, except that it tests the condition
at the end of the loop body.

Control Statement Description


break statement Terminates the loop or switch statement and transfers
execution to the statement immediately following the
loop or switch.
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.

int no = 1;
while (no) { } is wrong

public class BooleanExampleLoop{

public static void main(String[] args) {


// Loop without comparision operator
int no = 1;
boolean nvalue = true;
while (no){
no = no + 1;
if (no > 10) {
break;
}
System.out.println("number :" + no);
}
}
}

BooleanExampleLoop.java:7: error: incompatible types: int cannot be converted to


boolean
while (no){
^
1 error

A: A Boolean and an integer are not compatible types in Java. The result of a conditional
test must be a Boolean; the only variable you can directly test (without using a
comparison operator) is a Boolean. For example, you can say:
Boolean nvalue = true;
while (nvalue) { } is true.

Java – Decision Making

Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:

Java programming language provides following types of decision making statements.

Statement Description
if statement An if statement consists of a boolean expression
followed by one or more statements.
if...else statement if statement can be followed by an optional else
statement, which executes when the boolean
expression is false.

nested if statements You can use one if or else if statement inside


another if or else if statement(s).
switch statement A switch statement allows a variable to be tested for
equality against a list of values.

What is the output?

public class OutputExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
OutputExample o = new OutputExample();
o.go();
}
void go() {
int y = 7;
for(int x=1;x<8;x++){
y++;
if(x>4){
System.out.println(++y);
}
if(y>14){
System.out.println(x);
}
}
}
}

public class Counter {


int myCount = 0;
static int ourCount = 0;
void increment(){
myCount++;
ourCount++;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Counter counter1 = new Counter();
Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
counter2.increment();
System.out.println("Counter1 : " + counter1.myCount + " " + counter1.ourCount);
System.out.println("Counter2 : " + counter2.myCount + " " + counter2.ourCount);
}

// Prime Number

public class PrimeNumber {

public static void main(String []args) {


// TODO Auto-generated method stub

int num = 30;


boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for non prime number
if(num % i == 0)
{
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");

// Program taking input from standard input

import java.util.Scanner;

public class scannerprog1 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);

sc.close();
}

import java.util.*;
public class SwitchExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

System.out.print("Enter Month Number :");


Scanner s = new Scanner(System.in);
int a = s.nextInt();

switch(a)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("No of days is 31");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("No of days is 30");
break;
case 2:
System.out.println("No of days is 28 or 29");
break;

default:
System.out.println("Enter valid month");

}
s.close();
}

Arrays: an array is a group of contiguous or related data items that share a common name.
Array can be of any variable type.
It is often more useful to think of an array as a collection of variables of the same type.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way. Style come from c++

Example: double[] myList;

Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];

Following statement declares an array variable, myList, creates an array of 10 elements of


double type and assigns its reference to myList:
double[] myList = new double[10];

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

Arrays are always objects, whether they are declared to hold primitives or object
reference.

Once you have declared an array, you can’t put anything in it except the things that are of the
declared array type. You can’t stick a double into an int array type. But you can put a Byte into an
int array type. Byte will always fit into an int sized.

import java.util.*;
public class IntArrayForLoop {

public static void main(String[] args) {


// TODO Auto-generated method stub

int number[];
number = new int[5];
// Enter the array elements
Scanner sc=new Scanner(System.in);

System.out.println("Enter Array Element");


for (int i = 0; i < 5; i++) {
number[i]=sc.nextInt();
}

// Print all elements

for (int i = 4; i >= 0; i--) {


System.out.println(number[i]);
}
sc.close();
}

--------------------------------
// Convert number amount into word amount

import java.util.*;

public class NumberToWordConverter {


public void ConvertStr(int n) {
String[] twodigit = { "", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve",
"Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen",
"Eighteen", "Nineteen" };

String[] tens = {
"", // 0
"", // 1
"Twenty", // 2
"Thirty", // 3
"Forty", // 4
"Fifty", // 5
"Sixty", // 6
"Seventy", // 7
"Eighty", // 8
"Ninety" // 9
};

if (n < 0) {
System.out.println("Amount is Negative");
}

else if (n < 20) {


System.out.println("Amount is :" + twodigit[n]);
}

else if (n < 100) {


int p = n/10;
int r = n%10;
System.out.println("Amount is :" +tens[p] + " " +
twodigit[r]);
}
else if (n < 1000) {
int p = n/100;
int r = n%100;
if (r < 20 ) {

System.out.println("Amount is :" +
twodigit[p] + " hundred " + twodigit[r]);
}
else {
int p1 = r/10;
int r1 = r%10;
System.out.println("Amount is :" +
twodigit[p] + " hundred " + tens[p1] + " " + twodigit[r1]);
}
}

} // end of function
public static void main(String[] args) {
// TODO Auto-generated method stub
int no;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to convert into word format
:");
no =sc.nextInt();
NumberToWordConverter fa = new NumberToWordConverter();
fa.ConvertStr(no);
}

}
--------------------------------------------------------------
Array – Object
import java.lang.String;
public class ReferenceArrayExample {
String title;
String author;
public static void main(String[] args) {
// TODO Auto-generated method stub
ReferenceArrayExample[] myBooks = new
ReferenceArrayExample[3];
myBooks[0] = new ReferenceArrayExample();
myBooks[1] = new ReferenceArrayExample();
myBooks[2] = new ReferenceArrayExample();
int x = 0;
myBooks[0].title = "The Grapes of Java";
myBooks[1].title = "The Java Gatsby";
myBooks[2].title = "The Java Cookbook";
myBooks[0].author = "bob";
myBooks[1].author = "sue";
myBooks[2].author = "ian";
while (x < 3) {
System.out.print(myBooks[x].title);
System.out.print(" by ");
System.out.println(myBooks[x].author);
x = x + 1;
}
}
}

// Student Array
import java.util.*;
public class StudentArray {
int rollno;
String sname;
int semester;
String division;
void studentdata() {
Scanner sc = new Scanner(System.in);

rollno = sc.nextInt();
sname = sc.next();
semester = sc.nextInt();
division = sc.next();

}
void Display() {
System.out.println(rollno);
System.out.println(sname);
System.out.println(semester);
System.out.println(division);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentArray sa[] = new StudentArray[3];

for(int i=0;i<3;i++) {
sa[i] = new StudentArray();
System.out.println("Enter " +i +" Student Details");
sa[i].studentdata();
}

for(int i=0;i<3;i++) {
System.out.println("Print " +i +" Student Details");
sa[i].Display();
}
}
}

Two Dimensional Array


The definition of an array is: a numbered sequence of items, which are all of
the same type.
In java there is no concept of two dimensional array. A two dimensional
array in java is just an array of array. If the data is linear we can use the One
Dimensional Array but to work with multi-level data we have to use Multi-
Dimensional Array.

Data_Type[][] Array_Name;

Initialization of Two Dimensional Array in Java


We can initialize the Two Dimensional Array in these ways
First Approach
Declaring and Creating an Array
int[][] Student_Marks = new int[2][3];

Second Approach
int[][] Student_Marks={{10, 20, 30},{15, 25, 35},{22, 44, 66},{33, 55, 77}};
Here, we did not mention the row size and column size but the compiler is
intelligent enough to calculate the size by checking the number of elements
inside the row and column. 4 X 3

// Two Dimensional Array in Java Example

public class TwoDimesionalArray {

public static void main(String[] args) {


// TODO Auto-generated method stub
int[][] a = { {15, 25, 35}, {45, 55, 65} };
int[][] b = {{12, 22, 32}, {55, 25, 85} };
int[][] Sum = new int[2][3];
int rows, columns;
for(rows = 0; rows < a.length; rows++) {
for(columns = 0; columns < a[0].length; columns++) {
Sum[rows][columns] = a[rows][columns] +
b[rows][columns];
}
System.out.println(a.length);
System.out.println(a[0].length);
}
System.out.println("Sum Of those Two Arrays are: ");
for(rows = 0; rows < a.length; rows++) {
for(columns = 0; columns < a[0].length; columns++) {
System.out.format("%d \t", Sum[rows][columns]);
}
System.out.println("");
}

Condition inside the for loops (rows < a.length) will ensure the compiler, not to exceed
the array row limit and (rows < a[0].length) will ensure the compiler not to exceed the
array column limit.

// another method to display two dimensional array


public class TwoDimensionalArray1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a[][] = new int[3][];

a[0]= new int[4];


a[1]= new int[3];
a[2]= new int[5];

int k=1;

for(int i=0; i<3;++i)


{
for(int j=0; j<a[i].length;++j)
{
a[i][j] = k++;
}
}

//print the array

for(int i=0; i<3;++i)


{
System.out.println();
for(int j=0; j<a[i].length;++j)
{
System.out.print(a[i][j] +"\t");
}
}
}

import java.util.*;
public class MultiplicationMatrix {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];

System.out.println("Enter matrix A");


for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}

System.out.println("Enter matrix B");


for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}

// Multiplication
int[][] c = new int[rowsInA][columnsInB];

for (int i = 0; i < rowsInA; i++) {


for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("Product of A and B is");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}

}// End of Main


}// End of Class

A B
123 123
456 456
789

Mathematical Functions

To get the absolute value of a number, or round a number, or find the larger of two
numbers, to print number with exactly two decimal places, or you might want to put
commas into your large numbers to make them easier to read, to print dates In a variety
of ways, parsing a String Into a number Or turning a number into a String

public class MathExample {

public static void main(String[] args) {


// Math Function
Integer x = 5;
Integer y = -5;
double dd = -100;
float ff = -90;

/* The method converts the value of the Number Object into the primitive data type. Here
is a separate method for each primitive data type.
byte byteValue()
short shortValue()
int int Value()
long longValue()
float floatValue()
double doubleValue()*/

System.out.println(x.longValue()); // Returns long primitive data type


System.out.println(x.doubleValue());// Returns double primitive data type

// Returns absolute value |a|


System.out.println(Math.abs(y));
System.out.println(Math.abs(dd));
System.out.println(Math.abs(ff));

/* However, two different types cannot be compared, both the argument and the Number
object invoking the method should be of the same type.

public int compareTo( NumberSubClass referenceName )

referenceName -- OBJECT - This could be a Byte, Double, Integer, Float, Long, or


Short.

Return Value
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
If the Integer is greater than the argument then 1 is returned. */

Float xx = 34.23f;
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8));
System.out.println(xx.compareTo(8.2f));

Double obj1 = new Double("8.5");


Double obj2 = new Double("11.50");
int retval = obj1.compareTo(obj2);
System.out.println(retval);

/* The method determines whether the Number object that invokes the method is equal
to the object that is passed as an argument.

public boolean equals(Object o)

The method returns True if the argument is not null and is an object of the same type and
with the same numeric value. */

Integer a = 5;
Integer b = 10;
Integer c = 5;
Short d = 5;
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals(d));

/ * The valueOf method returns the relevant Number Object holding the value of the
argument passed. The argument can be a primitive data type, String, etc.

Integer valueOf(int i)
Integer valueOf(String s)
Integer valueOf(String s, int radix) */

Integer x1 =Integer.valueOf(9);
Double c1 = Double.valueOf(5);
Float a1 = Float.valueOf("80");
Integer b1 = Integer.valueOf("444",8);
System.out.println(x1);
System.out.println(c1);
System.out.println(a1);
System.out.println(b1);

// The method is used to get a String object representing the value of the Number Object.
If the method takes a primitive data type as an argument, then the String object
representing the primitive data type value is returned.

String s1;
s1 = a.toString();
System.out.println(s1);
s1 = Integer.toString(55);
System.out.println(s1);

//This method is used to get the primitive data type of a certain String.

int x2 =Integer.parseInt("9");
double c2 = Double.parseDouble("5");
int b2 = Integer.parseInt("444",16);
System.out.println(x2);
System.out.println(c2);
System.out.println(b2);
// CEIL - This method returns the smallest integer that is greater than or equal to the
argument. Returned as a double
// FLOOR - The method floor gives the largest integer that is less than or equal to the
argument.

double d2 = 100.675;
float f2 = -90.500f;
float f4 = 90.500f;
System.out.println(Math.ceil(d2));
System.out.println(Math.ceil(f2));
System.out.println(Math.floor(d2));
System.out.println(Math.floor(f2));
/* The method round returns the closest long or int, as given by the methods return type.
long round(double d)
int round(float f) */

long d3 = Math.round(d2);
int f3 = Math.round(f2);
int f5 = Math.round(f4);
System.out.println(d3);
System.out.println(f3);
System.out.println(f5);

Min() method gives the smaller of the two arguments. The argument can be int, float,
long, double.
Max() method gives the maximum of the two arguments. The argument can be int, float,
long, double.
double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)

System.out.println(Math.min(12.123, 12.456));
System.out.println(Math.min(23.12, 23.0));
System.out.println(Math.max(12.123, 12.456));
System.out.println(Math.max(23.12, 23.0));

Exp() method returns the base of the natural logarithms, e, to the power of the argument.
double exp(double d)
Log() method returns the natural logarithm of the argument.
double log(double d)
Pow() method returns the value of the first argument raised to the power of the second
argument.
double pow(double base, double exponent)

System.out.printf("The value of e is %.4f%n", Math.E);


System.out.printf("The value of e is %.4f%n", Math.PI);

System.out.printf("Exp(%.3f) is %.3f and log is %.3f %n", x.doubleValue(),


Math.exp(x.doubleValue()), Math.log(x.doubleValue()));

double d5 = Math.pow(x.doubleValue(), 2.0);


System.out.println(d5);

Sqrt() method returns the square root of the argument.


double sqrt(double d)

double d6 = Math.sqrt(4.0);
System.out.println(d6);
Sin() method returns the sine of the specified double value.
double sin(double d)

double degrees = 45.0;


double radians = Math.toRadians(degrees);
System.out.format("The value of pi is %.4f%n", Math.PI);
System.out.format("The sine of %.1f degrees is %.4f%n", degrees,
Math.sin(radians));

Cos() method returns the cosine of the specified double value.


double cos(double d)
Tan() method returns the tangent of the specified double value.
double tan(double d)
Asin() method returns the arcsine of the specified double value.
double asin(double d)
Acos() method returns the arccosine of the specified double value.
double acos(double d)
Atan() method returns the arctangent of the specified double value.
double atan(double d)

Random() method is used to generate a random number between 0.0 and 1.0. The range
is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic
operations.
double random()
This is a default method and accepts no parameter.
This method returns a double.

System.out.println( Math.random() );

}
-------------------------------
public class PhraseOMatic {

public PhraseOMatic() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {


String[] wordListOne = {"24/7" , "multiTiar" , "30,OOO foot", "B-
to-B" , "win-win" , "frontend", "web- based" , "pervasive", "smart",
"sixsigma", "critical-path" , "dynamic"};
String[] wordListTwo = {"empowered", "sticky", "value-added.",
"oriented", "centric", "distributed", "clustered", "branded", "outaide-the-
box", "positioned" , "networked", " focused" , "leveraged", "aligned",
"targeted", "shared" , "cooperative", "accelerated"};
String[] wordListThree = {"process", "tippingpoint", "solution",
"architecture", "core competency" , "strategy", "mindshare", "portal" ,
"apace" , "vision", "paradigm", "mission"};
// find out how many words are in list

int OneLength = wordListOne.length;


int TwoLength = wordListTwo.length;
int ThreeLength = wordListThree.length;
System.out.println(OneLength + " " + TwoLength + " "+
ThreeLength);

// Generate three random numbers

int rand1 = (int) (Math.random() * OneLength);


int rand2 = (int) (Math.random() * TwoLength);
int rand3 = (int) (Math.random() * ThreeLength);

System.out.println(rand1 + " " + rand2 + " "+ rand3);


// generate phrase

String phrase1 = wordListOne[rand1] + " " + wordListTwo[rand2] + "


" + wordListThree[rand3];
System.out.println(" We Need Phrase : " + phrase1);
}

public class TimeComputationExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
long startTime; // Starting time of program, in
milliseconds.
long endTime; // Time when computations are done, in
milliseconds.
double time; // Time difference, in seconds.
startTime = System.currentTimeMillis();
double width, height, hypotenuse; // sides of a triangle
width = 42.0;
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has
hypotenuse ");
System.out.println(hypotenuse);
System.out.println("\nMathematically, sin(x)*sin(x) + "
+ "cos(x)*cos(x) - 1 should be 0.");
System.out.println("Let’s check this for x = 1:");
System.out.print(" sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
System.out.println( Math.sin(1)*Math.sin(1)
+ Math.cos(1)*Math.cos(1) - 1 );
System.out.println("(There can be round-off errors when"
+ " computing with real numbers!)");
System.out.print("\nHere is a random number: ");
System.out.println( Math.random() );
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.print("\nRun time in seconds was: ");
System.out.println(time);
}

The java.io package includes a PrintStream class that has two formatting
methods printf and format methods that you can use to replace print and
println.

The format string contains plain text as well as format specifiers, which are
special characters that format the arguments of Object.

Format specifiers begin with a percent sign (%) and end with a converter.
The converter is a character indicating the type of argument to be formatted.
In between the percent sign (%) and the converter you can have optional
flags and specifiers.
There are various converters, flags, and specifiers, which are documented
in java.util.Formatter

Example - The %d specifies that the single variable is a decimal integer.


The %n is a platform-independent newline character.

The printf and format methods are overloaded.

The following table lists some of the converters and flags that are used in
the sample program, TestFormat.java.

Converters and Flags Used in TestFormat.java


Converter Flag Explanation
d A decimal integer.
f A float.
A new line character appropriate to the platform running the
n
application. You should always use %n, rather than \n.
tB A date & time conversion—locale-specific full name of month.
A date & time conversion—2-digit day of month. td has
td, te
leading zeroes as needed, te does not.
ty, tY A date & time conversion—ty = 2-digit year, tY = 4-digit year.
tl A date & time conversion—hour in 12-hour clock.
A date & time conversion—minutes in 2 digits, with leading
tM
zeroes as necessary.
A date & time conversion—locale-specific am/pm (lower
tp
case).
A date & time conversion—months in 2 digits, with leading
tm
zeroes as necessary.
tD A date & time conversion—date as %tm%td%ty
08 Eight characters in width, with leading zeroes as necessary.
+ Includes sign, whether positive or negative.
, Includes locale-specific grouping characters.
- Left-justified..
.3 Three places after decimal point.
Ten characters in width, right justified, with three places after
10.3
decimal point.

import java.util.Calendar;
//import java.util.Locale;

public class TestFormat {

public static void main(String[] args) {


long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"

double pi = Math.PI;

System.out.format("%f%n", pi); // --> "3.141593"


System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"

Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> " July 05, 2018"

System.out.format("%tl:%tM %tp%n", c, c, c); // --> "11:28 am"

System.out.format("%tD%n", c); // --> "07/05/18"


}
}

-------------------------------------------------------
To initialize the instance variables of all objects individually, does not
promote data hiding and it would be inconvenient if the number of objects is
very large.
A better solution of this problem is to initialize values to the object at a time
of its creation in the same way as we initialize values to the variable of
primitive data types.
Constructor makes an object to initialize itself at the time of its creation
without the need to make separate call to the instance method.

What is a Constructor?
A constructor is similar to a method (but not actually a method) that is
invoked automatically when an object is instantiated.
Java compiler distinguishes between a method and a constructor by its
name and return type. In Java, a constructor has same name as that of the
class, and doesn’t return any value.

class Test {
Test() {
// constructor body
}
}

Here, Test() is a constructor; it has same name as that of the class and
doesn’t have a return type.

class Test {
void Test() {
// method body
}
}
Here, Test() has same name as that of the class. However, it has a return
type void. Hence, it’s a method not a constructor.
No-Argument Constructor
public class ConstructorExample {
int x;
public ConstructorExample() {
// TODO Auto-generated constructor stub public or private no
change
System.out.println("Constructor Called");
x = 5; // if int x = 5 means it’s a local variable and output of x =0

public static void main(String[] args) {


// TODO Auto-generated method stub
ConstructorExample con = new ConstructorExample();
System.out.println("Value of x = " + con.x);
}

}
When you run the program, the output will be:
Constructor Called
Value of x = 5

Here, ConstructorExample () constructor is called when con object is


instantiated.
A constructor may or may not accept arguments.

If a Java constructor does not accept any parameters, it is a no-argument


constructor.

Notice that the access modifier of ConstructorExample () constructor is


private.
This is because the object is instantiated from within the same class. Hence,
it can access the constructor.
However, if the object was created outside of the class, you have to declare
the constructor public to access it.

Default Constructor

If you do not create constructors yourself, the Java compiler will


automatically create a no-argument constructor during run-time. This
constructor is known as default constructor. The default constructor
initializes any uninitialized instance variables.
Example: Default Constructor
class DefaultConstructorExample {
int a;
boolean b;
public static void main(String[] args) {
DefaultConstructorExample obj = new DefaultConstructorExample();
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

The above program is equivalent to:

class DefaultConstructor {

int a;
boolean b;

private DefaultConstructor() {
a = 0;
b = false;
}

public static void main(String[] args) {

DefaultConstructor obj = new DefaultConstructor();

System.out.println("a = " + obj.a);


System.out.println("b = " + obj.b);
}
}
When you run the program, the output will be:
a=0
b = false

When we do not create a default constructor, Java compiler inserts the


default constructor into the code on our behalf. You will not see the default
constructor in your source code (the .java file) as it is inserted during
compilation and present in the bytecode (.class file).

However this is not always true. See the example below:


class Example{
Example(int i, int j){
System.out.print("parameterized constructor");
}
Example(int i, int j, int k){
System.out.print("parameterized constructor");
}
public static void main(String args[]){
Example obj = new Example();
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor Example() is undefined. The program throw compilation
error because the statement Example obj = new Example(); is trying to
invoke the no-arg constructor (no argument constructor) which we don’t
have in our program. You don’t get this error if you remove the
parameterized constructors from the above code. This is because if you do
not have any constructor in your class, Java compiler inserts default
constructor into your code on your behalf however if you implement any
constructor then you no longer receive a default constructor.
Parameterized Constructor
A constructor may also accept parameters. It's syntax is:
accessModifier ClassName(arg1, arg2, ..., argn) {
// constructor body
}

public ConstructorExample() {
// TODO Auto-generated constructor stub
System.out.println("Constructor Called");
x = 5;
}
public ConstructorExample(int x1) {
// TODO Auto-generated constructor stub
System.out.println("Constructor one argument Called");
y = x1;
}
public ConstructorExample(int x2, int x3) {
// TODO Auto-generated constructor stub
System.out.println("Constructor two argument Called");
y = x2;
z = x3;
}
public ConstructorExample(int x2, int x3, String s1) {
// TODO Auto-generated constructor stub
System.out.println("Constructor three argument Called");
y = x2;
z = x3;
s = s1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorExample con = new ConstructorExample();
System.out.println("Value of x = " + con.x);
ConstructorExample con1 = new ConstructorExample(3);
System.out.println("Value of y = " + con1.y);
ConstructorExample con2 = new ConstructorExample(7,8);
System.out.println("Value of y = " + con2.y + " and Value of z = "
+ con2.z);
ConstructorExample con3 = new
ConstructorExample(9,10,"Hello");
System.out.println("Value of y = " + con3.y + " and Value of z = "
+ con3.z + " value of s =" + con3.s);
}
}

Constructor Called
Value of x = 5
Constructor one argument Called
Value of y = 3
Constructor two arguments Called
Value of y = 7 and Value of z = 8
Constructor three arguments Called
Value of y = 9 and Value of z = 10 value of s =Hello

--------------------------------------------------------------------

Private Constructor:

If a method is private, it means that it cannot be accessed from any class


other than itself. This is the access control mechanism provided by Java.
When it is used appropriately, it can produce security and functionality.
Constructors can also be declared as private.
Why we need a private constructor since it is only accessible from its own
class?
When a class needs to prevent the caller from creating objects, Private
constructors are suitable. Objects can be constructed only internally.

One application is in the singleton design pattern. The policy is that only one
object of that class is supposed to exist, so no other class than itself can
access the constructor. This ensures the single instance existence of the
class.

public class PrivateConstructorExample {


static int i = 0;
private PrivateConstructorExample(){
i = i + 1;
System.out.println("Instance created - " +i);
}

public static PrivateConstructorExample display(){


PrivateConstructorExample p1 = new
PrivateConstructorExample();
return(p1);
}
public static void main(String[] args) {
display(); // 1st instance
display(); // 2nd instance
//PrivateConstructorExample PCE = new
PrivateConstructorExample();
//PCE.display();
}
}
--------------------------------------------------------------------------------
This Key word
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 clarity
between formal parameter and member of the class)
To differentiate between formal parameter and data member of the class,
the data member of the class must be preceded by "this".
"this" keyword is always pointing to current class (scope is within the
class) features.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
Rollno = rollno; //The assignment to the variable has no
effect
Name = name;
Fee = fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
public class ThiskwdExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}

}
Output :
0 null 0.0
0 null 0.0

In the below example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}

Public class TestThis2{


public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

If local variables(formal arguments) and instance variables are different,


there is no need to use this keyword like in the following program:

class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.

class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
Public class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}

Calling default constructor from parameterized constructor:


class A{
A(){
System.out.println("hello a");
}
A(int x){
this();
System.out.println(x);
}
}
Public class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}

Calling parameterized constructor from default constructor:


class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
Public class TestThis6{
public static void main(String args[]){
A a=new A();
}
}

class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}

Constructors Overloading in Java


Similar like method overloading, you can also overload constructors if two or more
constructors are different in parameters. For example:
class Company {
String domainName;
public Company(){
this.domainName = "default";
}
public Company(String domainName){
this.domainName = domainName;
}
public void getName(){
System.out.println(this.domainName);
}
public static void main(String[] args) {
Company defaultObj = new Company();
Company amaObj = new Company("amazon.com");
defaultObj.getName();
amaobject.getName();
}
}
When you run the program, the output will be:
default
amazon.com

Important notes
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
A Java constructor name must exactly match with the class name (including case).
A Java constructor must not have a return type.
If a class doesn't have a constructor, Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with
default values. For example: int variable will be initialized to 0
Constructors cannot be abstract or static or final.
Constructor can be overloaded but cannot be overridden.

Copy Constructor –
Sometimes a programmer wants to create an exact but separate copy of an existing
object so that any changes to the copy should not alter the original or vice versa. This is
made possible by using the copy constructor. A copy constructor is a constructor that
creates a new object that is using an existing object of the same class and initializes
each instance variable of newly created object with corresponding instance variables of
the existing object passed as argument. This constructor takes a single argument whose
type is that of the class containing the constructor.
Program Example of Copy Constructor:
Let us consider a program in which we create a copy of an existing object.
First we create a class Rectangle in which we declare the copy constructor to initialize
length and breadth:

class Rectangle
{
int length;
int breadth;
//constructor to initialize length and breadth of rectangle
Rectangle(int l, int b)
{
length=l;
breadth=b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("copy constructor invoked");
length=obj.length;
breadth=obj.breadth;
}
//method to calculate area of rectangle
int area()
{
return (length*breadth);
}
}
//Second create a class CopyConstructorExample which inherit the methods of above
class Rectangle and create its object and calculate area:
//class to create a rectangle objects and calculate area

Public class CopyConstructorExample{


public static void main(String args[]){
Rectangle firstRect=new Rectangle(5,6);
Rectangle secondRect=new Rectangle(firstRect);
System.out.println("Area of first rectangle=" + firstRect.area());
System.out.println("Area of second rectangle = " + secondRect.area());
}
}
Output:
Copy constructor invoked
Area of first rectangle= 30;
Area of second rectangle= 30;

-------------------------------------------------------------------------------------
Dynamic Array
ArrayList in Java
ArrayList is a part of collection framework and is present in java.util
package. It provides dynamic arrays in Java. Though, it may be slower than
standard arrays but can be helpful in programs where lots of manipulation in
the array is needed.

ArrayList is initialized by a size, however the size can increase if collection


grows or shrunk if objects are removed from the collection, so manipulation
is slow.

Java ArrayList allows us to randomly access the list because array works at
the index basis.

ArrayList cannot be used for primitive types, like int, char, etc. We need a
wrapper class.

Java ArrayList class maintains insertion order.

Java ArrayList allows duplicate and null values.

How to check if an ArrayList is empty using the isEmpty() method.


How to find the size of an ArrayList using the size() method.
How to access the element at a particular index in an ArrayList using the
get() method.
How to modify the element at a particular index in an ArrayList using the
set() method.

Difference
/* ........... Normal Array............. */
// Need to specify the size for array
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

// We cannot add more elements to array arr[]

/*............ArrayList..............*/
// Need not to specify size
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// We can add more elements to arrL

Array can contain both primitive data types as well as objects of a class
depending on the definition of the array.
However, ArrayList only supports object entries, not the primitive data types.
Note: When we do arraylist.add(1); : it converts the primitive int data type
into an Integer object.

// Example

import java.util.*;
public class ArrayListExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
// size of ArrayList
int n = 5;
//declaring ArrayList with initial size n
ArrayList<Integer> arrli = new ArrayList<Integer>(n);

// Appending the new element at the end of the list


for (int i=1; i<=n; i++)
arrli.add(i);

// Printing elements
System.out.println(arrli);

// Printing elements one by one


for (int i=0; i<arrli.size(); i++)
System.out.print(arrli.get(i)+" ");

// Remove element at index 3


arrli.remove(3);

// Displaying ArrayList after deletion


System.out.println(arrli);

// Inserting the new element at the specified position in the list


arrli.add(3, 4);

// Displaying ArrayList after deletion


System.out.println(arrli);
}

// another example of String class

For reading all elements from ArrayList, by using Iterator class. We can iterate
through the ArrayList based on index.
import java.util.*;
public class ArrayListExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList<String> list=new ArrayList<String>(); //Creating
arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");

//Traversing list through Iterator

Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); // next string
}

} // End of Main

} // End of Class

// another example of user defined class object

import java.util.*;
class StudentData{
int rollno;
String name;
int age;
StudentData(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

public class ArrayListExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
StudentData s1=new StudentData(101,"Sujal",23);
StudentData s2=new StudentData(102,"Ravi",21);
StudentData s3=new StudentData(103,"Hemant",25);
ArrayList <StudentData> AL = new ArrayList <StudentData>();
AL.add(s1);
AL.add(s2);
AL.add(s3);

//Getting Iterator
Iterator<StudentData> itr=AL.iterator();

//traversing elements of ArrayList object


while(itr.hasNext()){
StudentData sdt=(StudentData) itr.next();
System.out.println(sdt.rollno+" "+sdt.name+" "+sdt.age);
}
}

// One More Example other methods

import java.util.*;
public class ArrayListExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList<String> list=new ArrayList<String>(); //Creating
arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");

ArrayList<String> list2=new ArrayList<String>(); //Creating


arraylist

list2.add("Sunil");
list2.add("Sachin");

//Traversing list through Iterator

Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); // next string
}

System.out.println("For Loop");
for (int counter = 0; counter < list.size(); counter++) {
System.out.println(list.get(counter));
}

list.addAll(list2);//adding second list in first list


System.out.println("Another advance for loop method to print");
// another advance for loop method to get string list
for(String obj:list)
System.out.println(obj);

System.out.println("Another List-2 to print");


Iterator<String> itr2 = list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next()); // next string
}

list2.add("Gopal");

System.out.println("After adding List-2 to print");


for(String obj1:list2)
System.out.println(obj1);

System.out.println("Another method Remove all of list2 from


list");
list.removeAll(list2);

//while(itr.hasNext()){
// System.out.println(itr.next()); // next string
// }
System.out.println(list.size());

System.out.println("Advance For Loop");


for(String obj:list)
System.out.println(obj);

System.out.println("For Loop");
for (int counter = 0; counter < list.size(); counter++) {
System.out.println(list.get(counter));
}
}

ArrayList retainAll() method in Java

This method is used to retain all matching elements in the current ArrayList instance that
match all elements from the Collection list passed as a parameter to the method.

import java.util.*;
public class ArrayListExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub

// Creating an empty array list


ArrayList<String> bags = new ArrayList<String>();

// Add values in the bags list.


bags.add("pen");
bags.add("pencil");
bags.add("paper");

// Creating another array list


ArrayList<String> boxes = new ArrayList<String>();

// Add values in the boxes list.


boxes.add("pen");
boxes.add("paper");
boxes.add("books");
boxes.add("rubber");

// Before Applying method print both lists


System.out.println("Bags Contains :" + bags);
System.out.println("Boxes Contains :" + boxes);

// Apply retainAll() method to boxes passing bags as parameter


boxes.retainAll(bags);

// Displaying both the lists after operation


System.out.println("\nAfter Applying retainAll()"+
" method to Boxes\n");
System.out.println("Bags Contains :" + bags);
System.out.println("Boxes Contains :" + boxes);
} // End of main
} // end of Class

OutPut:

Bags Contains :[pen, pencil, paper]


Boxes Contains :[pen, paper, books, rubber]

After Applying retainAll() method to Boxes

Bags Contains :[pen, pencil, paper]


Boxes Contains :[pen, paper]

---------------------------------------------------

Vectors:
This class can be used to create a generic dynamic array which can hold
objects of any type and any number. The objects do not have to be homogeneous.

import java.util.*;
public class VectorExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Vector v = new Vector();
int len = args.length;
for(int i=0;i<len;i++) {
v.addElement(args[i]);
}
v.insertElementAt("Cobol", 2);
int size = v.size();
System.out.println(v);
System.out.println("List of Languages");
for(int i=0;i<len;i++) {
System.out.println(args[i]);
}
}

}
OutPut:
C:\HRP_JAVA>java VectorExample2 Ada Basic C++ Fortran Java
[Ada, Basic, Cobol, C++, Fortran, Java]
List of Languages
Ada
Basic
C++
Fortran
Java

// One More Example

import java.util.*;
public class VectorExmple1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
// create default vector
Vector v = new Vector();

v.add(0, 1);
v.add(1, 2);
v.add(2, "Manish");
v.add(3, "Mahesh");
v.add(4, 3);
v.add(5, 1);
v.add(6, 2);
v.add(7, "Poojan");
v.add(8, "Parth");
v.add(9, 3);
v.add(10, 1);
v.add(11, 2);
v.add(12, "geeks");
v.add(13, "forGeeks");
v.add(14, 3);
System.out.println("Vector is " + v);

System.out.println((int)v.get(4) * (int)v.get(6));
}

OBJECT:

Objects are born and objects die.


When objects created where they live, while they are alive and how to keep or abandon
them efficiently.
Unused Objects actually does not destroy simply abandon. But once it is abandoned, the
Garbage Collector can vaporize it, reclaiming the memory that object was using.
Java garbage collection is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine. When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to
free up memory.
Java garbage collection is an automatic process. The programmer does not need to
explicitly mark objects to be deleted. The garbage collection implementation lives in the
JVM.
In the first step, unreferenced objects are identified and marked as ready for garbage
collection. In the second step, marked objects are deleted. Optionally, memory can be
compacted after the garbage collector deletes objects, so remaining objects are in a
contiguous block at the start of the heap. The compaction process makes it easier to
allocate memory to new objects sequentially after the block of memory allocated to
existing objects.

In java, programmers care about two areas of memory-the one where objects live (the
heap), and the one where method live and local variables live (the stack).

When a JVM starts up, it gets a chunk of memory from the underlying OS, and uses it to
run your Java program. How much, memory, and whether or not you can adjust it, is
dependent on which version of the JVM and on which platform you are running.

All objects live on the garbage-collectible heap, but where variables live. And where a
variable lives depends on what kind of variable it is. And by "kind", we don't mean type
(i.e. primitive or object reference).

The two kinds of variables whose lives we care about now are instance variables and
local variables. Method invocation and local variables are also known as stack variables,
which is a big clue for where they live.

Instance Variables
Instance variables are declared inside a class but not inside a method. They represent
the "fields" that each Individual object has (which can be filled with different values for
each Instance of the class). Instance variables live inside the object they belong to.

Local Variables
Local variables are declared inside a method, including method parameters, they are
temporary, and live only as long as the method is on the stack (in other words, as long as
the method has not reached the closing curly brace).

Methods are stacked


When you call a method, the method, lands on the top of a call stack. New thing actually
pushed onto the stack is the stack frame, and it holds the state of the method including
which line of code is executing, and the values of all local variables.

The method at the top of the stack is always the currently-running method for that stack
(for now, assume there is only one stack.) A method stays on the stack until the method
hits its closing curly brace (which means the method's done). If method foo() calls
method bar(), method bar() is stacked on top of method foo().

The method on the top of the stack is always the currently executing method.

A stack scenario
Public void dostuff(){
Boolean b = True;
Go(4);
}
Public void Go(int x){
Int z = x +24;
Crazy();
}

Public void Crazy(){


Char c = ‘a’;
}

The code on the top is a snippet (we don't care what the rest of the class looks like) with three
methods. The first method dostuff() calls the second method Go() , and the second method calls
the third Crazy(). Each method declares one local variable within the body of the method, and
method Go() has two local variables.

Code from another doStuff() calls go(), Go() calls crazy(), crazy() completes,
class calls dostuff(), go() is pushed on top Crazy() is now on the and its stack frame is
and dostuff() goes of the stack. top of the stack, with popped off the stack.
into a stack frame at Variables 'x' and 'z' variable 'c' in the Execution goes back
the top of the stack. are in the go() stack frame. to the go() method.
The Boolean variable frame. and picks up at the
named 'b' goes on line following the call
the doStuff() stack to crazy().
frame.
____________ ____________ Crazy() - c
____________ Go() – x z Go() – x z Dostuff() - b
Dostuff() - b Dostuff() - b Dostuff() - b Go() – x z

What about local variables that are objects?


Remember, a non-primitive variable holds a reference to an object, not the object itself.
You already know where objects live--on the heap. It does not matter where they are
declared or created. If the local variable is a reference to an object, only the variable (the
reference/remote control) goes on the stack. The object itself still goes in the heap.

Public void crazy(){


Duck d = new Duck();
Char c = ‘a’;
}

Duck reference variable d declared inside the method, it is a local variable and goes on
to stack, but object goes on the heap.

Why are we learning the whole stack/heap thing? How does this help?

Knowing the fundamentals of the Java Stack and Heap is crucial If you want to
understand variable scope, object creation Issues, memory management, threads, and
exception handling.
If local variables live on the stack where do instance variables live?

Class Cellphone(){
Int a;
Long b;
Private antenna ant = new antenna();
}

When you say new Cellphone(), Java has to make space on the Heap for that
CellPhone. But how much space?
Enough for the object, which means enough to house the entire object’s instance
variables. It means instance variables live on the Heap, inside the object they belong to.

Remember that the values of an object's instance variables live inside the object. If the
instance variables are all primitives, Java makes space for the instance variables based
on the primitive type.

But what if the instance variables are objects? For example CellPhone has a reference
variable of type Antenna.

When the new object has instance variables that are object references rather than
primitives, the real question is: does the object need space for all of the objects it holds
references to?

The answer is, not exactly. No matter what, Java has to make space for the instance
variable values. But remember that a reference variable value is not the whole object, but
merely a remote control (reference) to the object.

So if CellPhone has an instance variable declared as the non-primitive type Antenna,


Java makes space within the CellPhone object only for the Antenna's remote control (i.e.
reference variable) but not the Antenna object.

When does the Antenna object get space on the Heap? First we have to find out when
the Antenna object itself is created. That depends on the instance variable declaration. If
the instance variable is declared but no object is assigned to it, then only the space for
the reference variable (the remote control) is created.

private Antenna ant;


No actual Antenna object is made on the heap unless or until the reference variable is
assigned a new Antenna object.
private Antenna ant = new Antenna () ;

--------------------------------------------------------------------------

There is no global anything in Java. But think about this: what if you have a method
whose behaviour does not depend on an instance variable value. Take the round ()
method in the Math class, for example.
It does the same thing every time-round a floating point number (the argument to the
method) to the nearest integer every time. If you had 10,000 instances of class Math, and
ran the round (42.2) method, you would get an integer value of 42 every time. In other
words, the method acts on the argument, but is never affected by an instance variable
state. The only value that changes the way the round () method runs is the argument
passed to the method.

In fact the Math class doesn't have any instance variables. So there's nothing to be
gained by making an instance of class Math. If you try to make an instance of class Math:
Math mathObject = new Math () , You will get error.

Methods in the Math class don't use any instance variable values. Because the methods
are 'static', you don't need to have an instance of Math.

The static keyword is used in java mainly for memory management. It is used with
variables, methods, blocks and nested class. It is a keyword that are used for 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 main method of a class is
generally labelled as static.

Let us assume that we want to define a member that is common to all objects and
accessed without using a particular object. That is the member belongs to the class as a
whole rather than the objects created from the class. Such members can be defined as
follows:

public static variableName;

public static void methodName()


{
.......
.......
}

Static method cannot call non-static method.

The static variable allocate memory only once in class area at the time of class loading.
Using static variable we make our program memory efficient (i.e it saves memory).

Static variables in a class are initialized before any object of that class can be created.

Static variables in a class are initialized before any static method of the class runs.

Static variables are initialized when the class is loaded. If you don't explicitly initialize a
static variable (by assigning it a value at the time you declare it), it gets a default value,
so int variables are initialized to zero.

You can not make reference to a static variable from a non-static method. To understand
this, you need to understand the difference between static and non-static.
Static variables are class variables, they belong to the class with their only one instance,
created at the first only. Non-static variables are initialized every time you create an
object of the class.

When you use new() operator we will create a copy of every non-static field for every
object, but it is not the case for static fields. That's why it gives compile time error if you
are referencing a static variable from a non-static method.

// Method example
public class StaticMathExample {

static float mul(float x, float y) {


return x*y;
}
static float divide(float x, float y) {
return x/y;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
float a = StaticMathExample.mul(4.0f, 5.0f);
float b = StaticMathExample.divide(a, 2.0f);
System.out.println(b);
}
}

// Other Example as variable

public class Counter {


int myCount = 0;
static int ourCount = 0;
void increment(){
myCount++;
ourCount++;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Counter counter1 = new Counter();
Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
counter2.increment();
System.out.println("Counter1 : " + counter1.myCount + " " +
counter1.ourCount);
System.out.println("Counter2 : " + counter2.myCount + " " +
counter2.ourCount);
}

// this program illustrates the use of static block


public class StaticBlock{
static int r;
static{
r =5;
System.out.println(" static block");
++r;
System.out.println(" r = " + r);
}
void display(){
++r;
System.out.println(" r = " + r);
}
public static void main(String[] args) {
System.out.println(" Main fuction");
StaticBlock sb1 = new StaticBlock();
StaticBlock sb2 = new StaticBlock();
sb1.display();
sb2.display();
}
}

---------------------------------------
Nested class meaning:
public class NestedClassExample {
int no;

public class nesclass{


public void disp() {
no = 22;
System.out.println(no + " Hello");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub

NestedClassExample.nesclass obj = new


NestedClassExample().new nesclass();
obj.disp();
}
}
---------------
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
public class NestedClassExample {
int no;

public class nesclass{


public void disp() {
no = 22;
System.out.println(no + " Hello");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer x = new Outer();
x.outerMethod();
NestedClassExample.nesclass obj = new NestedClassExample().new
nesclass();
obj.disp();
}
}
-----------------------------

Passing and Returning Objects in Java


Although Java is strictly pass by value, the precise effect differs between
whether a primitive type or a reference type is passed.

Pass by Value
Let us understand what is pass by value. Actual parameter expressions that
are passed to a method are evaluated and a value is derived. Then this value
is stored in a location and then it becomes the formal parameter to the
invoked method. This mechanism is called pass by value and Java uses it.
When we pass a primitive type to a method, it is passed by value.

class PassByValue
{
static void change(int a){
a = 500;
System.out.println("value of n changed in the function : "+a);
}
public static void main(String args[]){
int n = 56;
System.out.println("value of n before calling a function : "+n);
change(n);
System.out.println("value of n after calling a function : "+n);
}
}
Pass by Reference
In pass by reference, the formal parameter is just an alias to the actual
parameter. It refers to the actual argument. Any changes done to the formal
argument will reflect in actual argument and vice versa.
When we pass an object to a method, the objects are passed by what is
effectively call-by-reference. While creating a variable of a class type, we only
create a reference to an object. Thus, when we pass this reference to a
method, the parameter that receives it will refer to the same object as that
referred to by the argument.
 This effectively means that objects act as if they are passed to methods by
use of call-by-reference.
 Changes to the object inside the method do reflect in the object used as
an argument.

class School{
String name;
School(String n){
name = n;
}
}
class PassByRef{
static void change(School S){
S.name = "Udgam School";
System.out.println("School namevalue of S changed in the function :
"+S.name);
}

public static void main(String args[]){


School S = new School("Anand Niketan School");
System.out.println("School name before calling a function : "+S.name);
change(S);
System.out.println("School name after calling a function : "+S.name);
}
}

// One more Example


public class StaticExample1 {
int rollno;
String name;
static String college = "GPA";

static void change(){


college = "DDIT";
}

void display (){


System.out.println(rollno+" "+name+" "+college);
}

StaticExample1(int r, String n){


rollno = r;
name = n;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticExample1 s1 = new StaticExample1 (111,"Karan");
StaticExample1 s2 = new StaticExample1 (222,"Aryan");
StaticExample1 s3 = new StaticExample1 (333,"Sonoo");

s1.display();
s2.display();
s3.display();

StaticExample1.change();

s1.display();
s2.display();
s3.display();

--------------------------------------------------------------

//a program to accept two nos through command line args and add the nos.
public class CommandLineExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a, b, c;

a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
c=a+b;

System.out.println("The sum is "+ c);

//student name using command line argument and print output as


FirstSecondLastName

public class CommandLineExample2 {


public static void main(String[] args) {
// TODO Auto-generated method stub
if (args.length != 3)
{
System.out.println("not Sufficient arguments are passed");
System.exit(0);
}

System.out.println("First Name :" +args[0]);


System.out.println("Second Name:" +args[1]);
System.out.println("Last Name :" +args[2]);

// write an application that converts between meters and feet. Its first
command line argument
// is a number. Its second argument is either 'feet' or 'meters'.
// If this argument is 'feet' display equivalent meters and vice versa. 1 M =
3.28 FT

public class CommandLineExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
if (args.length != 2)
{
System.out.println("Two arguments are not passed");
System.exit(0);
}

int no = Integer.parseInt(args[0]);

String unit = args[1].toUpperCase();


if (unit.equals("FEET"))
System.out.format("%d feet = %f meters",no,no/3.28);
else
if (unit.equals("METERS"))
System.out.format("%d meters = %.2f feet",no,no*3.28);
else
System.out.println("Unit is unknown.");

/* Write an application that searches through its command line arguments. If


an argument is
* found that does not begin with an upper case letter, display error message
and terminate.
*/

public class CommandLineExample4 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int cnt = args.length;

if (args.length == 0)
{
System.out.println("command-line arguments are not passed");
System.exit(0);
}

for (int i=0;i<cnt;++i)


{
char c =args[i].charAt(0);

if (!( c>='A' && c <= 'Z'))


{ System.out.println("Argrument "+args[i]+" does not
start with a capital letter");
System.exit(0);
}
}

System.out.println("All arguments start with a capital letter");

----------------------------------

In Java, it is common to combine several classes in one .jar ("java archive") file. Library
classes are stored that way. Larger projects use jar files. You can create your own jar
file combining several classes, too.
jar files are created using the jar.exe utility program from the JDK. You can make your
jar file runnable by telling jar.exe which class has main. To do that, you need to create a
manifest file. A mainfest is a one-line text file with a "Main-Class" directive. For
example:
Main-Class: Craps
This line must end with a newline.
A jar file created with a main class manifest can be used both as a library and a runnable
jar. If you use it as a library, you can edit and compile any of the classes included in the
jar, and add it to your project. Then it will override the one in the jar file.

How to make Executable jar file

Once you have a manifest and all your classes have been compiled, you need to run
JDK's jar.exe utility. It is located in the JDK’s bin folder, the same place where javac.exe
and java.exe are. jar.exe takes command-line arguments; if you run it without any
arguments, it will display the usage information and examples. You need
C\mywork> jar cvfm MyJarName.jar mainfest.txt *.class

cvfm means "create a jar; show verbose output; specify the output jar file name; specify
the mainfest file name." This is followed by the name you wish to give to your jar file, the
name of your manifest file, and the list of .class files that you want included in the jar.
*.class means all class files in the current directory.

Actually, if your manifest contains only the Main-Class directive, you can specify the main
class directly on the jar.exe's command line, using the e switch, instead of m. Then you
do not need a separate manifest file; jar will add the required manifest to your jar file for
you. For example:
C\mywork> jar cvfe MyJarName.jar MyMainClass *.class

Below is a reference for creating a jar file in Eclipse and the detailed steps for doing this
in Command Prompt and in JCreator.
Creating a jar File in Eclipse
In Eclipse Help contents, expand "Java development user guide" ==> "Tasks" ==>
"Creating JAR files." Follow the instructions for "Creating a new JAR file" or "Creating a
new runnable JAR file."
The JAR File and Runnable JAR File commands are for some reason located under the
File menu: click on Export... and expand the Java node.

First Create manifest.txt file contains


Main-Class: MathEx

Command prompt: jar cfm mex.jar mainfest.txt MathEx.class

Run file using Command prompt: java -jar mex.jar


-----------------------------------------------------------------------------------------------------

Inheritance

Java Supports the OOP concept of reusability. Inheritance in java is a


mechanism in which one object acquires all the properties and behaviours
of parent object. (Instance variables and methods)

The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of parent class. Moreover, you can add new
methods and fields in your current class also.

Inheritance represents the parent-child relationship.

Why use inheritance in java


1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.

Terms used in Inheritence


Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
Super Class/Parent Class: Super class is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
Reusability: Reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in previous class.
The biggest advantage of Inheritance is that the code that is already present
in base class need not be rewritten in the child class.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and Variables
}

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.

Example:

Programmer is the subclass and Employee is the superclass. Relationship


between two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

// First Example

class Employee{
float salary=40000;
}
public class InheritExample extends Employee{
int bonus=10000;
public static void main(String[] args) {
// TODO Auto-generated method stub
InheritExample p=new InheritExample();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

// Second Example

class shape{
int l;
int b;
public void cirarea(int x) {
b = x;
double carea = 3.14 * b * b;
System.out.println(carea);
}
public void sqrarea(int x) {
b = x;
double sarea = b * b;
System.out.println(sarea);
}

public void rectarea(int x, int y) {


l = x;
b = y;
double rarea = l * b;
System.out.println(rarea);
}
}
public class InheritExample1 extends shape {

public static void main(String[] args) {


// TODO Auto-generated method stub
InheritExample1 ie = new InheritExample1();

System.out.println("calcualte circle area");


ie.cirarea(5);
System.out.println("calcualte square area");
ie.sqrarea(5);
System.out.println("calcualte rectangle area");
ie.rectarea(5,10);
}

// Little Change

class shape{
int b;
public void cirarea(int x) {
b = x;
double carea = 3.14 * b * b;
System.out.println(carea);
}
public void sqrarea(int x) {
b = x;
double sarea = b * b;
System.out.println(sarea);
}
}
class shapevolume extends shape {
int l;
int h;
public void rectarea(int x, int y) {
l = x;
b = y;
double rarea = l * b;
System.out.println(rarea);
}
public void rectvol(int x, int y, int z) {
l = x;
b = y;
h = z;
double rvol = l * b * h;
System.out.println(rvol);
}
}
public class InheritExample1 extends shapevolume {

public static void main(String[] args) {


// TODO Auto-generated method stub
InheritExample1 ie = new InheritExample1();

System.out.println("calcualte circle area");


ie.cirarea(5);
System.out.println("calcualte square area");
ie.sqrarea(5);
System.out.println("calcualte rectangle area");
ie.rectarea(5,10);
System.out.println("calcualte box volume");
ie.rectvol(5,10,10);
}

Method Overriding Example


class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
Public class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest:
"+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest:
"+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest:
"+a.getRateOfInterest());
}
}

Method Overloading
When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from
overriding. In overriding, a method has the same method name, type,
number of parameters. Overloading lets you make multiple versions of a
method, with different argument lists, for convenience to the callers. Here
return type is different.

public class OverLoadingExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

Types of inheritance
Inheritance may take different forms.

In single inheritance,, subclasses inherit the features of one superclass. In


image below, the class A serves as a base class for the derived class B.

Single Inheritance Example

class room
{
int length;
int breadth;

void getdata(){
length=10;
breadth=14;
}

int area(){
return(length
length*breadth);
}
}
class bedroom extends room
{
int height=10,vol;
void display()
{
vol=height*length
length*breadth;
System.out.println(
.println(vol);
}
}
public class InheritExample2 {
public static void main(String[] args) {
// TODO Auto-
-generated method stub
bedroom r1=new
new bedroom();
r1.getdata();
.getdata();
r1.area();
r1.display();
.display();
}

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.

Example:

class Animal
{
void eat()
{
System.out.println("Animal can eat");
}
}

class Bird extends Animal


{
void walk()
{
System.out.println("Bird can walk");
}
}

class Ostrich extends Bird


{
void run()
{
System.out.println("Ostrich can run at good speeds");
}
}

public class InheritExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Ostrich o1 = new Ostrich();
o1.eat();
o1.walk();
o1.run();

Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a


super class (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.
Example:
class Fruit {
protected void fruitInfo() {
System.out.println(
.println("I am a fruit. ");
}
}

// class 'Mango'
' inherits from class 'Fruit'
class Mango extends Fruit {
public void mangoInfo() {
fruitInfo(); // calling base class function
System.out.println(
.println("My name is mango. ");
}
}

// class 'Apple' inherits from class 'Fruit'


class Apple extends Fruit {
public void appleInfo() {
fruitInfo();//
// calling base class function
System.out.println(
.println("My name is apple. ");
}
}

public class InheritExample5 {

public static void main(String[] args) {


// TODO Auto-
-generated method stub
Mango m = new Mango();
Apple a = new Apple();
m.mangoInfo();
a.appleInfo();

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.

Java does not support multiple inheritance with classes. In java, we can
achieve multiple inheritance only through Interfaces.

Hybrid Inheritance: 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.
Important facts about inheritance in Java

Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.

The Object class, in the java.lang package, sits at the top of the class hierarchy tree.
Every class is a descendant, direct or indirect, of the Object class. Every class you use or
write inherits the instance methods of Object.

java.lang.Object class is the super base class of all Java classes. Every other Java
classes descend from Object.
Should we say the God class?
If a class is declared without extending another class then it will implicitly extend Object
class. This is taken care of by the JVM.
The reason for this design decision: By having the Object as the super class of all Java
classes, without knowing the type we can pass around objects using the Object
declaration.

Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.

Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.

Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods for accessing
its private fields, these can also be used by the subclass.

What all can be done in a Subclass?


 In sub-classes we can inherit members as is, replace them, hide them, or
supplement them with new members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same signature
as the one in the superclass, thus overriding it.
 We can write a new static method in the subclass that has the same signature as
the one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super
--------------------------------------------------
Access Specifier

One of the techniques in object-oriented programming is encapsulation. It


concerns the hiding of data in a class and making this class available only
through methods. In this way the chance of making accidental mistakes in
changing values is minimized. Java allows you to control access to classes,
methods, and fields via so-called access specifiers.
Java offers three access specifiers, listed below in decreasing accessibility:
• public
• protected
• private

We look at these access specifiers in more detail.


Public
Public classes, methods, and fields can be accessed from everywhere. The
only constraint is that a file with Java source code can only contain one public
class whose name must also match with the filename. You use public classes,
methods, or fields only if you explicitly want to offer access to these entities
and if this access cannot do any harm.
class Animal{
private int no=5;
public void eat(){
System.out.println("Animal can eat");
System.out.println(no);
}
}

class Bird extends Animal{


public void walk(){
System.out.println("Bird can walk");
}
}
class Ostrich extends Bird{
public void run(){
System.out.println("Ostrich can run at good speeds");
}
}
public class AccessSpecifier2{
public static void main(String[] args) {
// TODO Auto-generated method stub
Ostrich o1 = new Ostrich();
Bird b1 = new Bird();
Animal a1 = new Animal();
//System.out.println(a1.no); // cannot access – can access
through public method
a1.eat();
b1.eat();
o1.eat();
o1.walk();
o1.run();
}
}

Protected
Protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes
of the same package, but not from anywhere else. You use the protected
access level when it is appropriate for a class’s subclasses to have access to
the method or field, but not for unrelated classes.
class Animal{
protected int no = 5;
protected void eat(){
System.out.println("Animal can eat");
}
}

class Bird extends Animal{


private void walk(){
System.out.println("Bird can walk");
}
}
class Ostrich extends Bird{
public void run(){
System.out.println("Ostrich can run at good speeds");
System.out.println(no);
}
}
public class AccessSpecifier3{
public static void main(String[] args) {
Ostrich o1 = new Ostrich();
Bird b1 = new Bird();
Animal a1 = new Animal();
a1.eat();
b1.eat();
//b1.walk();
o1.eat();
//o1.walk();
o1.run();
}
}

Private
Private Methods and fields can only be accessed within the same class to
which the methods and fields belong. Private methods and fields are not
visible within subclasses and are not inherited by subclasses.
class Animal{
private void eat(){
System.out.println("Animal can eat");
}
public void disp(){
Animal a1 = new Animal();
a1.eat();
}
}

class Bird extends Animal{


void walk(){
System.out.println("Bird can walk");
}
}
class Ostrich extends Bird{
void run(){
System.out.println("Ostrich can run at good speeds");
}
}
public class AccessSpecifier1{
public static void main(String[] args) {
Ostrich o1 = new Ostrich();
Bird b1 = new Bird();
Animal a1 = new Animal();
//a1.eat(); // can't access
a1.disp();
//b1.eat(); //can't access
//o1.eat();//can't access
o1.walk();
o1.run();
}
}

So, the private access specifier is opposite to the public access specifier. It is
mostly used for encapsulation: data are hidden within the class and accessor
methods are provided.

------------------------------------------------------------------------------------------
The use of super keyword
In java to access the data members of parent class when both parent and
child class have member with same name. (Variables or methods)

To explicitly call the no-arg and parameterized constructor of parent class.

To access the method of parent class when child class has overridden that
method.
--------------------------------------------
In java a subclass inherits the accessible variables and methods from its superclass, but the constructors
of the superclass are not inherited in the subclass. They can only be invoked from constructors of subclass
using the keyword super.
The superclass constructor call must be the first statement in the body of childclass constructor. If one
does not specify super, the compiler implicitly inserts super(); at the beginning of the childclass’s default
constructor to call the superclass’s default constructor.

When you have a method in child class which is already present in the
parent class then in order to access the method of parent class, you need to
use the super keyword.

class Super1{
void show(){
System.out.println("Super Class method has been called");
}
}
class Sub1 extends Super1{
void show(){
super.show();
System.out.println("sub Class method has been called");
}
}
public class InheritExample6 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Sub1 s1 = new Sub1();
s1.show();
}
}

When you have a variable in child class which is already present in the
parent class then in order to access the variable of parent class, you need to
use the super keyword.

class Super1{
int x = 30;
void show(){
System.out.println("Super Class method has been called");
}
}
class Sub1 extends Super1{
int x = 35;
void show(){
super.show();
System.out.println("sub Class method has been called");
System.out.println("Supper class x value :" + super.x);
System.out.println("sub class x value :" + x);
}
}
public class InheritExample6 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Sub1 s1 = new Sub1();
s1.show();
}
}

When we create the object of sub class, the new keyword invokes the
constructor of child class, which implicitly invokes the constructor of parent
class. So the order to execution when we create the object of child class is:
parent class constructor is executed first and then the child class constructor
is executed. It happens because compiler itself adds super()(this invokes
the no-arg constructor of parent class) as the first statement in the
constructor of child class.
Let’s see an example to understand:

class Supercl1{
int x;
Supercl1(){
x = 30;
System.out.println("Supper class x value :" + x);
}
void show(){
System.out.println("Super Class method has been called");
}
}
class Subcl1 extends Supercl1{
int x;
Subcl1(){
x = 35;
System.out.println("sub class x value :" + x);
}
void show(){
super.show();
System.out.println("sub Class method has been called");
}
}
public class InheritExample7 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Subcl1 s1 = new Subcl1();
s1.show();
}

}
OUTPUT:
Supper class x value :30
sub class x value :35
Super Class method has been called
sub Class method has been called

However when we have a constructor in parent class that takes arguments


then we can use parameterized super, like super(100); to invoke
parameterized constructor of parent class from the constructor of child
class.

Let’s see an example to understand:

class Supercl1{
Supercl1(int y){
System.out.println("Supper class y value :" + y);
}
}
class Subcl1 extends Supercl1{
Subcl1(int y){
super(30);
System.out.println("Sub class y value :" + y);
}
}
public class InheritExample7 {

public static void main(String[] args) {


Subcl1 s2 = new Subcl1(35);
}
}

--------------------------------------

// another example

class studentdetail{
String sname;
int rollno;
studentdetail(String sname, int rollno){
this.sname = sname;
this.rollno = rollno;
}
}

class studentmark extends studentdetail{


int maths, science, english;
studentmark(int maths, int science, int english) {
super("Harshad",111);
this.maths = maths;
this.science = science;
this.english = english;
}
}
class studentresult extends studentmark{
studentresult(){
super(30,45,55);
}
void resultshow() {
if((maths > 35) && (science > 35) && (english > 35))
System.out.println("RollNo :" + rollno + " Name :" + sname +
" whose Result is pass");
else System.out.println("RollNo :" + rollno + " Name :" + sname +"
whose Result is fail");
}
}

public class InheritExample4 {

public static void main(String[] args) {


//TODO Auto-generated method stub

studentresult s1 = new studentresult();


s1.resultshow();
}

---------------------------------------------------------------------------
Rules of Super Keyword
The superclass constructor call, using keyword super must be the first statement in the
body of subclass constructor.
A superclass constructor can only be called from a subclass constructor. Any other
subclass method cannot call it.
A superclass constructor call requires the use of super. It is illegal to specify the actual
name of the class.
When a child class declares a same method which is already present in the parent class
then this is called method overriding. When child class doesn’t override the parent
class method then we don’t need to use the super keyword to call the parent class
method.

---------------------------------------------------------------------------

//Recursion Method
public class FibRecursion {

void fibonacci(int n, int n1, int n2)


{
if (n<=0)
return;
System.out.println(n2);
fibonacci(n-1,n2,n1+n2);

}
public static void main(String[] args) {
// TODO Auto-generated method stub
FibRecursion fr = new FibRecursion();
fr.fibonacci(6, 0, 1);
}

// Another Recursion Method

class fibo{
public static int fibb(int n) {
if(n <= 0) {
//System.out.println(n);
return 0;
}
if (n == 1) {
//System.out.println(n);
return 1;
}
else {
//System.out.println(n);
return(fibb(n-1)+fibb(n-2));
}
}
}
public class FibRecursion1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
fibo f = new fibo();
for(int a=0; a<6 ; a++) {
System.out.println(f.fibb(a));
}
}

// Without Recursion
public class FibwoRecursion {

int n1 = 0;
int n2 = 1;
int s = 0;
void fibonacciwr(int n)
{
if (n<=0)
return;
while ( n > 0) {
s = n1 + n2;
n1 = n2;
n2 = s;
n = n - 1;
System.out.println(s);
}
}

public static void main(String[] args) {


// TODO Auto-generated method stub
FibwoRecursion fr = new FibwoRecursion();

fr.fibonacciwr(6);

}
}

Final variable
All methods and variables are overridden in subclasses. To prevent the subclasses from
overriding the members of the superclass, declare them final using the keyword final as
a modifier.
Final variables are nothing but constants. We cannot change the value of a final variable
once it is initialized.

class finalvariable{
final int temp = 10;
}
public class FinalExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
finalvariable fv = new finalvariable();
fv.temp = 30;
System.out.println(fv.temp);
}

Blank final variable:


Let us say we have a Student class which is having a field called RollNo. Since Roll No
should not be changed once the student is registered, we can declare it as a final
variable in a class but we cannot initialize RollNo in advance for all the students
(otherwise all students would be having same roll no). In such case we can declare roll
no variable as blank final and we initialize this value during object creation like this:

class finalvariable{
final int temp;
finalvariable(int x){
temp = x;
}
}
public class FinalExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
finalvariable fv = new finalvariable(10);
finalvariable fv1 = new finalvariable(30);
//fv.temp = 30;
System.out.println(fv.temp + " " + fv1.temp);
}

Reference final variable:


When a final variable is a reference to an object, then this final variable is called
reference final variable.
As you know that a final variable cannot be re-assign. But in case of a reference final
variable, internal state of the object pointed by that reference variable can be changed.
Note that this is not re-assigning. This property of final is called non-transitivity.

public class FinalExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
final StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb);
sb.append(" World");
System.out.println(sb);
}

Final method

A final method cannot be overridden, which means even though a sub class can call the
final method of parent class without any issues but it cannot override it.

Functionality defined in this method will never be altered in any way.

class s1{
void display() { // Add final keyword
System.out.println(" Super class ");
}
}
class d1 extends s1{
void display() { /this method should be in comment
super.display();
System.out.println(" Derived class ");
}
}
public class FinalExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
d1 der = new d1();
der.display();
}

Final class:
When a class is declared with final keyword, it is called a final class. There are two uses
of a final class:
One is definitely to prevent inheritance, as final classes cannot be extended (inherited).
For example, all Wrapper Classes like Integer, Float etc. are final classes. We cannot
extend them.

Final class s1{


void display() {
System.out.println(" Super class ");
}
}
class d1 extends s1{ // gives error
}
public class FinalExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
d1 der = new d1();
der.display();
}

The other use of final with classes is to create an immutable class like the predefined
String class.

final class Student1{


final String name;
final int regNo;

public Student1(String name, int regNo)


{
this.name = name;
this.regNo = regNo;
}
public String getName()
{
return name;
}
public int getRegNo()
{
return regNo;
}
}
public class ImmutableExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
Student1 s1 = new Student1("ABC", 111);
System.out.println(s1.name);
System.out.println(s1.regNo);
//s1.regNo = 222;
Student1 s2 = new Student1("XYZ", 222);
System.out.println(s2.name);
System.out.println(s2.regNo);
}

}
---------------------------------------------------------------------------
Final variable
Final method
Final class
---------------------------------------------------------------------------

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just 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.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)

A class that is declared with abstract keyword is known as abstract class in java. It can
have abstract and non-abstract methods (method with body). It needs to be extended
and its method implemented. It cannot be instantiated.

abstract class A{}

A method that is declared as abstract and does not have implementation is known as
abstract method.

In short Abstract class means it must be extended and an abstract method means it must
be overridden.
If you declare an abstract method, you MUST mark the class abstract as well. You can’t
have an abstract method in a non-abstract class. But you can mix both abstract and non-
abstract method in an abstract class.

abstract class GraphicShape{


abstract void gdraw();
void display() {
System.out.println("Hello this is non-abstract method");
}
}
//In real scenario, implementation is provided by others i.e. unknown
by end user
class Rectangle1 extends GraphicShape{
void gdraw(){
System.out.println("drawing rectangle");
}
}
class Circle1 extends GraphicShape{
void gdraw(){
System.out.println("drawing circle");
}
}

public class AbstractExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
GraphicShape s = new Rectangle1(); ////Object is provided
through method
GraphicShape s1 = new Circle1();
s.gdraw();
s1.gdraw();
}

By marking the class as abstract, the compiler will stop creating an instance. You cannot
create the object.

A Class that is not abstract is known as concrete class.

Duplicate code is kept to a minimum. Overridden methods are subclass specific.

You can use abstract type as a reference type.

With an abstract class, doing the work at runtime are instances of a subclass of your
abstract class.

The important point is that the reference type and the object type are the same. i.e.
Rectangle1
But with polymorphism, the reference and the object can be different. GraphicShape and
Rectangle1. Reference variable type is declared as GraphicShape, but the object is
Rectangle1.
With polymorphism, the reference type can be a superclass of the actual object type.
public class AbstractExample1 {
public static void main(String[] args) {

GraphicShape s1 = new Circle1();


s1.display();

GraphicShape[] s = new GraphicShape[2];


s[0] = new Rectangle1();
s[1] = new Circle1();

for(int i = 0; i < s.length; i++) {


s[i].gdraw();
}
}
}
// Another Example

abstract class Bank{


abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest(){
return 7;
}
}

class PNB extends Bank{


int getRateOfInterest(){
return 8;
}
}
public class AbstractExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Bank b;
b=new SBI();
System.out.println("For SBI Rate of Interest is:
"+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("For PNB Rate of Interest is:
"+b.getRateOfInterest()+" %");
}

If you can declare a reference variable of a supertype, and assign a subclass object to it,
think of how that might work when the reference is an argument to a method.

abstract class Bank{


abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest(){
return 7;
}
}
class PNB extends Bank{
int getRateOfInterest(){
return 8;
}
}
class Bankd{
void Bankn(Bank bb) {
System.out.println(bb.getRateOfInterest());
}
}

class Bankf extends Bankd{

public class AbstractExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Bank b;
b=new SBI();
System.out.println("For SBI Rate of Interest is:
"+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("For PNB Rate of Interest is:
"+b.getRateOfInterest()+" %");
Bankd dd = new Bankd();
dd.Bankn(b);

If I write my code using polymorphic arguments, where I declare the method parameter
as a super-class type, I can pass in any subclass object at runtime. Because that also
means I can write my code, go on vacation, and someone else can add new subclass
types to the program and my methods will still work.

/*
Describe abstract class called Shape which has three subclasses say Triangle,
Rectangle, Circle. Define one method area()in the abstract class and override this area()
in these three subclasses to calculate for specific object i.e. area() of Triangle subclass
should calculate area of triangle etc. Same for Rectangle and Circle.
*/

import java.util.Scanner;

abstract class GShape


{
double l,b;
Scanner s = new Scanner(System.in);
abstract void area();
abstract void get();
}
class Circle extends GShape
{
void get()
{
System.out.println("Enter Radious of Circle :");
l = s.nextDouble();
}
void area()
{
System.out.println("Area of Circle is "+(3.14*l*l));
}
}

class Triangle extends GShape


{
void get()
{
System.out.println("Enter base and Height of Triangle :");
l = s.nextDouble();
b = s.nextDouble();
}
void area()
{
System.out.println("Area of Triangle is "+(l*b*0.5));
}
}

class Rectangle extends GShape


{
void get()
{
System.out.println("Enter length and breadth of Rectangle
:");
l = s.nextDouble();
b = s.nextDouble();
}void area()
{
System.out.println("Area of Rectangle is "+(l*b));
}
}

public class AbstractExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Circle c = new Circle();
c.get();
c.area();
Triangle t = new Triangle();
t.get();
t.area();
Rectangle r = new Rectangle();
r.get();
r.area();
}

What is an Interface?
An interface is just like Java Class, but it only has static constants and
abstract method. Java uses Interface to implement multiple inheritance. A
Java class can implement multiple Java Interfaces. All methods in an
interface are implicitly public and abstract.

To use an interface in your class, append the keyword "implements" after


your class name followed by the interface name.

Why is an Interface required?


To understand the concept of Java Interface better, let us see an example.
The class "Media Player" has two subclasses: CD player and DVD player.
Each having its unique implementation method to play music.

Another class "Combo drive" is inheriting both CD and DVD (see image
below). Which play method should it inherit? This may cause serious design
issues. And hence, Java does not allow multiple inheritance.
Another example of Dog:
Suppose you have a requirement where class "dog" inheriting class "animal" and "Pet"
(see image below). But you cannot extend two classes in Java. So what would you do?
The solution is Interface.

The rule for interface says,


 An interface is 100% abstract class and has only abstract methods.
 Class can implement any number of interfaces.
Class Dog can extend to class "Animal" and implement interface as "Pet".

// Example -1
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}

// Example-2
interface Pet{
int a = 10;
public void test();
}

class InterfaceExample1 implements Pet {


public void test(){
System.out.println("Interface Method Implemented");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Pet p = new InterfaceExample1();
p.test();
System.out.println("Value of a :" + p.a);
}
}

Default keyword in interface:

See following example default keyword used.


interface Petd{
int a = 10;
default void test(){
System.out.println("Interface Method Implemented");
}
}
public class InterfaceExample3 implements Petd{

public static void main(String[] args) {


// TODO Auto-generated method stub
Petd p = new InterfaceExample3();
p.test();
System.out.println("Value of a :" + p.a);
}
}

Previously we are writing the interface program in this way:

interface A{
public void disp();
}
interface B{
public void disp();
}

public class InterfaceExample11 implements A, B{


public void disp(){
System.out.println("same method name");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample11 if11 = new InterfaceExample11();
if11.disp();
}
}

Default methods can be provided to an interface without affecting


implementing classes as it includes an implementation. If each added method
in an interface is defined with implementation, then no implementing class is
affected. An implementing class can override the default implementation
provided by the interface.

Example:

interface A {
default void disp(){
System.out.println("Interface A default method");
}
}
interface B {
default void disp(){
System.out.println("Interface B default method");
}
}

public class InterfaceExample10 implements A, B{


public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample10 if10 = new InterfaceExample10();
if10.disp();
}
}
The above code will fail to compile with the error.
Since Java classes can implement multiple interfaces and each interface can
define a default method with the same method signature, the inherited
methods can conflict with each other.

To remove error following code added:


interface A {
default void disp(){
System.out.println("Interface A default method");
}
}
interface B {
default void disp(){
System.out.println("Interface B default method");
}
}

public class InterfaceExample10 implements A, B{


public void disp(){
A.super.disp();
B.super.disp();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample10 if10 = new InterfaceExample10();
if10.disp();
}
}

In summary, Default methods enable us to add new functionality to existing


interfaces without breaking older implementation of these interfaces.

When you extend an interface that contains a default method, you can do the
following:

1 Not mention the default method at all, which lets your extended interface
inherit the default method.
2 Redeclare the default method, which makes it abstract.
3 Redefine the default method, which overrides it.

We can define static methods which don’t require any object for calling.

interface Petd{
int a = 10;
static void test(){
System.out.println("Interface Method Implemented");
}
}
public class InterfaceExample3 implements Petd{

public static void main(String[] args) {


// TODO Auto-generated method stub
//Petd p = new InterfaceExample3();
Petd.test();
System.out.println("Value of a :" + Petd.a);
}
}

// Another Example

interface Drawable{
void draw();
}

class Rectanglen implements Drawable{


public void draw(){
System.out.println("drawing rectangle");
}
}
class Circlen implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
}
public class InterfaceExample7 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Drawable d=new Circlen();//In real scenario, object is provided by
method e.g. getDrawable()
d.draw();
}

}
// another Example

// A Grand parent class


interface GrandParent{
void fun();
}

// First Parent class


interface Parent1 extends GrandParent{
default void fun(){
System.out.println("Parent1");
}
}

// Second Parent Class


interface Parent2 extends GrandParent
{
default void fun(){
System.out.println("Parent2");
}
}

public class InterfaceExample8 implements Parent1, Parent2{


public void fun() {
Parent1.super.fun();
Parent2.super.fun();
//GrandParent.super.fun();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample8 if8 = new InterfaceExample8();
if8.fun();
}
}

// Example of extending interface

interface Inf1{
void method1();
}
interface Inf2 extends Inf1{
void method2();
}

public class InterfaceExample4 implements Inf2{


public void method1() {
System.out.println("Method 1 Executed");
}
public void method2() {
System.out.println("Method 2 Executed");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Inf2 obj = new InterfaceExample4();
obj.method2();
}

// Example of two interfaces

interface Banksbi{
public void disp();
int x = 10;
}
interface Bankpnb{
public void disp();
int x = 100;
}
public class InterfaceExample5 implements Banksbi,Bankpnb {
public void disp() {
System.out.println("Hello Interface");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample5 obj = new InterfaceExample5();
obj.disp();
System.out.println(Banksbi.x);
System.out.println(Bankpnb.x);
}

// Another Example

interface Banksbi{
public void disp();
int x = 10;
public int calintrest();
}
interface Bankpnb{
public void disp();
int x = 100;
public int calintrest(int a);
}
public class InterfaceExample5 implements Banksbi,Bankpnb {
public void disp() {
System.out.println("Hello Interface");
}
public int calintrest() {
return(6);
}
public int calintrest(int a) {
return(a);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample5 obj = new InterfaceExample5();
obj.disp();
System.out.println(Banksbi.x);
System.out.println(Bankpnb.x);
System.out.println(obj.calintrest());
System.out.println(obj.calintrest(7));
}

// Override the methods Example

interface Circle{
void area_circle();
void circum_circle();
}
interface Square{
void area_square();
void circum_square();
}
interface Rectangle1{
void area_rect();
void circum_rect();
}
class drgShapes implements Circle,Square,Rectangle1{
public void area_circle(int r){
double area=3.14*Math.sqrt(r);
System.out.println("Area of Circle :" + area);
}
public void circum_circle(int r){
double circum=6.28*r;
System.out.println("Circumference of Circle :" + circum);
}
public void area_square(int a){
int area=a*a;
System.out.println("Area of Square :" + area);
}
public void circum_square(int a){
int circum=4*a;
System.out.println("Circumference of Square :" + circum);
}
public void area_rect(int l,int b){
int area=l*b;
System.out.println("Area of Rectangle :" + area);
}
public void circum_rect(int l,int b){
int circum=2*l+b;
System.out.println("Circumference of Rectangle :" + circum);
}
@Override
public void area_rect() {
// TODO Auto-generated method stub

}
@Override
public void circum_rect() {
// TODO Auto-generated method stub

}
@Override
public void area_square() {
// TODO Auto-generated method stub

}
@Override
public void circum_square() {
// TODO Auto-generated method stub

}
@Override
public void area_circle() {
// TODO Auto-generated method stub

}
@Override
public void circum_circle() {
// TODO Auto-generated method stub
}
}
public class InterfaceExample6 {

public static void main(String[] args) {


// TODO Auto-generated method stub
drgShapes sh=new drgShapes();
sh.area_circle(3);
sh.circum_circle(3);
sh.area_square(4);
sh.circum_square(4);
sh.area_rect(10,20);
sh.circum_rect(10,20);
}

}
Must know facts about Interface
A Java class can implement multiple Java Interfaces. It is necessary that the class must
implement all the methods declared in the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning which classes it
belongs.
Class needs to provide functionality for the methods declared in the interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only one class
but implement any number of interfaces
An interface cannot implement another Interface. It has to extend another interface if
needed.
An interface which is declared inside another interface is referred as nested interface
At the time of declaration, interface variable must be initialized. Otherwise, the compiler
will throw an error.
The class cannot implement two interfaces in java that have methods with same name
but different return type.

How do you know whether to make a class, a subclass, an abstract class, or an


interface?

Make a class that doesn’t extend anything (other than Object) when your new class
doesn’t pass the IS-A test for any other type.

Make a subclass (in other words, extend a class) only when you need to make a more
specific version of a class and need to override or add new behaviours.

Use an abstract class when you want to define a template for a group of subclasses,
and you have at least some implementation code that all subclasses could use.

Make the class abstract when you want to guarantee that nobody can make objects of
that type.

Use an interface when you want to define a role that other classes can play, regardless
of where those classes are in the inheritance tree.

When you don’t want anyone to make a new object of that class type, mark the class with
the abstract keyword.

An abstract class can have both abstract and non-abstract methods.

If a class has even one abstract method, the class must be marked abstract.

An abstract method has no body, and the declaration ends with a semicolon (no curly
braces).
All abstract methods must be implemented in the first concrete subclass in the
inheritance tree.

Every class in Java is either a direct or indirect subclass of class Object (java.lang.
Object).

JAVA PACKAGE

A java package is a group of similar types of classes, interfaces and sub-


packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

The Java API is a library of prewritten classes, that are free to use, included
in the Java Development Environment.

The library contains components for managing input, database programming,


and much much more. The complete list can be found at Oracles website:
https://docs.oracle.com/javase/8/docs/api/

The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import
keyword:
We can assume package as a folder or a directory that is used to store similar
files.

How? - creating and using user-defined packages

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision. There can not be two classes
with same name in a same Package But two packages can have a class
with same name.
4) It helps improve re-usability.

In short 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.

The package keyword is used to create a package in java.


//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package


Follow the syntax given below:

javac -d directory javafilename

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file.
You can use any directory name like d:/abc. If you want to keep the package
within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

We can assume package as a folder or a directory that is used to store


similar files.
Additional points about package:
1. Package statement must be first statement in the program even before
the import statement.
2. A package is always defined as a separate folder having the same
name as the package name.
3. Store all the classes in that package folder.
4. All classes of the package which we wish to access outside the
package must be declared public.
5. All classes of the package must be compiled before use.

How to access package from another package?


There are three ways to access the package from outside the package.

import package.*;
import package.classname;
fully qualified name.

1. Using packagename.*
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{
public void msg(){
System.out.println("Hello");
}
}

//save by B.java

import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

2. Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname

//save by B.java
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

3. Using fully qualified name


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.
Example of package by import fully qualified name

//save by B.java

class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
package mypack;
public class calculator {
public int add(int a, int b){
return a+b;
}
}
import mypack.*;
public class calc{
public static void main(String args[]){
calculator obj = new calculator();
System.out.println(obj.add(100, 200));
}
}

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize
the package further.
As an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized
the java package into subpackages such as lang, net, io etc. and put the Input/Output
related classes in io package, Server and ServerSocket classes in net packages and so
on.

Example of Subpackage

package pack.subpack;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java pack.subpack.Simple
Output:Hello subpackage

TYPES of predefined packages:


As a part of J2SE we have nine predefined packages which are given in the
following table:

java.lang.*
This package is used for achieving the language functionalities such as
conversion of data from string to fundamental data, displaying the result on
to the console, obtaining the garbage collector. This is the package which is
by default imported for each and every java program.

java.io.*
This package is used for developing file handling applications, such as,
opening the file in read or write mode, reading or writing the data, etc.

java.awt.*(abstract windowing toolkit)


This package is used for developing GUI (Graphic Unit Interface)
components such as buttons, check boxes, scroll boxes, etc.

java.awt.event.*
Event is the sub package of awt package. This package is used for
providing the functionality to GUI components, such as, when button is
clicked or when check box is checked, when scroll box is adjusted either
vertically or horizontally
.
java.applet.*
This package is used for developing browser oriented applications. In other
words this package is used for developing distributed programs. An applet is
a java program which runs in the context of www or browser.

java.net.*
This package is used for developing client server applications.

java.util.*
This package is used for developing quality or reliable applications in java or
J2EE. This package contains various classes and interfaces which improves
the performance of J2ME applications. This package is also known as
collection framework (collection framework is the standardized mechanism
of grouping of similar or different type of objects into single object. This
single object is known as collection object).

java.text.*
This package is used for formatting date and time on day to day business
operations.

java.lang.reflect.*
Reflect is the sub package of lang package. This package is basically used
to study runtime information about the class or interface. Runtime
information represents data members of the class or interface, Constructors
of the class, types of methods of the class or interface.

java.sql.*
This package is used for retrieving the data from data base and performing
various operations on data base.

/* if Comp class is used in this file, and if the class file is available, this
program will compile successfully; but if the Comp.class file is not available
and that class is stored in Comp.java file, then when you compile this class,
it will automatically compile that Comp.java file and create Comp.class and
this program will compile successfully;
*/

class Comp{
void disp(){
System.out.println("disp method of Computer ");
}
}
class Mech{
void dispClass2() {
Comp c1 = new Comp();
c1.disp();
}
}

class AutoCompile{
public static void main(String args[]){
Mech m = new Mech();
m.dispClass2();
}
}

------------------------------
EXCEPTION HANDLING
------------------------------
Exception handling allows us to handle the runtime errors caused by
exceptions.

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the


program. When an exception occurs, program execution gets terminated. In
such cases we get a system generated error message. The good thing
about exceptions is that they can be handled in Java. By handling the
exceptions we can provide a meaningful message to the user about the
issue rather than a system generated message, which may not be
understandable to a user.

String t = “two”;
int y = Integer.parseInt(t);

Exception in thread "main"


java .lang.NumberFormatException: two
at java.lang.lnteger.parselnt(Integer .java:409)
at java .lang .lnteger.parselnt(Integer .java:458)
at Wrappers.main(Wrappers.java:9)

It's a runtime exception : NumberFormatException

This message is not user friendly so a user will not be able to understand
what went wrong. In order to let them know the reason in simple language,
we handle exceptions. We handle such conditions and then print a user
friendly warning message to user, which lets them correct the error.

Why an exception occurs?

Most of the time exception occurs due to bad data provided by user. There
can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by user etc.

Exception handling ensures that the flow of the program doesn’t break when
an exception occurs.

Difference between error and exception

Errors indicate that something is wrong and the application will crash rather
than try to handle the error.

Exceptions are events that occur in the code. A programmer can handle
such conditions and take necessary corrective actions. Few examples:

NullPointerException – When you try to use a reference that points to null.


ArithmeticException – When bad data is provided by user, for example,
when you try to divide a number by zero this exception occurs because
dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements
of an array out of its bounds, for example array size is 5 (which mean it has
five elements) and you are trying to access the 10th element.

There are two types of exceptions in Java:


1)Checked exceptions
2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked


exceptions as the compiler checks them during compilation to see whether
the program can handle them or not. If these exceptions are not handled/
declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time so compiler does not check, but
it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.

Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block.
catch block
A catch block is where you handle the exceptions, this block must follow the
try block. A single try block can have several catch blocks associated with it.
You can catch different exceptions in different catch blocks. When an
exception occurs in try block, the corresponding catch block that handles
that particular exception executes.
EXAMPLE-1
public class ExceptionExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num1, num2;
try {
/* We suspect that this block of statement can throw exception so we
handled it by placing these statements inside try and handled the
exception in catch block */
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
occurs in try block */

System.out.println("You should not divide a number by


zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can
handle all the exceptions. This will execute if the exception is not
handled by previous catch blocks.*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}

}
OUTPUT:
You should not divide a number by zero
I'm out of try-catch block in Java.

Rules about multiple catch blocks

1. A single try block can have any number of catch blocks.


2. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of them.
3. If no exception occurs in try block then the catch blocks are completely
ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can handle
ArithmeticException
catch(NullPointerException e) is a catch block that can handle
NullPointerException
5. You can also throw exception.

Why we need other catch handlers when we have a generic that can handle
all?
This is because in generic exception handler you can display a message but
you are not sure for which type of exception it may trigger so it will display
the same message for all the exceptions and user may not be able to
understand which exception occurred. That is the reason you should place
all the specific exception catch blocks before generic.

EXAMPLE-2
public class ExceptionExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try{
int a[]=new int[7];
a[9]=30/2; // check with a[4] = 30/0;
//String s=null;
//System.out.println(s.length());
//String s="abc";
//int i=Integer.parseInt(s);
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:
ArrayIndexOutOfBoundsException");
}
catch(NullPointerException e){
System.out.println("Warning: NullPointerException");
}
catch(NumberFormatException e){
System.out.println("Warning: NumberFormatException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");

}
OUTPUT:
Warning: ArrayIndexOutOfBoundsException
Out of try-catch block...

Example:-

/* A program to find out average of its command line arguments */


class Average {
public static void main(String[] args) {
int len=args.length,temp,sum=0, lena=len;
float avg;
System.out.println(len);
for(int i=0;i<len;++i){
try{
temp = Integer.parseInt(args[i]);
}

catch(NumberFormatException e){
temp=0;
lena = lena - 1;
}
System.out.println("temp =" + temp);
sum = sum +temp;
}
System.out.println("Sum =" + sum);
try{
avg = sum /lena;
}
catch(ArithmeticException e){
avg = 0.0f;
}

System.out.println("Average is : " + avg);


}
}

Java’s Built-in Exception classes


Under java.lang package Java defines many exception classes to capture
exceptions. Below is a list of exception classes available.

Exception Meaning
Arithmetic error, such as integer divide-by-
ArithmeticException
zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
Assignment to an array element of an
ArrayStoreException
incompatible type.
ClassCastException Invalid cast.
An attempt is made to use an undefined
EnumConstantNotPresentException
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on
IllegalMonitorStateException
an unlocked thread.
Environment or application is in an incorrect
IllegalStateException
state.
Requested operation not compatible with current
IllegalThreadStateException
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException The array created with a negative size.
NullPointerException Invalid use of a null reference.
Invalid conversion of a string to a numeric
NumberFormatException
format.
SecurityException Attempt to violate security.
Attempt to index outside the bounds of a
StringIndexOutOfBoundsException
string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
ClassNotFoundException Class not found.
Attempt to clone an object that does not
CloneNotSupportedException
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
Attempt to create an object of an abstract
InstantiationException
class or interface.
One thread has been interrupted by another
InterruptedException
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
ReflectiveOperationException Superclass of reflection-related exceptions.

Throw and throws in Java


Throw
The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");

Creating Instance of Throwable class using NEW operator.


This constructs an instance of ArithmeticException with name ("/ by zero")

public class ExceptionExample6 {


static void validateage(int age){
if (age < 18)
throw new ArithmeticException(" Age is not valid");
else
System.out.println("WelCome for Voting");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
validateage(18);
validateage(13);
}
}

OUTPUT:
WelCome for Voting
Exception in thread "main" java.lang.ArithmeticException: Age is not valid
at ExceptionExample6.validateage(ExceptionExample6.java:5)
at ExceptionExample6.main(ExceptionExample6.java:13)

In this exception instance must be of type Throwable or a subclass of Throwable.

The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to see
if it has a catch statement that matches the type of exception. If it finds a
match, control is transferred to that statement otherwise next enclosing try
block is checked and so on. If no matching catch is found then the default
exception handler will halt the program.

// Another Program - use of throw


public class ExceptionExample4 {
static void fun(){
try{
throw new NullPointerException("demo");
}
catch(NullPointerException e){
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
fun();
}
catch(NullPointerException e){
System.out.println("Caught in main.");
}
}
}
OUTPUT:
Caught inside fun().
Caught in main.

The java.lang.Throwable class is the superclass of all errors and


exceptions in the Java language. Only objects that are instances of this
class (or one of its subclasses) are thrown by the Java Virtual Machine or
can be thrown by the Java throw statement.

Class constructors
Throwable(): This constructs a new throwable with null as its detail
message.
Throwable(String message): This constructs a new throwable with the
specified detail message.
Throwable(String message, Throwable cause): This constructs a new
throwable with the specified detail message and cause.
Throwable(Throwable cause): This constructs a new throwable with the
specified cause.

Class methods
1 Throwable fillInStackTrace()
This method fills in the execution stack trace.
2 Throwable getCause()
This method returns the cause of this throwable or null if the cause is
nonexistent or unknown.
3 String getLocalizedMessage()
This method creates a localized description of this throwable.
4 String getMessage()
This method returns the detail message string of this throwable.
5 StackTraceElement[] getStackTrace()
This method provides programmatic access to the stack trace information
printed by printStackTrace().
6 Throwable initCause(Throwable cause)
This method initializes the cause of this throwable to th
thee specified value.
7 void printStackTrace()
This method prints this throwable and its backtrace to the standard error
stream.
8 void printStackTrace(PrintStream s)
This method prints this throwable and its backtrace to the specified print
stream.
9 void
id printStackTrace(PrintWriter s)
This method prints this throwable and its backtrace to the specified print
writer.
10 void setStackTrace(StackTraceElement[] stackTrace)
This method sets the stack trace elements that will be returned by
getStackTrace() and printed by printStackTrace() and related methods.
11 String toString()
This method returns a short description of this throwable.

List of Java Exceptions


All public exceptions and errors in the Java API (version 8), grouped by package:
Package java.lang
 Throwable
o Exception
 CloneNotSupportedException
 InterruptedException
 ReflectiveOperationException
 ClassNotFoundException
 IllegalAccessException
 InstantiationException
 NoSuchFieldException
 NoSuchMethodException
 RuntimeException
 ArithmeticException
 ArrayStoreException
 ClassCastException
 EnumConstantNotPresentException
 IllegalArgumentException
 IllegalThreadStateException
 NumberFormatException
 IllegalMonitorStateException
 IllegalStateException
 IndexOutOfBoundsException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
 NegativeArraySizeException
 NullPointerException
 SecurityException
 TypeNotPresentException
 UnsupportedOperationException
o Error
 AssertionError
 LinkageError
 BootstrapMethodError
 ClassCircularityError
 ClassFormatError
 UnsupportedClassVersionError
 ExceptionInInitializerError
 IncompatibleClassChangeError
 AbstractMethodError
 IllegalAccessError
 InstantiationError
 NoSuchFieldError
 NoSuchMethodError
 NoClassDefFoundError
 UnsatisfiedLinkError
 VerifyError
 ThreadDeath
 VirtualMachineError
 InternalError
 OutOfMemoryError
 StackOverflowError
 UnknownError

public class ExceptionExample16 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try
{
int a = 20/0;
} catch (Exception e)
{

System.out.println(e.getMessage());
System.out.println("");
System.out.println(e.toString());
System.out.println("");
// Prints what exception has been thrown
System.out.println(e);
System.out.println("");
// printStackTrace method
// prints line numbers + call stack
e.printStackTrace();

}
}
}

OUTPUT:
/ by zero

java.lang.ArithmeticException: / by zero

java.lang.ArithmeticException: / by zero

java.lang.ArithmeticException: / by zero
at ExceptionExample16.main(ExceptionExample16.java:8)

Throws

Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that method
gets a prior knowledge about which exceptions are to be handled. A method
can do so by using the throws keyword.
Throws indicate that this method might throw one of the listed type
exceptions. The caller to these methods has to handle the exception using a
try-catch block.
We can use throws keyword to delegate the responsibility of exception
handling to the caller (It may be a method or JVM) then caller method is
responsible to handle that exception.
Syntax:
type method_name(parameters) throws exception_list
{ //definition of method }
exception_list is a comma separated list of all the exceptions which a
method might throw.

public class ExceptionExample7 {

static void check() throws ArithmeticException{


System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
try{
check();
}
catch(ArithmeticException e){
System.out.println("Caught--" + e);
}
}
}

OUTPUT:
Inside check function
Caught--java.lang.ArithmeticException: demo

You just need to extend the Exception class to create your own Exception
class. These are considered to be checked exceptions.
An exception class is like any other class, containing useful fields and
methods.
----------Example--------

import java.util.*;
class RangeException extends Exception
{

}
public class ExceptionExample8 {
static int add() throws RangeException{
int sum = 0;
System.out.println("Enter the number for summation");
for(int i=0;i<5;i++) {
Scanner s = new Scanner (System.in);
int no = s.nextInt();
if(no > 25 && no <50) {
throw new RangeException();
}
sum = sum + no;
}

return(sum);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int Total = add();
System.out.println("Total =" + Total);
}
catch(RangeException e) {
System.out.println("No is out of range");
}

}
}

----------------Example--------------

import java.util.*;
class RangeOutofException extends Exception
{

}
public class ExceptionExample9 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int sum = 0;
try {
System.out.println("Enter the number for summation");
for(int i=0;i<5;i++) {
Scanner s = new Scanner (System.in);
int no = s.nextInt();
if(no > 25 && no < 50) {
throw new RangeOutofException();
}
sum = sum + no;
}
}
catch(RangeOutofException e) {
System.out.println("No is out of range");
}
}
}

A finally block is where you put code that must run regardless of an
exception.
-------------Example-------------

import java.util.*;
class RangeOutofException extends Exception
{

}
public class ExceptionExample9 {

public static void main(String[] args) {


// TODO Auto-generated method stub
int sum = 0;
try {
System.out.println("Enter the number for summation");
for(int i=0;i<5;i++) {
Scanner s = new Scanner (System.in);
int no = s.nextInt();
if(no > 25 && no < 50) {
throw new RangeOutofException();
}
sum = sum + no;
}
}
catch(RangeOutofException e) {
System.out.println("No is out of range");
}
finally {
System.out.println("summation :" + sum);
}
}
}
------------------Another Example----------

import java.util.*;
class SemException extends Exception
{
}
public class ExceptionExample11 {
int sem;
String name;
Scanner Sc = new Scanner(System.in);

void getData() throws SemException{


System.out.println("Enter Semester:");
sem = Sc.nextInt();

if(sem<1 || sem >6)


throw new SemException();
}
void display(){
System.out.println("Semester : "+sem);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
ExceptionExample11 Sem = new ExceptionExample11();
try {
Sem.getData();
Sem.display();
}
catch(SemException e){
System.out.println("semester is out of range");
}
}

-----Another Example-----------
import java.util.*;
class NotSufficientFundException extends Exception
{
}
public class ExceptionExample10 {
String name;
int ac_no;
String type;
long balance;
Scanner s = new Scanner(System.in);
void getData(){
System.out.print("Enter name:");
name=s.nextLine();
System.out.print("Enter number:");
ac_no=s.nextInt();
System.out.print("Enter type(Saving/Current):");
type=s.nextLine();
System.out.print("Enter initial Balance:");
balance=s.nextLong();
}
void display(){
System.out.println("Name :"+name);
System.out.println("Number :"+ac_no);
System.out.println("Type :"+type);
System.out.println("Balance :"+balance);
}
void deposit(){
System.out.print("Enter amount to deposit :");
int amt = s.nextInt();
balance = balance + amt;
System.out.println("New Balance :"+ balance);
}
void withdraw() throws NotSufficientFundException{
System.out.print("Enter amount to withdraw :");
int amt = s.nextInt();
if(balance > amt){
balance -= amt;
System.out.println("New Balance :"+ balance);
}
else
throw new NotSufficientFundException();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionExample10 cust = new ExceptionExample10();
System.out.println("\n1. Open an Account");
System.out.println("\n2. Deposit");
System.out.println("\n3. Withdraw");
System.out.println("\n4. Display");
System.out.println("\n5. Exit");
Scanner s = new Scanner(System.in);
System.out.print("\n\n. Enter your choice(1-5):");
boolean ac_opened = false;
int choice = s.nextInt();
switch(choice)
{
case 1: if( ac_opened == false){
cust.getData();
ac_opened=true;
}
else
System.out.println("Your account
is opened !!");
break;
case 2: cust.deposit(); break;
case 3:
try{
cust.withdraw();
}
catch(NotSufficientFundException e)
{ System.out.println("Not sufficient fund");
}
break;
case 4: cust.display(); break;
case 5: System.exit(0);
default : System.out.println("Enter choice between 1 to
5");
}

}
------------------------------------------
In Below Example constructor of MyExampleException requires a
string as its argument. The string is passed to parent class
Exception’s constructor using super().

class MyExampleException extends Exception{


public MyExampleException(String s){
// Call constructor of parent Exception
super(s);
}
}
public class ExceptionExample5 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try
{
// Throw an object of user defined exception
throw new MyExampleException("Error Generated");
}
catch (MyExampleException ex)
{
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}

}
OUTPUT:
Caught
Error Generated
-----------------------------------------------
In a nut shell:
Important points to remember about throws keyword:

throws keyword is required only for checked exception and usage of throws
keyword for unchecked exception is meaningless.
throws keyword is required only to convince compiler and usage of throws
keyword does not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the
method about the exception.

Throw
1. Java throw keyword is used to explicitly throw an exception.
2. Checked exception cannot be propagated using throw only.
3. Throw is followed by an instance.
4. Throw is used within the method.
5. You cannot throw multiple exceptions.
Throws
1. Java throws keyword is used to declare an exception.
2. Checked exception can be propagated with throws.
3. Throws is followed by class.
4. Throws is used with the method signature.
5. You can declare multiple exceptions e.g. public void method()throws
IOException,SQLException

Java Exception propagation


An exception is first thrown from the top of the stack and if it is not caught, it
drops down the call stack to the previous method, If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack. This is called exception
propagation.
public class ExceptionExample15 {
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");
}
}

public static void main(String[] args) {


// TODO Auto-generated method stub
ExceptionExample15 obj = new ExceptionExample15();
obj.p();
System.out.println("normal flow...");
}
}

In the above example exception occurs in m() method where it is not handled, so it
is propagated to previous n() method where it is not handled, again it is
propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method, p()
method, n() method or m() method.

------------------------------------------------------------------------------------------

Give Answer:
1) What is the output of the following program?
public class Test
{
public static void main(String[] args)
{
try
{
System.out.printf("1");
int sum = 9 / 0;
System.out.printf("2");
}
catch(ArithmeticException e)
{
System.out.printf("3");
}
catch(Exception e)
{
System.out.printf("4");
}
finally
{
System.out.printf("5");
}
}
}

public class ExceptionExample13 {


private void m1()
{
m2();
System.out.printf("1");
}
private void m2()
{
m3();
System.out.printf("2");
}
private void m3()
{
System.out.printf("3");
try
{
int sum = 4/0;
System.out.printf("4");
}
catch(ArithmeticException e)
{
System.out.printf("5");
}

System.out.printf("7");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionExample13 obj = new ExceptionExample13();
obj.m1();
}

public class Test


{
public static void main(String[] args)
{
try
{
System.out.printf("1");
int data = 5 / 0;
}
catch(ArithmeticException e)
{
System.out.printf("2");
System.exit(0);
}
finally
{
System.out.printf("3");
}
System.out.printf("4");
}
}

We want something to run continuously, checking for messages from the


server, but without interrupting the user’s ability to interact with the GUI. So
while the user is happily typing new messages or scrolling through the
incoming messages, we want something behind the scenes to keep reading
in new input from the server.
That means we need a new thread and a new separate Stack.

With more than one call Stack, we get the appearance of having multiple
things happen at the same time. In reality, only a true multiprocessor system
can actually do more than one thing at a time, but with Java threads, it can
appear that you're doing several things simultaneously. In other words,
execution can move back and forth between stacks so rapidly that you feel as
though all stacks are executing at the same time.

Thus, multithreading is a specialized form of multitasking (two or more parts


that can run concurrently) and each thread defines a separate path of the
execution.

Java provides built-in support for multithreading and Threads reduce


inefficiency by preventing the waste of CPU cycles.

Multiple threading in Java means we have to look at both the thread and the
job that's run by the thread. And we will also have to look at the Thread class
in the java.lang package.

A Java thread is actually a lightweight process.

A Thread object represents a thread of execution. You will create an instance


of class Thread each time you want to start up a new thread of execution.

Every Java application starts up a main thread - the thread that puts the
main() method on the bottom of the stack. The JVM is responsible for starting
the main thread. As a programmer, you can write code to start other threads
of your own.

Threads exist in several states. The following are those states:


New - When we create an instance of Thread class, a thread is in a new
state. Thread t = new Thread();
Runnable - This means the thread is ready to run and just waiting for its
chance to be selected for execution. At this point, there is a new call stack for
this thread. t.start()
Running – The Java thread is in running state. You cannot force a thread to
move from runnable to running. In the running state, a thread has an active
call stack, and the method on the top of the slack is executing.
Blocked/Waiting - A java thread can be blocked (temporarily not runnable)
when waiting for a resource. For example, the thread might be executing
code to read from a Socket input stream, but there isn't any data to read. The
scheduler will move the thread out of the running state until something
becomes available. Or the executing code might have told the thread to put
itself to sleep (sleep()). Or the thread might be waiting because it tried to call
a method on an object, and that object was 'locked', In that case, the thread
can't continue until the object's lock is freed by the thread that has it.
When multiple threads are running in the application, there is a need for
synchronization between threads. Hence, one thread has to wait, till the other
thread gets executed.
After completion thread can be resumed, allowing it to pick up where it left off.
Terminated - A thread can be terminated, which halts its execution
immediately at any given time. Once a thread is terminated, it cannot be
resumed.

Java's multithreading system is built upon the Thread class, its methods, and
its companion interface - Runnable.

Thread class Constructors:

Thread(): Allocates a new Thread object


Thread(Runnable target): Allocates a new Thread object. target - the object
whose run method is invoked when this thread is started.
Thread(String name): Allocates a new Thread object. name - the name of the new
thread.
Thread(Runnable target, String name): Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target): Allocates a new Thread
object. group - the thread group. If null and there is a security manager, the
group is determined by SecurityManager.getThreadGroup(). If there
is not a security manager or SecurityManager.getThreadGroup() returns null,
the group is set to the current thread's thread group.
Thread(ThreadGroup group, String name): Allocates a new Thread object
Thread(ThreadGroup group, Runnable target, String name): Allocates a new
Thread object so that it has target as its run object, has the specified name
as its name, and belongs to the thread group referred to by group
Thread(ThreadGroup group, Runnable target, String name, long stackSize):
Allocates a new Thread object so that it has target as its run object, has the
specified name as its name, and belongs to the thread group referred to by
group, and has the specified stack size

The Thread class defines several methods that help in manage threads.

start() - Start a thread by calling its run method


run() - Entry point for the thread getName()
- Obtain thread’s name
setName(String name) – set thread’s name
isAlive() – Returns true if the thread is alive, which is any time after the thread
has been started but before it runs to completion.
join(long millisec) - The current thread invokes this method on a second
thread, causing the current thread to block until the second thread terminates
or the specified number of milliseconds passes.
sleep(int milliseconds) - Suspend a thread for a period of time
getPriority - Obtain thread’s priority
setPriority(int newpriority) - It changes the priority of the thread.
yield () - It causes current thread on halt and other threads to execute.
Thread.currentThread() - Returns a reference to the currently executing thread
object
Thread.getState() Returns the state of this thread
Thread.interrupt() Interrupts this thread Thread.getId()
Returns the identifier of this Thread

All Java programs begin with the main java thread.

Why Is Main Thread So Important?


Because this thread affects the other 'child' threads,
Because it performs various shutdown actions,
It is created automatically when your program is started.
To create a new thread, your program will either extend Thread or implement
the Runnable interface.

By implementing the Runnable interface.

The easiest way to create a thread is to create a class that implements the
Runnable interface.

Runnable is an interface. You'll write a class that implements the Runnable


interface, and that class is where you will define the work that a thread will
perform.

Runnable threadJob = new MyRunnable(); Thread


myThread = new Thread(threadJob);

Pass the new Runnable object to the Thread constructor. This tells the new
Thread object which method to put on the bottom of the new stack- the
Runnable's run() method.

myThread.start();

Nothing happens until you call the Thread's start() method. When the new
thread starts up, it takes the Runnable object's run() method and puts it on
the bottom of the new thread's stack.
When you pass a Runnable to a Thread constructor, you're really just giving
the Thread a way to get to a run() method. You're giving the Thread its job to
do.

Runnable is in the java.lang package, so you do not need to import it.


Runnable has only one method to implement: public void run() with no
arguments. This is where you put the job the Thread is supposed to run. This
is the method that goes at the bottom of the stack.
---------------------------------------------------------------------------

class MyRunnable implements Runnable {


public void run(){
domore();
}
public void domore() { go();
}
public void go(){
System.out.println("top of the stack");
}
}

public class ThreadingExample1 {


public static void main(String[] args) {
// TODO Auto-generated method stub Runnable
threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread.start();

System.out.println("Back in main()");
}

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

The thread scheduler makes all the decisions about who moves from
runnable to running, and about when (and under what circumstances) a
thread leaves the running state. The scheduler decides who runs, and for
how long, and where the threads go when the scheduler decides to kick them
out of the currently-running state.

The scheduler implementations are different for different JVM's, and even
running the same program on the same machine can give you different
results.

Putting a thread to sleep, even for a few milliseconds, forces the currently-
running thread to leave the running state, thus giving another thread a
chance to run.
Thread Priorities
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of
1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.
------------------------------------------------------------------------------------------------

class MyRunnable implements Runnable {


public void run(){
go();
}
public void go() {

domore();
}
public void domore(){ System.out.println("top of the
stack");
}
}

public class ThreadingExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub Runnable
threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
System.out.println("before start(), tt.isAlive()=" +
myThread.isAlive());

myThread.start(); System.out.println(myThread.getName());
System.out.println("after start(), tt.isAlive()=" +
myThread.isAlive());
try {
Thread.sleep(1000); System.out.println("Back
in main()");
}catch(InterruptedException ex) {
ex.printStackTrace();
}

}
Output:
before start(), tt.isAlive()=false
Thread-0
after start(), tt.isAlive()=true top
of the stack
Back in main()

---------------------------------------------------------------------------

public class ThreadingExample4 implements Runnable{

public static void main(String[] args) {


// TODO Auto-generated method stub
Thread T1 = new Thread("Thread1");
Thread T2 = new Thread("Thread2");
T1.start();
T2.start();
System.out.println("Thread names are following:");
System.out.println(T1.getName());
System.out.println(T2.getName());

}
public void run() {
}

}
Output:
Thread names are following:
Thread1
Thread2

Inside run( ), we will define the code that constitutes the new thread. Example:

class MyClass implements Runnable {


public void run(){
System.out.println("MyClass running");
}
}

To execute the run() method by a thread, pass an instance of MyClass to a


Thread in its constructor:

public class ThreadingExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub Thread
t1 = new Thread(new MyClass()); t1.start();
}
}

When the thread is started it will call the run() method of the MyClass instance
instead of executing its own run() method.

Output: "MyClass running ".

By extending the Thread

The second way to create a thread is to create a new class that extends
Thread, then override the run() method and then to create an instance of that
class. The run() method is what is executed by the thread after you call
start(). Here is an example of creating a Java Thread subclass:
class MyThreadclass extends Thread{
public void run(){
System.out.println("My Thread Class running");
}
}

To create and start the above thread you can do so like this:

public class ThreadingExample2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
MyThreadclass t1 = new MyThreadclass();
t1.start();

}
}

Output: " MyClass running ".

Thread Class vs Runnable Interface


1. If we extend the Thread class, our class cannot extend any other class because
Java doesn’t support multiple inheritances. But, if we implement the Runnable
interface, our class can still extend other base classes.

class A1 {
public void f1() {
System.out.println();
}
}
public class ThreadingExample7 extends A1 implements Runnable{
public void run() {
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadingExample7 t = new ThreadingExample7();
t.f1();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}

2. We can achieve basic functionality of a thread by extending Thread class because


it provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.

Creating Multiple Threads

Thread(Runnable threadObj, String threadName);

class MyThread implements Runnable {


String name;
Thread t;
MyThread (String threadname){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t); t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + "Exiting.");
}
}

public class ThreadingExample3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
new MyThread("One"); new
MyThread("Two"); new
MyThread("Three"); try {
Thread.sleep(10000);
} catch (InterruptedException e) { System.out.println("Main
thread Interrupted");
}
System.out.println("Main thread exiting.");

}
Output:
New thread: Thread[One,5,main] New
thread: Thread[Two,5,main] New
thread: Thread[Three,5,main] One: 5
Two: 5
Three: 5
Three: 4
Two: 4
One: 4
Three: 3
Two: 3
One: 3
Two: 2
One: 2
Three: 2
Three: 1
One: 1
Two: 1
ThreeExiting.
OneExiting.
TwoExiting.
Main thread exiting.

Any application can have multiple processes (instances). Each of this


process can be assigned either as a single thread or multiple threads.

Multithreading in java is a process of executing two or more threads


simultaneously to maximum utilization of CPU.

Multithreaded applications are where two or more threads run concurrently;


hence it is also known as Concurrency in Java. This multitasking is done,
when multiple processes share common resources like CPU, memory, etc.
Each thread runs parallel to each other. Threads don't allocate separate
memory area; hence it saves memory. Also, context switching between
threads takes less time.
-----------------------------------------------------------------------
When we start two or more threads within a program, there may be a
situation when multiple threads try to access the same resource and finally
they can produce unforeseen result due to concurrency issues.

For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be
closing the same file.

In short when more than one thread try to access a shared resource, we
need to ensure that resource will be used by only one thread at a time. The
process by which this is achieved is called synchronization. The
synchronization keyword in java creates a block of code referred to as
critical section.

So there is a need to synchronize the action of multiple threads and make


sure that only one thread can access the resource at a given point in time.
This is implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one thread
at a time may hold a lock on a monitor.

Java programming language provides a very handy way of creating threads


and synchronizing their task by using synchronized blocks. You keep shared
resources within this block. Following is the general form of the synchronized
statement –
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}

Here, the objectidentifier is a reference to an object whose lock associates


with the monitor that the synchronized statement represents.

Multithreading Example without Synchronization

class PrintCounter {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter---"+ i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadCounter extends Thread {
private String threadName;
PrintCounter PC;
ThreadCounter(String name, PrintCounter pc) {
threadName = name;
PC = pc;
}

public void run() {

System.out.println("Starting -- " + threadName );


PC.printCount();
System.out.println("Thread --" + threadName + " exiting.");
}
}

public class ThreadingExample8 {

public static void main(String[] args) {


// TODO Auto-generated method stub
PrintCounter PCN = new PrintCounter();

ThreadCounter T1 = new ThreadCounter("Thread - 1", PCN );


ThreadCounter T2 = new ThreadCounter("Thread - 2", PCN );

T1.start();
T2.start();
}
}
OutPut:
Starting -- Thread - 1
Starting -- Thread - 2
Counter --- 5
Counter --- 5
Counter --- 4
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 3
Counter --- 1
Counter --- 2
Counter --- 1
Thread --Thread - 1 exiting. Thread
--Thread - 2 exiting.

Multithreading Example with Synchronization

class PrintCounter {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter---" + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadCounter extends Thread {
private String threadName;
PrintCounter PC;
ThreadCounter(String name, PrintCounter pc) {
threadName = name;
PC = pc;
}

public void run() {


synchronized(PC) {
System.out.println("Starting -- " +threadName );
PC.printCount();
}

System.out.println("Thread --" + threadName + " exiting.");


}
}

public class ThreadingExample8 {

public static void main(String[] args) {


// TODO Auto-generated method stub

PrintCounter PCN = new PrintCounter();

ThreadCounter T1 = new ThreadCounter("Thread - 1", PCN ); ThreadCounter


T2 = new ThreadCounter("Thread - 2", PCN );

T1.start();
T2.start();
}
}

Output:
Starting -- Thread - 1
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread --Thread - 1 exiting.
Starting -- Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread --Thread - 2 exiting.

Threading and Exception:

class mException extends Exception{


}
class MyThreading extends Thread {
public void run(){
try {
System.out.println("Throwing in " +"MyThreading");
throw new mException();
}catch(mException e) {
System.out.println("Caught it in MyThreading Exception");
}
}
}

public class ThreadingExample10 {

public static void main(String[] args) {


// TODO Auto-generated method stub
MyThreading t = new MyThreading();
t.start();
try { Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Caught it" + e);
}
System.out.println("Exiting main");
}
}
Output:
Throwing in MyThreading
Caught it in MyThreading
Exiting main
-----------------------------------------------------------------------------------------------

class MyClass extends Thread {


public void run()
{
try {
for (int i = 0; i < 5; i++) { System.out.println("Child Thread executing");

// Here current threads goes to sleeping state


// Another thread gets the chance to execute
Thread.sleep(1000);
}
}
catch (InterruptedException e) { System.out.println("Interruption occur");
}
}
}
public class ThreadingExample11 {

public static void main(String[] args) {


// TODO Auto-generated method stub
MyClass thread = new MyClass();
thread.start();

// main thread calls interrupt() method on child thread


thread.interrupt();

System.out.println("Main thread execution completes");


}

}
Output:
Main thread execution completes
Child Thread executing Interruption
occur

Stream Classes
In Java, a stream is a path along which the data flows. Every stream has a
source and a destination. We can build a complex file processing sequence
using a series of simple stream operations.
Two fundamental types of streams are Writing streams and Reading streams.
While a Writing streams writes data into a source (file), a Reading streams is
used to read data from a source (file).
Types of Streams
The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be
categorized into two groups based on the data type on which they operate.
Byte stream classes Character stream classes

A stream can be defined as a sequence of data. The InputStream is used to


read data from a source and the OutputStream is used for writing data to a
destination. InputStream and OutputStream are the basic stream classes in
Java.
All the other streams just add capabilities to the basics, like the ability to read
a whole chunk of data at once for performance reasons
(BufferedInputStream) or convert from one kind of character set to Java's
native unicode (Reader), or say where the data is coming from
(FileInputStream, SocketInputStream and ByteArrayInputStream, etc.) Byte
Streams

Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.

Some important Byte stream classes.


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java
standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are read() :
reads byte of data.
write() : Writes byte of data.

Following is an example which makes use of these two classes to copy an


input file into an output file –

import java.io.*;
public class fileIOExample1 {

public static void main(String[] args) throws IOException {


// TODO Auto-generated
method stub FileInputStream in
= null; FileOutputStream out =
null;
try {
in = new FileInputStream("input.txt");
out = new
FileOutputStream("output.txt"); int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch(IOException e) {
System.out.println("Something is
wrong");
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter. Though
internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that
FileReader reads two bytes at a time and FileWriter writes two bytes at a
time.

Some important Charcter stream classes.


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

We can re-write the above example, which makes the use of these two
classes to copy an input file (having unicode characters) into an output file –

import java.io.*;
public class fileIOExample2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are three popular methods to create file in java.

File.createNewFile()
java.io.File class can be used to create a new File in Java. When we initialize
File object, we provide the file name and then we can call createNewFile()
method to create new file in Java.

File createNewFile() method returns true if new file is created and false if file
already exists.
This method also throws java.io.IOException when it is not able to create the
file.
The files created is empty and of zero bytes.
When we create the File object by passing file name, it can be with absolute
path, or we can provide relative path.

For non-absolute path, File object tries to locate files in the project root
directory. If we run the program from command line, for non-absolute path,
File object tries to locate files from the current directory.

While creating the file path, System property file.separator used.

import java.io.File;
import java.io.IOException;
import java.io.*;
public class FileExample1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
try {
File file = new File("F:\\newfile.txt");
if (file.createNewFile())
System.out.println("File has been created successfully");
else
System.out.println("File already present at the specified
location");
//Write Content
FileWriter wrt = new FileWriter(file);
wrt.write("Test data");
wrt.close();
}catch(IOException e) {
System.out.println("IO Exception occured");
}
}
}

FileOutputStream.write(byte[] b)
If you want to create a new file and at the same time write some data into it,
you can use FileOutputStream write method. Below is a simple code snippet
to show it’s usage. The rules for absolute path and relative path discussed
above is applicable in this case too.

import java.io.*;
public class fileIOExample4{

public static void main(String[] args) throws IOException{


// TODO Auto-generated method
stub FileOutputStream fos = null;
FileInputStream fis = null;
byte b = 66;
int i = 0;
char c;

try {
// create new file output stream
fos = new FileOutputStream("F://test.txt");

// writes byte to the output stream


fos.write(b);

// flushes the content to the underlying


stream fos.flush();

// create new file input stream


fis = new FileInputStream("F://test.txt");

// read till the end of the file


while((i = fis.read())!=-1) {

// convert integer to character c


= (char)i;

// prints
System.out.print(c);
}
} catch(Exception ex) {
// if an error occurs
ex.printStackTrace();
} finally {
// closes and releases system resources from stream
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
}
}
}

Java NIO Files.write()


We can use Java NIO Files class to create a new file and write some data
into it. This is a good option because we don’t have to worry about closing IO
resources.

You might also like