0% found this document useful (0 votes)
255 views247 pages

Untitled

This document provides an overview of core Java topics and advanced Java concepts. It discusses the history and creation of Java, compares Java to C++, and describes the basic structure and components of a Java program. The key topics covered include data types, operators, I/O, basic programs, type casting, conditions, loops, arrays, functions, classes, inheritance, polymorphism, abstraction, encapsulation, packages, exception handling, and multithreading.

Uploaded by

K.Eshwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views247 pages

Untitled

This document provides an overview of core Java topics and advanced Java concepts. It discusses the history and creation of Java, compares Java to C++, and describes the basic structure and components of a Java program. The key topics covered include data types, operators, I/O, basic programs, type casting, conditions, loops, arrays, functions, classes, inheritance, polymorphism, abstraction, encapsulation, packages, exception handling, and multithreading.

Uploaded by

K.Eshwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 247

Java Topics(Core & Adv)

1.About java
2.Diff B/w C++ and Java
3.Structrure Of Java And Rules Of Java Lang
4.Data Types And Operators
5.I/O Operations
6.Basic Programs
7.Type Casting
8.Condetions Operations
9.Looping Operations
10.Array Concepts
11.Functions/Methods
12. Class
13.Inheritance
14.Polymorphism
15.Abstraction
16.Encapsulation
17. Packages
18.Exception Handling
19. Multithreading
20.Files
About Java:
In early 1980’s object oriented programming using C++
took hold. Indeed for a moment it seemed like
programmers had finally found the perfect language as C+
+. It blended the high efficiency and stylistic elements of C
with object oriented feature, it was a language that could be
used to create wide range of programs. Within a few years,
the world wide web and the internet would react critical
mass.

Creation of JAVA :

Java was conceived by James Ghosling, Patrick Naughton


and his team at Sun Micro System in 1991. This language was
initially called OAK language. But it was renamed as Java in
1995. The first public available version of Java (Java 1.0) was
released 1995. Over time several version of Java were release
which improved and enhanced the language and it libraries. The
current version of Java is Java 1.6 also known as Java 6.0.

Trees---oak
Oak------->Name of the tree----->Tea seeds
Java------>Name of the coffee seed
The original idea for java was not internet, instead the
primary motivation was the need for a platform
independent language that would be used to create software
to be embedded in various consumer electronic devices
such as microwave ovens and remote controls. The trouble
with C and C++ was that they were designed to be
compiled for a specific target. While it is possible to
compile a C++ program for just about any type of CPU to-
do so required a full C++ compiler targeted for the CPU.
The problem was that compilers are expensive then Gosling
and others begin work on a portable platform neutral
language that could be used to produce code that could be
run on various CPU’s under different environments. This
effort ultimately led for the creation of Java.

The second force was the World Wide Web(www). It is


an open ended information retrieval system designed to be
used in the internet distriubuted environment. It contains
web pages that provide both information and control. In
Web system we can navigate a document in any direction.
This is possible with the help of a language called as
HTML.
Web pages contain HTML tags that enable to find,
retrieve and display the documents on World Wide Web.
Before java ,world wide web was limited to display small
information and images. However the incorporation of java
into the web, the web pages has made it capable of
supporting animation, graphics, games and wide ranges of
special effects with the support of java.
1)Introduction to java:
Program:
Sequence of instructions that are needed to be executed in order to
get the output/result.

Purpose of writing a program:

1)To get the results in a faster manner.


2)To get the results in an accurate manner.
That means,we are writing programs in order to accomplish some task.
What might be the tasks for which we are writing code:
1)Performing basic operations(Addtion,subtraction,etc)
2)Generating a calculator------>Desktop application
3)Creating web pages----------->Web applicaions
Desktop application:
Source code will be in one system and output will be seen in same
system.
Web application:Source code will be in one system and output can be
seen in another system.
Java is used to develop both desktop and web applications.
Java Modules:
Java was divided into three modules:
-------J2SE(Java Standared Edition)/Core java/Desktop applications
-------J2EE(Java Enterprise Edition)/Ad java/Web application
-------J2ME(Java Micro Edition)/Mobile applications
Java was introduced by "Sun Micro Systems" in 1991.It was initially
called as "Oak" by James Gosling. Later it was renamed to Java.

Oak------->Name of the tree


Java------>Name of the coffee seed
In order to see the output of any program,we have to follow the
two step process.They are-----
1)Compilation
2)Execution
1)Compilation:
Converting high level code(code written by us) into machine
understandable code or binary code.
2)Execution:
Resolving the binary code step by step.
Difference between C++ and Java:

The difference between C++ and Java can be classified as

1. C++ features not supported by Java

1. The single important difference between java and C++ is java


doesn’t support pointers
2. Java doesn’t include structures and unions.
3. Java doesn’t supports operator overloading
4. Java doesn’t include pre-processor statements
5. Java doesn’t supports multiple inheritance
6. Java doesn’t allow goto statement
7. Java doesn’t have delete operator
8. In java objects are passed by reference only, where as in C+
+ objects may be passed by value or by reference.

2. Features added by Java

There are number of features in Java that have no equivalent in


C++

1. Multi threading allows two or more processes of the same


program to execute concurrently.

2. Java interfaces are somewhat similar to C++ abstract


classes.

3. There is no feature in C++ that directly corresponds to java


package

4. Java has a clear cut approach to memory allocation. Like


C++ it supports the “new” keyword as it does not have
“delete” keyword . Instead when the last reference to an
object is destroyed automatically using the
garbage collection.

4. Java contains built-in data types called “String”

5. When we create a C++ class, the access specifiers apply to a


group of statements .In java, access specifiers apply only at
the declarations.

1)Compilation:
Converting high level code(code written by us) into machine
understandable code or binary code.
2)Execution:
Resolving the binary code step by step.

Features:
1)Compiled and interpreted:
.java file on compilation produces .class file.(done by compiler)
.class file on Interpretation(Execution) produces .exe(ouput) file(done
by Java Virtual machine).
Hello.java---Hello.class--Hello.exe
2)Platform independent(OS):
We can write the source code in a system having one OS and we can
see the output in other system that have different OS.
3)Multi threaded and interactive:
To Perform more than one task simultaneously.
4)Extendible:To embed the code of native languages like c,cpp,etc into
our java
program and to run the java program.This can be done using Java
Native Interface(JNI).
5)Secure:
We can prevent our java programs from being interacted with the virus
present in the internet.Java is more secure than C.More no. of. security
checks will be there.Java is slower than C.Code for security will also be
included in java.
Security in java:
Sandbox model.
1)Class loader---------->Loads the class into the memory.
2)Byte code verifier------>Check will be performed before compilation
3)Security checker-------->Check will be performed before execution.
Java API---------->JDK+JSL
Any language will be released in the form of API.(All the
symbols,keywords,etc).
API-------->Application Programming Interface.
JDK------>Java Development Kit.Tools to develop java progs. are
present here.
Version: JDK1.10
JSL------>Java Standard Library.---->Set of predefined classes and
interfaces.
JRE------>Java Run Time Environment.Tools to execute or run a java
program.Examples----JVM,U I tool kits will be in this.
Java utilities:
javac---->java compiler
java----->Launches JVM
javah--->header file support
javap---->java dis-assembler
Steps for executing a java program:
1)Install Java Development Kit(JDK). 1.10
2)Set the path.
3)Take a notepad and wite the program.
4)Open command prompt and give compilation and execution -
commands.
cd Desktop
Command for compilation:
javac Filename.java
Command for Execution:
java Filename
Other Drive:
>D:
D:\>cd Swarupa
javac
java
Path:To show the location of .exe files to the OS.
Class Path:To show the location of .class files to the JVM.
To set the path:
rc
My Computer------------------->properties----->Advanced--->
Environmental variables------>User variables--->new--->
variable name:PATH
variable value:paste
ok----->ok----->ok.
C--->program files---->java---->jdk1.7------>bin------------->copy
Structure of a basic java program:
class ClassName
{
public static void main(String a[])
{
//Logic to be written;
}
}
First java program:
class Demo
{
public static void main(String a[])
{
System.out.println("welcome to java");
System.out.println("Hai");
}
}

main()------->Predefined function/method.Starting point of program


Execution
void---->main block is not going to return anything.
public----->To make main() accessible any where(through out the
program).
static------->To load main() first(Top priority in loading main()).
System-------->Predefined class.
To gain access over the system resources.
out------>Predefined object.(An object of PrintStream class).
To gain access over the output devices of the system.
Variable:Name of a memory cell is called as a variable.
To store the information,we will use this
Data types in java:

Data Types

Primitive Derived

class interface enum


Numeric Non-Numeric

Integer Floating-point character Boolean

Primitive Data Types

Java defines eight simple (or elemental) types of data: byte, short, int, long, char,
float, double, and boolean. These can be put in four groups:

■ Integers This group includes byte, short, int, and long, which are for whole
valued signed numbers.

■ Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.

■ Characters This group includes char, which represents symbols in a character


set, like letters and numbers.

■ Boolean This group includes boolean, which is a special type for representing
true/false values.
Integers

Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only
integers.

Name Width Range


long 64(8 bytes) –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32(4 bytes) –2,147,483,648 to 2,147,483,647
short 16(2 bytes) –32,768 to 32,767
byte 8(1 byte) –128 to 127

Floating-Point Types

Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. There are two kinds of floating-point
types, float and double, which represent single- and double-precision numbers,
respectively. Their width and ranges are shown here:

Name Width in Bits Approximate Range

double 64(8bytes) 4.9e–324 to 1.8e+308


float 32 (4bytes) 1.4e−045 to 3.4e+038

Characters

In Java, the data type used to store characters is char. However, C/C++
programmers beware: char in Java is not the same as char in C or C++. In C/C++,
char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java
uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages.
It is a unification of dozens of character sets, such as Telugu, Tamil, Hindi, Latin,
Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this
purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. There are no
negative chars.

char 16bits(2 bytes) 0 to 65,536

Boolean

Java has a simple type, called boolean, for logical values. It can have only one of
two possible values, true or false. This is the type returned by all relational
operators, such as a < b. boolean is also the type required by the conditional
expressions that govern the control statements such as if and for.

Variables
The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of an identifier, a type, and an optional initializer. In addition, all
variables have a scope, which defines their visibility, and a lifetime.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java’s atomic types(primitive data types), or the name of a class
or interface. The identifier is the name of the variable. You can initialize the
variable by specifying an equal sign and a value.

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Operators in java:
Note : If you are familiar with C/C++/C#, then you will be pleased to know that most
operators in Java work just like they do in those languages.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that

they are used in algebra. The following table lists the arithmetic operators:

Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
The Bitwise Operators

Java defines several bitwise operators which can be applied to the integer types,
long, int, short, char, and byte. These operators act upon the individual bits of
their operands. They are summarized in the following table:

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

The bitwise logical operators are &, |, ^, and ~. The following table shows the
outcome of each operation. In the discussion that follows, keep in mind that the
bitwise operators are applied to each individual bit within each operand.

A B A|B A&B A^B ~A


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

Relational Operators
The relational operators determine the relationship that one operand has to the
other. Specifically, they determine equality and ordering. The relational operators
are shown here:

Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

The outcome of these operations is a boolean value. The relational operators are
most frequently used in the expressions that control the if statement and the various
loop statements.

Boolean Logical Operators


The Boolean logical operators shown here operate only on boolean operands. All
of the binary logical operators combine two boolean values to form a resultant
boolean value.

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit Logical OR
&& Short-circuit Logical AND
! Logical unary NOT

Basic concepts of OOPS (or) Object Oriented Programming Principles:

Objects:

These are run time entities in an object oriented programming.


They may represent a person, a place etc of data or any item that
are program has to handle. They may also represent user defined
data

Classes:

We just maintained that objects contain data and code to


manipulate that data. The entire set of data and code of an object
can be made a user defined data type called class. Once a class has
been defined we can create any number of objects belongs to that
class.

Data Encapsulation and Abstraction:

1.Encapsulation:

It is mechanism that associates the code and the data


manipulations into a single unit and keeps them safe from external
interface. This is supported by a construct called “class”.
The use of encapsulation is to protecting the members of a
class, the data is not accessible to the outside class and only those
functions which are wrapped in a class can access it. This
installation of data from direct access by the program is called as
“data hiding”.

2.Abstraction:

The technique of creating new data types that are well suited to
an application is called “data abstraction”.
Data abstraction means you can combine the data structure and
the operations of data structure together into a new abstract data
type(ADT).
The ADT behaves just like data types, that are not a part of
language definition and they are created by the programmer.

Inheritance:
It is a mechanism which is used to extend the definition of an
existing class. The extension can be done by declaring some other
class. The class is originally present is called as “super class” and
the class which is extended with the help of inheritance is called
“sub class”. A sub class always can access the members of super
class, where as the super class never access the members of sub
class. The main purpose of inheritance is the reusability of
definition that are already made

Def: The Mechanism of deriving a new class from an old class is


called inheritance.

Polymorphism:

The word polymorphism derived from two Latin words poly


(many) and morphs(forms).
Polymorphism is nothing but the ability to access different
implementations of the function using the same name. there are
two levels at which polymorphism operates.
1. compile polymorphism
2. runtime polymorphism

Java Virtual Machine (JVM) :

When java software is installed in a particular machine, it constructs a


JVM for that operating system. It means JVM construction is depends
upon the operating system. In fact every operating system depends upon
hardware of the machine.

Here JVM acts as an interpreter between java program and


operating system. Actually JVM functionality is more than the
regular interpreter.JVM is complex structure which provides a
collection of registers, which capable to convert any java program
into machine executable programs. JVM accepts a java class file as
its input. (The java class file is produced as a result of java source
program compilation).

Java both Compile and Interpreted:

Generally computer programming languages are either compiled


or interpreted. But java combines both these approaches. Thus java
making two stage systems.

The first stage java compiler translates source code into a byte
code (class file). Byte codes are not machine instructions and
therefore the second stage java interpreter. It generates machine
code , that can be directly executed by the machine. Thus we can
say that java is both compile and interpreted language.

Java Architecture:

It is a set of softwares which allows a java programs to be executed on


any specified system.
Elements of java architecture.
1. java program
2. java classes
3. java API(application program interface)
4. JVM(java virtual machine)
5) Operating system & system Hardware

Java Runtime Environment(JRE)


Here,

Represents “request and response”

SDK: software development kit


JDK: Java development kit

Java program and java classes:

In C or C++, the source program is converted into machine code when it is


compiled. But in order to make java programming as machine independent
programming. Java program is not directly converted into machine code.
The source program is first converted into intermediate code called byte
code. This byte code is later converted into executable code, which is the
format of machine language.

Byte code : Byte code is sequence of bytes present in class file .since the
least addressable unit for any machine is byte. Byte code is universally
accessed all kinds of system.

JVM:
It s the main component of java architecture. It performs several rolls in
java programming. The main role of this is code interpretation. So it is
frequently referred as interpreter. JVM accepts byte code and it converts
into the machine executable code.

Java API:

In order to convert different functionalities of java byte code into


machine code, a set of java API functions are used. This API generally
called as JDK and SDK.

JRE:

It is a combination of JVM and java API. Java byte code conversion


and execution takes place in these two components with help of
operating system and system hardware.

Basic structure of Java program:

[Document section]

[Package statements]

Import statements

[Interface statements]
Class definition

Main method class

Document section:

It consists a set of comment lines giving the name of the program,


author name and other details about the entire program. This is optional
section.

Package statements:

It declares a package name and informs the compiler that the class
defined here belongs to this package. This is also optional section.

Import statements:

It is similar to “#include” statement in C or C++. It instructs the


interpreter to load the classes to contain the java package.

Interface statements:

An interface is like a class but it consists a group of method


declarations. It is same as abstract class in C++. This is also an optional
section.

Class definitions:

A java program may contain multiple class definitions. Classes are


the primary and essential elements of java program.

Main method class:

Since every java program requires a main method. This class is


essential part of java program. The main method creates objects of
various classes and establishes communication between them.

Rules for writing java programs:


1 It is case sensitive programming language.
2 The main method class name is recommended to be the name of
the java source file
3 Any java program contains only one public class is possible.
4 The main method class name is recommended to be a public class.

Package java.lang:

It provides classes that are fundamental to the design of


java programming. This package primarily deals with data types,
classes, objects, exceptions etc.

Package java.io:

It provides system input and output operations through data


streams and files streams.

Class System:

It is a predefined class, it belongs to java.io package. This


class contains several useful class fields and methods. This class
provides input and output services. It consists 3 fields called in,
out, and err. The field “in” for standard input stream, “out” for
standard output stream, and “err” for standard output error
stream. These are the static fields in this class.

The static fields are invoked directly with the help of class
name without declaring any object of the class.

Syntax: classname.fieldname

Java input and output:

Java supports string input and output operations only.

print / println:

It is used to print data on the standard output device. This


method belongs to standard output stream class.

Syntax:

print(data) or print(data-1+data-2+……+data-n);
or
println(data) or println(data -1+data-2+…………+data- n);

Example:

1. System.out.println(“welcome to java programming”);

2. int n=10;
System.out.println(“Value of n = “ + n);
Note:

This method accepts only one parameter. It is possible to


concatenate deferent data items with the help of operator”+”.
Here “+” is pre-defined overloaded operator.

Variable:

A quantity which may vary during the execution of a program is called as a


variable.

Java variables can be classified into 3 categories.

1) Local variables:

These variables are declared and used inside the methods. They are not
accessible outside the methods.

2) Instance variables:

The variables declared within the class are called as instance


variables. Because each instance of class(object) contains its own copy
of variable.

3) Class variables:

The variables that are common to all objects and accessed without
using a Particular object are called as class variables. These are declared
with the keyword “static”.

Program :- (datatypes.java)

import java.io.*;
class datatypes
{
public static void main(String args[])
{
byte b=100;
short s=3450;
int n=90000;
long l=999999;
char c=’r’;
float f=10.234f; // (or) float f=(float)10.234 //
double d=10234.7644;
System.out.println(“ byte =”+b);
System.out.println(“short =”+s);
System.out.println(“integer =”n+);
System.out.println(“long =”+l);
System.out.println(“char =”+c);
System.out.println(“float =”+f);
System.out.println(“double =”+d);
}
}

Note:

If doesn’t specify float f=10.1234f (or) float f=(float)10.234, the system will
considers it is a double value, and it will shows an error message.

found : double
required : float

Type Casting:
Converting one data type into another data type.
or
Assigning a value of one type to a variable of another type is known as
Type Casting.
int x = 10;
byte y = (byte)x;
Types:
1)Narrowing
2)Widening
1)Narrowing:
Converting larger datatype to smaller datatype is called as narrowing.
2)Widening:
Converting smaller datatype to larger datatype is called as widening.
Example 1:
class DatatypeCasting
{
public static void main(String arg[])
{
byte b;
int i = 81;
double d = 323.142;
float f = 72.38f;
char c = 'A';

c = (char) i;
System.out.println("i = " + i + " c = " + c);

i = (int) d; // LINE A
System.out.println("d = " + d + " i = " + i); // LINE B
i = (int) f; // LINE C
System.out.println("f = " + f + " i = " + i); // LINE D

}
}
OUTPUT
i = 81 c = Q
d = 323.142 i = 323
f = 72.38 i = 72
Example2:
class ImplicitTypeCasting
{
public static void main(String aa[])
{
long a=2;/*long to int*/
System.out.println(a);
}
}output:2
/*Widining*/
class ExplicitTypeCasting
{
public static void main(String aa[])
{

System.out.println("The result is:"+(5/2));//2


System.out.println("The result is:"+(float)5/2);/*int to float */
System.out.println("The result is:"+(char)65);
}
}
output:
The result is:2
The result is:2.5
The result is:A

To accept input from the user:


1)Scanner class
2)BufferedReader class
3)DataInputStream class

Using Scanner class:

/*
package java.util;
class Scanner-->sc
{
public void nextInt()
{
}
public void nextFloat()
{
}
public void nextDouble()
{
}
public void nextLine()
{

}
*/
Program:
import java.util.Scanner;

class inp1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Scanner sc1=new Scanner(System.in);//Create an extra object for
//accepting a string

System.out.println("Enter your age");//28


int age=sc.nextInt();
System.out.println("Your age is:"+age);
System.out.println("Enter your gender:");//F
char gender=sc.next().charAt(0);
System.out.println("Your gender is:"+gender);
System.out.println("Enter your salary:");//6.6
float salary=sc.nextFloat();
System.out.println("Your salary is:"+salary);
System.out.println("Enter your name:");//pinky
String name=sc.nextLine();
System.out.println("Your name is:"+name);
}
}
}
Using BufferedReader class:
/*
package io;
class BufferedReader--br
{
public void readLine()
{
}
}
*/
import java.io.*;
class buf
{
public static void main(String a[])
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your name:");//Pinky
String name=br.readLine();
System.out.println("Your name is:"+name);
System.out.println("Enter your age:");//"28"
//String to integer
int age=Integer.parseInt(br.readLine());
System.out.println("Your age is:"+age);
System.out.println("Enter your gender");//"f"
char gender=(char)br.read();
System.out.println("Your gender is:"+gender);
System.out.println("Enter your salary:");//"6.6"
float salary=Float.parseFloat(br.readLine());
System.out.println("Your salary is:"+salary);
}
}
Using DataInputStream class:
class DataInputStream:

A DataInputStream lets an application, to read primitive java data


types from an underlying InputStream in a machine independent way.

Constructor:
DataInputStream(InputStream in)
Creates a DataInputStream object(Instance)that uses the specified
underlying InputStream.

Methods:

read:
public int read() throws IOException
It reads a single character from standard input device. It is returned as
an integer in the range of 0 to 255.

readLine:

public String readLine() throws IOException


It reads a group of characters from standard input device and it
returns a String object.

skip:

public long skip(long n) throws IOException


It skips specified number of bytes from standard input stream.

IOException:

Java provides certain exceptions to handle its error situation.


IOException is one, it occurs during an IO operation. So it is
compulsory to throw this exception.

Program :- (read1.java)

import java.io.*;
class read1
{
public static void main(String args[]) throws IOException
{
char ch;
String st;
DataInputStream dis=new DataInputStream(System.in);
System.out.print(“Enter any character:”);
ch=(char)dis.read();
dis.skip(2);
System.out.print(“Enter any string:”);
st=dis.readLine();
System.out.println(“Given character:”+ch);
System.out.println(“Given string:”+st);
}
}

class Integer:
The Integer class wraps a value of primitive type int, in a object.

Methods:

parseInt():

public static int parseInt(String s)


It parses the string argument as a signed decimal integer.

class Float:

The Float class wraps a value of primitive type int, in a object.

Methods:

parse Float ():

public static float parseFloat (String s)


It returns a new float initialized to the value represented by the specified
string.

Program :- (read2.java)

import java.io.*;
class read2
{
public static void main(String args[]) throws Exception
{
int n;
float f;
DataInputStream dis=new DataInputStream(System.in);
System.out.print(“enter any number:”);
n=Integer.parseInt(dis.readLine());
System.out.print(“enter any floatr:”);
f=Float.parseFloat(dis.readLine());
System.out.println(“Given number:”+n);
System.out.println(“Given float:”+f);
}
}

class InputStreamReader:

It is a bridge from byte streams to character streams. It reads bytes and decodes
them into character using a specified charset.

Constructor:

InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.

class BufferedReader:

It reads text from a character InputStream, buffering characters so as to provide for


the efficient reading of characters, arrays and lines.

Constructor:

BufferedReader(Reader in)
Creates a buffering character InputStream that uses default-sized input buffer.

Program :- (read3.java)

import java.io.*;
class read3
{
public static void main(String args[]) throws Exception
{
int n;
float f;
char c;
String s;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(br);
System.out.print(“enter any integer : “);
n=Integer.parseInt(br.readLine());
System.out.print(“enter any float : ”);
F=Float.parseFloat(br.readLine());
System.out.print(“enter any character : “);
c=(char)br.read();
System.out.print(“enter any string : “);
s=br.readLine();
System.out.println(“integer is : “ +n);
System.out.println(“float is : “ +f);
System.out.println(“character is : “ +c);
System.out.println(“string is : “ +s);
}
}
Program : ao.java

Program to read 2 numbers from the keyboard and to display their addition,
subtraction, multiplication, division and modulus.

import java.io.*;
class ao
{
Public static void main(String args[]) throws Exception
{
int a,b,add,sub,mul,div,mod;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print(“enter first number : “);
a=Integer.parseInt(br.readLine());
System.out.print(“enter second number : “);
B=Integer.parseInt(br.readLine());
add=a+b;
sub=a-b;
mul=a*b;
div=a/b;
mod=a%b;
System.out.println(“addition = “+add);
System.out.println(“subtraction = “+sub);
System.out.println(“multiplication = “+mul);
System.out.println(“division = “+div);
System.out.println(“modulus = “+mod);
}
}

Program : swap.java

Program to read 2 numbers from the keyboard and to swap the given number by
using a temporary variable.

import java.io.*;
public static void main(String args[])
{
class swap
{
int a,b,t;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print(“enter first number : “);
a=Integer.parseInt(br.readLine());
System.out.print(“enter second number : ”);
b=Integer.parseInt(br.readLine());
t=a;
a=b;
b=t;
System.out.prinln(“swapped numbers”);
System.out.prinln(“a = “+a);
System.out.prinln(“b = “+b);
}
}

Program : swap2.java

Program to read 2 numbers from the keyboard and to swap the given number
without using a temporary variable.
import java.io.*;
public static void main(String args[])
{
class swap2
{
int a,b;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print(“enter first number : “);
a=Integer.parseInt(br.readLine());
System.out.print(“enter second number : ”);
b=Integer.parseInt(br.readLine());
a=a+b;
b=a-b;
a=a-b;
System.out.prinln(“swapped numbers”);
System.out.prinln(“a = “+a);
System.out.prinln(“b = “+b);
}
}

import java.io.*;
class buf
{
public static void main(String a[])
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println("Enter your name:");//Pinky
String name=br.readLine();
System.out.println("Your name is:"+name);
System.out.println("Enter your age:");//"28"
//String to integer
int age=Integer.parseInt(br.readLine());
System.out.println("Your age is:"+age);
System.out.println("Enter your gender");//"f"
char gender=(char)br.read();
System.out.println("Your gender is:"+gender);
System.out.println("Enter your salary:");//"6.6"
float salary=Float.parseFloat(br.readLine());
System.out.println("Your salary is:"+salary);
}
}

Command Line Arguments

Argumets that are passed in the same line where the execution
command is given are called as Command Line Arguments.

(or)
The java command-line argument is an argument i.e. passed at the time
of running the java program.
The arguments passed from the console can be received in the java
program and it can be used as an input.So, it provides a convenient way
to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Purpose:
This is generally used for testing our applications with different test
cases.
Example 1:
class cla
{
public static void main(String ar[])
{
int a=Integer.parseInt(ar[0]);
int b=Integer.parseInt(ar[1]);
int c=a+b;
System.out.println("The sum is:"+c);
}
}
output:
javac cla.java
java cla 2 3
The sum is:5
ar
2
3
Example 2:
class cml
{
{
public static void main(String a[])
{
System.out.println("Your first arg is:"+a[0]);
}
}
javac cml.java
java cml 23 hello

Example 3:
class cml
{
public static void main(String a[])
{
for(int i=0;i<a.length;i++)
{
System.out.println("The args are:"+a[i]);
}
}
}
javac cml.java
java cml hello hai 22 42 ok bye

a
0-hello
1-hai
2-22
3-42
4-ok
5-bye

Conditions:
Depending on the condition,we will decide wether to execute or skip
a set of instructions.

1)if (pure if):

Syntax:

------------
-------------
------------
-------------
if(condition)
{
-----------
-----------
}
------------
-------------

class Demo
{
public static void main(String a[])
{
int a=13,b=13;

if(a==b)
{
System.out.println("They are equal");
}

System.out.println("I am the last");

}
}

2)if-else:
----
----
if(condition)
{
------
------
}
else
{
------
------
------
}
---
---

Code:

class Demo
{
public static void main(String a[])
{
int a=16,b=26;

if(a==b)//
{
System.out.println("They are equal");

}
else
{
System.out.println("They are not equal");
}
System.out.println("I am the last");
}
}

3)if-else-ladder/if-else-if:
Syntax:

if(condition)
{
//1
}
else if(condition)
{
//2
}
else if(condition)
{
//3
}

else if(condition)
{
//4
}

else
{
//5
}
----------------
----------------
Code:
class ladder
{
public static void main(String a[])
{
int avg=76;
if(avg>=90)
{
System.out.println("Grade A");
}
else if(avg>=75)
{
System.out.println("Grade B");
}
else if(avg>=60)
{
System.out.println("Grade C");
}
else if(avg>=40)
{
System.out.println("Grade D");
}
else
{
System.out.println("Failed---Waste fellow");
}
//................
}
----
---
}
}
Nested if:
Nesting:One with in another.
syntax:

if(condition)
{
---------
---------
---------
if(condition)
{
---------------
--------------------

}
else
{

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

}
----------------------
----------------------
}
else
{
----------------
----------------
----------------

Switch case:

Switch(var_name)
{
Case exp1:
Stat1;
Break;
Case exp2:
Stat2;
Break;
--
--
--
Default:
Final stat;
}

Loops:

If you want to repeatedly execute a set of statements,you can use


loops.
Types:
1)for
2)while
3)dowhile

=======for===========
----
----

for(initialization;condition;incrementation)
{
-----
-----
}

---
---

To print "Hello" for 5 times


class Demo
{
public static void main(String a[])
{

int i;
for(i=1;i<=5;i++)
{
System.out.println("Hello");
}

}//main
}//class

i--->6

Hello
Hello
Hello
Hello
Hello

class Demo
{
public static void main(String a[])
{

int i;
for(i=1;i<=5;i++)
{
System.out.println(i);//1 2
}

}//main
}//class

i-->1
=====Decrementation==========
for(i=10;i>=0;i--)
{
sop(i);
}
output:
10 9 8 7 6......0
========while======
initialization;
while(condition)
{
---
---
incremetation;
}

Example:
To print 1 to 5 nos. using while loop.
class loop
{
public static void main(String a[])
{
int i=1;
while(i<=5)
{
System.out.println(i);//1 2 3 4 5
i++;//3
}
}
}

=======do-while========
initialization;
do
{
-----
-----
incre/decre;
}while(condition);

Example:
class DoDemo
{
public static void main(String a[])

{
int i=1;
do
{
System.out.println(i);//1 2 3
i++;//4
}while(i>=5);

i--->1

======break====
for(i=0;c;incre)
{
--
--
--
continue;<--------------
--
--
-

------

=========break===============
As soon as the cursor encounter the break
keyword,it will skip all the statements
after "break" and exits(comes out) of that
block in which break is written.
for(i;c;i)
{
-----
-----
----
-----
if(a>10)
{
continue;
}
-----
-----
}
-----
-----
continue:
As soon as the cursor encounter the continue
keyword,it will skip all the statements
after continue and it will directly be
going to the 4th part(incrementation)
of the loop.

=========goto============
Used to skip the required instructions
------
------
------
goto label-name;
-------
-------
-------
label:
-------
-------
-------

------
------
------
goto pinky;
-------
-------
-------
pinky:
-------
-------
-------

class Demo
{
public static void main(String a[])
{
int n=4;
if(n%2==0)
{
goto even;
}
else
{
goto odd;
}

odd:
System.out.println("The number is odd");

even:
System.out.println("The number is even");

=========Nested loops========
class Demo
{
public static void main()
{
int r,c,sum;
for(r=1;r<=3;r++)
{
for(c=1;c<=2;c++)
{
sum=r+c;
System.out.println(r+" "+c+" "+sum);
}
}
}
}

Arrays:
Array is a collection of homogeneous/similar datatype elements sharing
a common name.Array in java is index based, first element of the array
is stored at 0 index.
Advantage of Java Array:
Code Optimization: It makes the code optimized, we can retrieve or
sort the data easily.Random access: We can get any data located at any
index position.
Disadvantages:
We can store homogeneous values only.
Size Limit: We can store only fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in java.
Types:
There are two types of array.
1)Single Dimensional Array
2)Multidimensional Array
Single Dimensional Array in java:
Syntax to Declare an Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in java:
arrayRefVar=new datatype[size];
Example of single dimensional java array:
Let's see the simple example of java array, where we are going to
declare, instantiate, initialize and traverse an array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Test it Now
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Test it Now
Output:33
3
4
5
Passing Array to method in java:
We can pass the java array to method so that we can reuse the same
logic on any array.
Let's see the simple example to get minimum number of an array using
method.
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Test it Now
Output:3
Multidimensional array in java:
In such case, data is stored in row and column based index (also known
as matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print
the 2Dimensional array.
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Test it Now
Output:1 2 3
245
445
What is the class name of java array?
In java, array is an object. For array object, an proxy class is created
whose name can be obtained by getClass().getName() method on the
object.

class Testarray4{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}
}
Test it Now
Output:I
Copying a java array:
We can copy an array to another by the arraycopy method of System
class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length )
Example of arraycopy method
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Test it Now
Output:caffein
Addition of 2 matrices in java
Let's see a simple example that adds two matrices.
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Test it Now
Output:2 6 8
6 8 10
Program to accept elements from the user and storing them in an array
and also to display the elements out of an array:
import java.util.Scanner;
class Array1
{
public static void main(String args[])
{
int a[]=new int[10];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements you want to store
into the array");
int n=sc.nextInt();
System.out.println("Enter the " +n+ " values");
for(i=0;i<n;i++)
{
//System.out.println("Enter the values:");
a[i]=sc.nextInt();
}
System.out.println("The array elements are:");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Output:
Enter the number of elements you want to store into the array
6
Enter the 6 values
1
2
3
4
5
6
The array elements are:
1
2
3
4
5
6
To print the elements out of an array using enhanced for loop/for each
loop:
class Demo
{
public static void main(String aa[])
{
int a[]=new int[5];
a[0]=10;
a[2]=30;
a[4]=40;
for(int result:a)
{
System.out.println(result);
}
}
}
output:
10
0
30
0
40
Functions/Methods:
Self contained block of statements that can be used any no. of. times
any where in the program.
Parts:
1)Function declaration
ReturnType FunctionName();

2)Function call
FunctionName();

3)Function definition
ReturnType FunctionName()
{

}
modifier - It defines the access type of the method and it is optional to
use.
returnType - Method may return a value.
nameOfMethod - This is the method name. The method signature
consists of the method name and the parameter list.
Parameter List - The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method may
contain zero parameters.
method body - The method body defines what the method does with
the statements.
Example:
Basic program:
class functions1
{
public static void main(String a[])
{
System.out.println("I am from main()");
italy();
System.out.println("I have executed italy");
brazil();
System.out.println("I have executed brazil");
argentina();
System.out.println("I have executed argentina");
}
static void italy()
{
System.out.println("I am from italy");
}
static void brazil()
{
System.out.println("I am from brazil");
}
static void argentina()
{
System.out.println("I am from argentina");
}
}
Function call in the function definition:
class functions1
{
public static void main(String a[])
{
System.out.println("I am from main()");
italy();
System.out.println("I have executed italy");
}
static void italy()
{
System.out.println("I am from italy");
brazil();
System.out.println("I have executed brazil");
}
static void brazil()
{
System.out.println("I am from brazil");
}
}
Parameter:
Extra information passed through a function call to a function definition
is called as parameter.
Parameter passing techniques to a function:

1)Call by value:
We will call the function(definition) by passing values.
class functions3
{
public static void main(String args[])
{
int a=2,b=3,sum;
sum=calsum(a,b);//5
System.out.println("The result is:"+sum);
}
static int calsum(int x,int y)
{
int w;
w=x+y;
return w;
}
}
Example 2:
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Example 3:
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5)
{
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
This will produce the following result -
Output:
Rank:A1
Example 4:
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will
be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
Function recursion:
A function calling itself is called as recursion.
Example 1:
public class Recursion {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
Example 2:
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Object Oriented Programming System:


Object Oriented Programming system is a programming approach
where a given task/problem is divided into no.of. objects and we
establish communication among the objects to fulfil the task.
or
Object-oriented programming (OOP) is a programming paradigm based
on the concept of "objects", which may contain data, in the form of
fields, often known as attributes; and code, in the form of procedures,
often known as methods. A feature of objects isthat an object's
procedures can access and often modify the data fields of the object
with which they are associated (objects have a notion of "this" or
"self"). In OOP, computer programs are designed by making them out
of objects that interact with one another.
There is significant diversity of OOP languages, but the most popular
ones are class-based, meaning that objects are instances of classes,
which typically also determine their type.Many of the most widely used
programming languages (such as C++, Object Pascal, Java, Python etc.)
are multi-paradigm programming languages that support object-
oriented programming to a greater or lesser degree, typically in
combination with imperative,procedural programming. Significant
object-oriented languages include Java, C++, C#, Python, PHP, Ruby,
Perl, Object Pascal,Objective-C, Dart, Swift, Scala, Common Lisp, and
Smalltalk.Pure object oriented programming language is "small talk".
Java oops concepts:
Object means a real word entity such as pen, chair, table etc. Object-
Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Description:

Object:
Any entity that has state and behavior is known as an object. For
example: chair, pen, table, keyboard, bike etc. It can be physical and
logical.

Class:
Collection of properties/variables and/or behaviours/methods.
or
Collection of objects is called class. It is a logical entity.

Inheritance:
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used
to achieve runtime polymorphism.

Polymorphism:
When one task is performed by different ways i.e. known as
polymorphism.
For example: to convince the customer differently, to draw something
e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog
barks woof etc.
Abstraction:
Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.
In java, we use abstract class and interface to achieve abstraction.

7)Encapsulation:
Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with
different medicines.

A java class is the example of encapsulation. Java bean is the fully


encapsulated class because all the data members are private
here.

Advantage of OOPs over Procedure-oriented programming language:

1)OOPs makes development and maintenance easier where as in


Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented
programming language a global data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more
effectively. We can provide the solution of real word problem
if we are using the Object-Oriented Programming language.

What is an object-based programming language?


Object based programming language follows all the features of OOPs
except Inheritance. JavaScript and VBScript are examples of object
based programming languages.

A language is said to be object oriented if everything(the entire code) is


implemented in the form of classes and objects.
java--more oops bcoz main() should be written inside the class.
cpp--less oop bcoz main() should be written outside the class.

Java is only 99% pure object oriented because it supports primitive data
types(int,float,char,etc)and it supports the concept of
static members(that can be called without objects).

Java is slower than C because of code for security is also existed in java.
Program using OOPS:
Class syntax:
class classname
{
<access-specifier> type instance-variable1;
<access-specifier> type instance-variable2;
// ...
<access-specifier> type instance-variableN;

<access-specifier> type methodname1(parameter-list)


{
// body of method
}
<access-specifier> type methodname2(parameter-list)
{
// body of method
}
// ...

<access-specifier> type methodnameN(parameter-list) {


// body of method
}
}
The data, or variables, defined within a class are called instance
variables. The code is contained within methods. Collectively, the
methods and variables defined within a class are called members of
the class.
Approach1:

class Student
{
int rollno,age;
void join()
{
System.out.println("Going to join Qshore");
}
public static void main(String a[])
{
Student d=new Student();//d---->object
d.rollno=101;
d.age=20;
System.out.println(d.rollno+" "+d.age);//10 20
d.join();
}
}

output:

10 20
Going to join Qshore

Approach2:

class Student
{
int rollno,age;
void join()
{
System.out.println("Going to join Qshore");
}
}
class FinalDemo
{
public static void main(String a[])
{
Student d=new Student();//d---->object
d.rollno=101;
d.age=20;
System.out.println(d.rollno+" "+d.age);//10 20
d.join();
}
}

Constructors:
Constructor in java is a special type of method that is used to initialize
the object.
Java constructor is invoked at the time of object creation. It constructs
the values i.e. provides data for the object that is why it is known as
constructor.
Rules for creating java constructor:
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
Parameterless constructor (no-arg constructor)
Parameterized constructor
Syntax:
class_name()
{

}
Rule: If there is no constructor in a class, compiler automatically creates
a default constructor.
Parameterless constructor Example 1:
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Default constructor provides the default values to the object like 0, null
etc. depending on the type.
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so
compiler provides you a default constructor.Here 0 and null
values are provided by default constructor.

Example 2:
class cons
{
int width;
int height;
int depth;
cons()
{
width=10;
height=10;
depth=10;

}
public void display()
{
System.out.println("The area is:"+width*height*depth);
}
}
class consdemo
{

public static void main(String a[])


{
cons cs=new cons();
cs.display();
}
}
stack heap
cs--->w=10
h=10
d=10
Parameterized constructor:
Java parameterized constructor:
A constructor that have parameters is known as parameterized
constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the
distinct objects.
Example of parameterized constructor:
In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
222 Aryan
Example 2:
class cons
{
int width;
int height;
int depth;
cons(int w,int h,int d)//class type is the implicit return type of the
constructor
{
width=w;
height=h;
depth=d;
}
public void display()
{
System.out.println("The area is:"+width*height*depth);
}
}
class consdemo
{
public static void main(String a[])
{
cons cs1=new cons(5,6,7);
cons cs2=new cons(3,2,1);
cs1.display();
cs2.display();
}
}
Realtime example:
Have you used mould anytime which we generally use to make some
small shapes with POP or some times with clay? Most of us must have
used it during art and craft work done in our school. Now you can
consider a mould as a class which makes objects for you.
Now it has some predefined properties for your object like height of
your object width of your object , height or width of a particular part of
your object . This is what exactly your Java constructor does in Java for
you it assign some predefined values to your objects . Now you can
change a height or length of a particular part of your object by covering
that very part of your mould with some thing like we use sand some
time to make some change in object shape along with POP, This can be
considered as Constructor with parameters or constructor overloading
is in Java.
Another Good real world example of Java. constructor is your Ice tray
which you keep in refrigerator you must have seen the ice trays of
different shape and once you put water into it . It produces ice cubes
exactly of same height and length every time.
You can consider your ice tray as class and your ice cubes as your
objects of that particular class . So your objects are getting some
predefined values for properties like Height , length, breadth etc. Now
if you want to make a parameterised constructor you can add some
colored syrup to water to make ice cubes of different colors. This is
what we do in Constructors with parameters in Java .

Advantages of Constructors:
A constructor eliminates placing the default values.
A constructor eliminates calling the normal method implicitly.
OVERLOADED CONSTRUCTORS:
class over
{
over()
{
System.out.println("I am a default constructor");
}
over(float a,int b)
{
System.out.println("The area is:"+a*b);
}
over(int a)
{
System.out.println("The value is:+a);
}
over(int a,int b,int c)
{
System.out.println("The area is:+ a*b*c);
}
}
class overdemo
{
public static void main(String a[])
{
over o1=new over();
over o2=new over(4);
over o3=new over(2.3f,5);
over o4=new over(1,2,3);
}
}
Advantage:
If we want to construct an object in different way then we need
constructor overloading.

15)Destructor:
This is used to deallocate the resources acquired by the object during
its life cycle.
stack heap
cs1----->w=10
h=10
d=10

finalize()--------->To call the destructor

16)Java Garbage Collection:


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically.
In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C+
+. But, in java it is performed automatically. So, java provides better
memory management.
Advantage of Garbage Collection:
It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
By nulling the reference
By assigning a reference to another
By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage
collection
3) By annonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
protected void finalize()
{
}
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword.
So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc()
{
}
Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC). This thread calls the finalize() method before
object is garbage collected.

Simple Example of garbage collection in java


public class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Test it Now
object is garbage collected
object is garbage collected
Garbage collector:
This will remove the object from the memory.
System.gc();========>To call the garbage collector thread
8)Encapsulation:
Encapsulation in java is a process of wrapping code and data together
into a single unit, for example capsule i.e. mixed of severalmedicines.
We can create a fully encapsulated class in java by making all the data
members of the class private. Now we can use setter and getter
methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.

Real Time example of Encapsulation:


The best example of car driving, car driver knows how to start car by
pressing start button. The driver doesn't know what happened inside
when pressing start button. Here the starting process is hidden from
driver. So this process can be called as “starting process is encapsulated
from driver”

Advantages of Encapsulation:
- The main advantage of Encapsulation is, when using objects, the
object need not reveal all its attributes and behaviors.
- Code changes can be made independently
- Increases usability

Disadvantages of Encapsulation:
- The main drawback or disadvantage of encapsulation is that it relies
heavily on standards to maintain readability
It provides you the control over the data. Suppose you want to set the
value of id i.e. greater than 100 only, you can write the
logic inside the setter method.
class Encap-->oe
{
private int a=2,b=3;
void display()
{
System.out.println("Hello from Encap class");
}
}
class owncap
{
public static void main(String a[])
{
Encap oe=new Encap();
//oe.a=10;//a is the private member of Encap
//oe.b=20;
oe.display();//diplay is the private member of Encap

}
}
Example 2:
//save as Student.java
package com.Qshore;
public class Student{
private String name;

public String getName(){


return name;
}
public void setName(String name){
this.name=name
}
}
//save as Test.java
package com.Qshore;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
9)Inheritance:
Deriving a new class from the existing class so that
the new class have its own qualities and also the
qualities acquired from the parent class.That means.....
Inheritance allows a class to use the properties and methods of another
class.
In other words, the derived class inherits the states and behaviors from
the base class.
The derived class is also called subclass and the base class is also known
as
super-class. The derived class can add its own additional variables and
methods.
These additional variable and methods differentiates the derived class
from the base
class.Inheritance is a compile-time mechanism. A super-class can have
any number of
subclasses. But a subclass can have only one superclass. This is because
Java does
not support multiple inheritance.

The superclass and subclass have “is-a” relationship between them.


Let’s have a look
at the example below.
Example:
Let’s consider a superclass Vehicle. Different vehicles have different
features and properties however there few of them are common to all.
Speed, color, fuel used, size are few which are common to all. Hence
we can create a class ‘Vehicle’ with states and actions that are common
to all vehicles. The subclass of this super class can be any type of
vehicle.
Example:
Class Car A has all the features of a vehicle. But it has its own attributes
,which makes it different from other subclasses. By using inheritance
we need not rewrite the code that we’ve already used with the
Vehicle. The subclass can also be extended. We can make a class ‘Sports
Car’ which extends ‘Car’. It inherits the features of both ‘Vehicle’ and
‘Car’.

The keyword used for inheritance is extends.


Syntax:
public class ChildClass extends BaseClass
{

}
Types:
Single----->One child for one parent(Base,Super).
Hierarchical----->More than one children for one parent
Multilevel--------->child--parent--grand father relationship
Multiple-------->Not supported in java directly.(Only through interfaces).
hybrid----->Combination of two inheritences(Not supported).

Single Inheritence:
Example 1:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Example 2:
class A
{
void displayA()
{
System.out.println("Hello from A");
}

}
class B extends A
{
void displayB()
{
System.out.println("I am from B");
}
public static void main(String[] args) {
B si=new B();
si.displayA();
si.displayB();
}
}
Overriding :

If members are declared with the same name both in super class and sub class, a
sub class object always gives preference to the sub class members, by overlooking
the super class members. Hence it is called as overriding.
Super : It is a keyword which is used in subclasses only.

Uses :

1) It is used to access overridden members in super class from sub class.

Syntax : super.member;

Program : inh3.java

import java.io.*;
class supercls
{
int n;
void accept() throws IOException
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
}
void disp()
{
System.out.println(n);
}
}
class sub extends supercls
{
void accept() throws IOException
{
super.accept();
} overriding(both method names are same)
void disp()
{
super.disp();
}
}
public class inh3
{
public static void main(String args[]) throws IOException
{
sub s=new sub();
System.out.print("Enter value of n : ");
s.accept();
System.out.print("Given value of n : ");
s.disp();
}
}

Uses :

2) Using super keyword to call super call constructor.A sub class constructor
can call constructor method defined by its super class by use of following
form of super.

Syntax : super ([parameter_list]);

Note :

1. super([parameter_list]) must be used in sub class constructor.


2. super([parameter_list]) must always be the first statement executed
inside a sub class constructor.

.
Program : inh4.java)

import java.io.*;
class supercls
{
int n;
supercls()
{
n=100;
}
void disp()
{
System.out.println(n);
}
}
class sub extends supercls
{
int n;
sub()
{
super();
n=200;
}
void disp()
{
System.out.print("Data in Super Class Member : ");
super.disp();
System.out.println("Data in Sub Class Member : "+n);
}
}
public class inh4
{
public static void main(String args[])
{
sub s=new sub();
s.disp();
}
}

Program : inh5.java

import java.io.*;
class supercls
{
int n;
supercls(int x)
{
n=x;
}
void disp()
{
System.out.println(n);
}
}
class sub extends supercls
{
int n;
sub(int a,int b)
{
super(a);
n=b;
}
void disp()
{
System.out.print("Data in Super Class Member : ");
super.disp();
System.out.print("Data in Sub Class Member : "+n);
}
}
public class inh5
{
public static void main(String args[])
{
sub s=new sub(100,200);
s.disp();
}
}

final :

It is a keyword and in java it is available as :


1. final variables
2. final methods
3. final classes

final variables :

A variable can be declared as final, it cannot be modified. final variable is similar


to constants in C and CPP. So the final variable must be initialized when it is
declared.

Program : final_var.java
class finalcls
{
final int n=100;
void setdata(int x)
{
//n=x;  cannot be modified hence ignore this line
}
void disp()
{
System.out.println(n);
}
}
public class final_var
{
public static void main(String args[])
{
finalcls f=new finalcls();
System.out.print("Initial Data in Object : ");
f.disp();
f.setdata(200);
System.out.print("Changed value in Object :" );
f.disp();
}
}

If we declare the variable n without the keyword final, the value of n can be
modified and we will get the output as :

Initial Data in Object : 100


Changed Data in Object : 200

But here we have declared the variable n as final, we cannot change the value of n
during the execution of the program and we will get an error message as “ cannot
assign a value to variable n “. Hence ignore n=x.
Now the output will be :

Initial Data in Object : 100


Changed Data in Object : 100
If we declare any variable with the keyword final, its value cannot be modified
during the execution of the program.

final methods :

All methods can be override by default in sub classes. If we wish to prevent in the
sub class from overriding the members of super class, we declare them as final
methods using final keyword.

Program : final_met.java)

import java.io.*;
class supercls
{
int n;
final void accept() throws IOException
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
}
final void disp()
{
System.out.println(n);
}
}

class sub extends supercls


{
/* void accept()
{
accept();
}
void disp()
{
disp();
} */
void input() throws IOException
{
accept();
}
void output()
{
disp();
}
}
class final_met
{
public static void main(String args[]) throws IOException
{
sub s=new sub();
System.out.print("Enter data in the object : ");
s.input();
System.out.print("Data in the object : ");
s.output();
}
}

Here we have declared the 2 methods in super class with the keyword final, hence
we can extend the methods in sub class, but we cannot override them (methods of
sub class and super class must not be same), hence use different method names in
sub class and with the help of those methods we can access the methods of super
class. If we attempt to override the methods the compiler will display the error
message as :
accept() in sub cannot override accept() in super class, overridden method is
final.

final class :

Sometimes we want to prevent a class being inherited. To do this, preceed the class
declaration with the final keyword.

Program : final_cls.java

import java.io.*;
final class supercls
{
int n;
void accept() throws IOException
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
}
void disp()
{
System.out.println(n);
}
}
class sub extends supercls
{
void accept() throws IOException
{
super.accept();
}
void disp()
{
super.disp();
}
}
public class final_cls
{
public static void main(String args[]) throws IOException
{
sub s=new sub();
System.out.print("Enter data in the object : ");
s.accept();
System.out.print("Data in the object : ");
s.disp();
}
}
If we execute the above program the compiler will display the error message
as : cannot inherit from final supercls class sub extends supercls, this is because
we have declare the super class supercls as final, hence we cannot inherit this class
in any other classes.
Multi level inheritance :

The mechanism of extending a class from another sub class is called as multi level
inheritance.

Program : minh.java

import java.io.*;
import java.text.*;
class student
{
int sno;
String sname;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
void accept() throws IOException
{
System.out.print("Enter Stduent Number : ");
sno=Integer.parseInt(br.readLine());
System.out.print("Enter Student Name : ");
sname=br.readLine();
}
void disp()
{
System.out.println("Stduent Number : "+sno);
System.out.println("Stduent Name : "+sname);
}
}
class marks extends student
{
int c,cpp,java;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
void accept() throws IOException
{
super.accept();

c=Integer.parseInt(br.readLine());
System.out.print("Enter Marks in CPP : ");
cpp=Integer.parseInt(br.readLine());
System.out.print("Enter Marks in Java : ");
java=Integer.parseInt(br.readLine());
}
void disp()
{
super.disp();
System.out.println("Marks in C : "+c);
System.out.println("Marks in CPP : "+cpp);
System.out.println("Marks in Java : "+java);
}
}
class result extends marks
{
int tot;
float avg;
String res,div;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
void accept() throws IOException
{
super.accept();
tot=c+cpp+java;
avg=(float)tot/3;
if(c>=50 && cpp>=50 && java>=50)
{
res="PASS";
if(avg>=60)
div="FIRST";
else
div="SECOND";
}
else
{
res="FAIL";
div="NO DIVISION";
}
}
void disp()
{
super.disp();
NumberFormat nf=NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
System.out.println("Total Marks : "+tot);
System.out.println("Average Marks : "+avg);
System.out.println("Result : "+res);
System.out.println("Division : "+div);
}
}
public class minh
{
public static void main(String args[]) throws IOException
{
char ch;
result r=new result();
do
{
r.accept();
r.disp();
System.out.print("Do u want to continue (y or n) : ");
ch=(char)System.in.read();
System.in.skip(2);
}
while(ch=='y');
}
}

Hierarchical Inheritance :

A super class with several sub classes is called as hierarchical inheritance.

-----------

Program : hinh.java

import java.io.*;
class supercls
{
int x;
}
class sub1 extends supercls
{
int y;
sub1(int a,int b)
{
x=a;
y=b;
}
void disp()
{
System.out.println("Data in super class from sub1 : "+x);
System.out.println("Data in sub class - 1 : "+y);
}
}
class sub2 extends supercls
{
int z;
sub2(int a,int b)
{
x=a;
z=b;
}
void disp()
{
System.out.println("Data in super class from sub2 : "+x);
System.out.println("Data in sub class - 2 : "+z);
}
}
public class hinh
{
public static void main(String args[])
{
sub1 s1=new sub1(100,200);
s1.disp();
sub2 s2=new sub2(300,400);
s2.disp();
}
}

Abstract class :

A class can be declared as an abstract class in order to prevent accessing members


of the class directly. We cannot create an object of the abstract class.

Purpose :

These are declared as a model definition. An abstract class in not used directly for
representing any object, but it can be used for the declaration of several sub class
by creating abstract class as a super class.

Program : abstcls.java

import java.io.*;
abstract class abst
{
void disp()
{
System.out.print("WELCOME");
}
}
/*
public class abstcls
{
public static void main(String args[])
{ not possible
abst a=new abst();
a.disp();
}
}
*/
If we run the above program, the compiler will displays the error message as:-
abst is abstract, cannot be instantiated
Because we cannot create object directly for the abstract class. Also we can extend
the abstract class in other class, hence by extending abstract class in some other
class, we can access the members of the abstract class. Hence extend the abstract
class abst in abst1, and hence we can access the members of abst.

Program : abstcls.java

import java.io.*;
abstract class abst
{
void disp()
{
System.out.print("WELCOME");
}
}

class abst1 extends abst


{
}
public class abstcls
{
public static void main(String args[])
{
abst1 a=new abst1();
a.disp();
}
}

Abstract methods :

A function can also be declared as an abstract. An abstract method is not having


body.

Purpose :

Although an abstract method is not provided body, it gives a uniform name and
that name can be used in sub classes.

Program : abstmet.java

import java.io.*;
abstract class ari
{
abstract void compute(int x,int y);
}
class add extends ari
{
void compute(int x,int y)
{
System.out.println("Addition : "+(x+y));
}
}
class sub extends ari
{
void compute(int x,int y)
{
System.out.println("Subtraction : "+(x-y));
}
}
public class abstmet
{
public static void main(String args[]) throws IOException
{
int a,b;
ari r;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Enter 2 numbrs : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
r=new add();
r.compute(a,b);
r=new sub();
r.compute(a,b);
}
}

Multiple Inheritence(Not supported):


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 timeerror if
you inherit 2 classes. So whether you have same method or different,
there will be compile time error now.

Program:
class A{
void msg()
{
System.out.println("Hello");
}
}
class B{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B
{//suppose if it were

public Static void main(String args[])


{
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Compile Time Error
Hybrid inheritence:
public class A
{
public void methodA()
{
System.out.println("Class A methodA");
}
}
public class B extends A
{
public void methodA()
{
System.out.println("Child class B is overriding inherited method
A");
}
public void methodB()
{
System.out.println("Class B methodB");
}
}
public class C extends A
{
public void methodA()
{
System.out.println("Child class C is overriding the methodA");
}
public void methodC()
{
System.out.println("Class C methodC");
}
}
public class D extends B, C
{
public void methodD()
{
System.out.println("Class D methodD");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodD();
obj1.methodA();
}
}
Output:
Error!!
Why? Most of the times you will find the following explanation of
above error – Multiple inheritance is not allowed in java so class D
cannot extend two classes(B and C). But do you know why it’s not
allowed? Let’s look at the above code once again, In the above program
class B and C both are extending class A and they both have overridden
the methodA(), which they can do as they have extended the class A.
But since both have different version of methodA(), compiler is
confused which one to call when there has been a call made to
methodA() in child class D (child of both B and C, it’s object is allowed
to call their methods), this is a ambiguous situation and to avoid it, such
kind of scenarios are not allowed in java. In C++ it’s allowed.
What’s the solution? Hybrid inheritance implementation using
interfaces.

interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
Output:
MethodA
MethodB
MethodC
Note: Even though class D didn’t implement interface “A” still we have
to define the
methodA() in it. It is because interface B and C extends the interface
A.The above code would work without any issues and that’s how we
implemented hybrid inheritance in java using interfaces.

Real Time Example:


The real time example for Inheritance is “parent child relationship”.
Because child receives all the property from parent.
Advantages of Inheritance:
- Inheritance is the process of object reusability
- Inheritance reduce code redundancy
- Inheritance reduce the size of program code
- Inheritance helps in adding additional features to an existing class
without modifying it

Disadvantages of Inheritance:
- In the concept of Inheritance , Both child class and parents class are
tightly coupled. If you modify the program code in parent
class then all child classes are effected, because those child classes are
inheriting from parent class.

Variables:
Instance Variables (default)
static Variables
final Variables
instance varaibles:
The variables are by default instance.For each and every
instance(object) of a class,a separate copy of instance variables is
available.To access an instance variable or an instance method,an
object must be created for the class in which this instance variables and
methods are present.
Example:
int a;//a is an instance variable by default.
static varaibles:
Only one copy of static variables have to be shared by all the
instances(objects) of a class because only one copy of static variables
will be created in the memory.(Loaded only for once)To access a static
variable or a static method,no need for us to create an object for the
class in which this variable or method is present.We can directly access
them using the class name.

Ways to access the static members:


object.variable/method name
classname.variable/method name
variable/method name(direct without preceeding by anything)

final keyword:
final variables:
A variable which is preceeded by the final keyword is called a final
variable.
A final variable's value can never be changed i.e., it becomes a
constant.
Example:
final int a=10;//Value of "a" cannot be changed furthur.
A final method can never be overriden.
A final class can never be inherited.
local variables:
A variable defined inside a block is known as a local variable.
Constructors:
Constructor in java is a special type of method that is used to initialize
the object.
Java constructor is invoked at the time of object creation. It constructs
the values i.e. provides data for the object that is why it is known as
constructor.
Rules for creating java constructor:
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
Parameterless constructor (no-arg constructor)
Parameterized constructor
Syntax:
class_name()
{

}
Rule: If there is no constructor in a class, compiler automatically creates
a default constructor.
Parameterless constructor Example 1:
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Default constructor provides the default values to the object like 0, null
etc. depending on the type.
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so
compiler provides you a default constructor.Here 0 and null
values are provided by default constructor.

Example 2:
class cons
{
int width;
int height;
int depth;
cons()
{
width=10;
height=10;
depth=10;

}
public void display()
{
System.out.println("The area is:"+width*height*depth);
}
}
class consdemo
{

public static void main(String a[])


{
cons cs=new cons();
cs.display();
}
}
stack heap
cs--->w=10
h=10
d=10
Parameterized constructor:
Java parameterized constructor:
A constructor that have parameters is known as parameterized
constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the
distinct objects.
Example of parameterized constructor:
In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
222 Aryan
Example 2:
class cons
{
int width;
int height;
int depth;
cons(int w,int h,int d)//class type is the implicit return type of the
constructor
{
width=w;
height=h;
depth=d;
}
public void display()
{
System.out.println("The area is:"+width*height*depth);
}
}
class consdemo
{
public static void main(String a[])
{
cons cs1=new cons(5,6,7);
cons cs2=new cons(3,2,1);
cs1.display();
cs2.display();
}
}
Realtime example:
Have you used mould anytime which we generally use to make some
small shapes with POP or some times with clay? Most of us must have
used it during art and craft work done in our school. Now you can
consider a mould as a class which makes objects for you.
Now it has some predefined properties for your object like height of
your object width of your object , height or width of a particular part of
your object . This is what exactly your Java constructor does in Java for
you it assign some predefined values to your objects . Now you can
change a height or length of a particular part of your object by covering
that very part of your mould with some thing like we use sand some
time to make some change in object shape along with POP, This can be
considered as Constructor with parameters or constructor overloading
is in Java.
Another Good real world example of Java. constructor is your Ice tray
which you keep in refrigerator you must have seen the ice trays of
different shape and once you put water into it . It produces ice cubes
exactly of same height and length every time.
You can consider your ice tray as class and your ice cubes as your
objects of that particular class . So your objects are getting some
predefined values for properties like Height , length, breadth etc. Now
if you want to make a parameterised constructor you can add some
colored syrup to water to make ice cubes of different colors. This is
what we do in Constructors with parameters in Java .

Advantages of Constructors:
A constructor eliminates placing the default values.
A constructor eliminates calling the normal method implicitly.
OVERLOADED CONSTRUCTORS:
class over
{
over()
{
System.out.println("I am a default constructor");
}
over(float a,int b)
{
System.out.println("The area is:"+a*b);
}
over(int a)
{
System.out.println("The value is:+a);
}
over(int a,int b,int c)
{
System.out.println("The area is:+ a*b*c);
}
}
class overdemo
{
public static void main(String a[])
{
over o1=new over();
over o2=new over(4);
over o3=new over(2.3f,5);
over o4=new over(1,2,3);
}
}
Advantage:
If we want to construct an object in different way then we need
constructor overloading.
this and super keywords:
this keyword:
1)Compiler passes reference to the current
object being used,which is known as "this".
2)If the instance variables and formal parameters have the same
name,then we have to preceed the instance variables using "this"
keyword.
3)If the instance variables and formal parameters have different
names,then the compiler will implicitly preceeds the instance variables
with "this" keyword.
4)This is used to call the current class members
(methods,constructors,variables...)

this before instance variables:


class cons
{
int w;.
int h;
int d;

cons(int w,int h,int d)//class type is the implicit return type of the
constructor
{
this.w=w;
this.h=h;
this.d=d;
}
public void display()
{
System.out.println("The area is:"+w*h*d);
}
}
class consdemo
{
public static void main(String a[])
{
cons cs1=new cons(5,6,7);
cons cs2=new cons(3,2,1);
cs1.display();
cs2.display();
}
}
"this" to call a method of current class:
class A
{
public static void main(String a[])
{
A a=new A();
a.methodTwo();
}
void methodOne()
{
System.out.println("Inside the method one");
}
void methodTwo()
{
System.out.println("Inside the method two");
this.methodOne();
}
}
this to call the constructor of current class:
class A
{
A()
{
this("Hai");//this();
System.out.println("Inside the parameterless constructor");
}
A(String str)//Hai
{
System.out.println("Inside the parameterized constructor:"+str);
}
public static void main(String a[])
{
A a=new A();
//A a1=new A("Hai");
}
}
Restrictions:
1)"this" and "super" keywords...when used in a constructor
must be the first statements.
2)"this" and "super" keywords cannot be used with static
members.
super keyword:
Used to call the super class members(variables
,methods,constructors) from with in the sub class.

Normal program:
class one
{
int i=10;
void show()
{
System.out.println("super class method:"+i);
}
}
class two extends one
{
int i=20;//Field shadowing--Parent and child classes will have the
variable
//with same name
void show()
{
System.out.println("sub class method:"+i);
}
}
class sdemo
{
public static void main(String a[])
{
two t=new two();
t.show();
/*One o=new One();
o.show();*/
}
}
calling variables and methods of super class:
class one
{
int i=10;
void show()
{
System.out.println("super class method:"+i);
}
}
class Two extends one
{
int i=20;
void show()
{

System.out.println("sub class method:"+i);//20


super.show();
System.out.println("super class i:"+super.i);//10
}
}
class super2
{
public static void main(String a[])
{
Two t=new Two();
t.show();
}
}
Calling super class constructor:
class one
{
int i;//11
one(int i)//11
{
this.i=i;//11
}
}
class two extends one
{
int i;//22
two(int a,int b)//11,22
{
super(a); //super(11);
i=b;//22
}
}
void show()
{
System.out.println("sub class i:"+i);//22
System.out.println("super class i:"+super.i);//11
}
}
class super3
{
public static void main(String a[])
{
two t=new two(11,22);
t.show();
}
}
Limitations:
1)this and super keywords cannot be used with static.
2)this and super, if used in a constructor,should
be the first statement(s).
15)Destructor:
This is used to deallocate the resources acquired by the object during
its life cycle.
stack heap
cs1----->w=10
h=10
d=10

finalize()--------->To call the destructor


16)Java Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically.
In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C+
+. But, in java it is performed automatically. So, java provides better
memory management.

Advantage of Garbage Collection:


It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
By nulling the reference
By assigning a reference to another
By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage
collection
3) By annonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
protected void finalize()
{
}
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword.
So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc()
{
}
Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC). This thread calls the finalize() method before
object is garbage collected.

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Test it Now
object is garbage collected
object is garbage collected
Garbage collector:
This will remove the object from the memory.
System.gc();========>To call the garbage collector thread
Packages:

A package is a group of classes and interfaces. It is like a header file in C or CPP


language. Logically a package maps to a directory of an operating system.
Packages are stored in hierarchical manner and they are explicitly imported to a
new class definitions.

Definiting a package :

To create a package, include a package command as the first statement in the java
source file. Any class declared within this file will belongs to the specified
package.
The general form of package statement is :
package package_name;

Eg : package pack;

Here pack is the name of the package. Java uses file system directories to
store packages.

Example :

The class file for any class is declared to be part of pack, the class file must be
stored in a directory called pack. We can create hierarchy of packages, to do so
simply separated by dot(.)

Syntax : package pack.pack_1.pack_2.pack_3;

Accessing package using fully qualified class name :

Program : pktest.java

package pack;
import java.io.*;
class cls
{
void disp()
{
System.out.print("WELCOME");
}
}
public class pktest
{
public static void main(String args[])
{
cls c=new cls();
c.disp();
}
}

To compile the package :

E:\raji\java\programs > javac –d . filename.java

Eg : E:\raji\java\programs > javac –d . pktest.java

To execute the package :

E:\raji\java\programs > java package_name.class_filename

Eg : E:\raji\java\programs > java pack. pktest

Note :

Here the package pack is created as a directory in our home directory and the
classes are saved in that package directory.
To verify this, go to the home directory and give the command dir/p, this
command will display all the files on our directory by page wise. In that our
directory will exists. Then again go to that directory and verify whether the classes
exists or not.

Eg : E:\raji\java\programs > dir/p


E:\raji\java\programs > cd pack
E:\raji\java\programs\pack > In that class files exists.

General form of import statement :

Syntax 1 : (Explicit import )

import package_name.class_name;
or
import packagename_1.packagename_2………packagename_n.class_name;

Syntax 2 : (Implicit import )

import package_name.*;
or
import packagename_1.packagename_2………packagename_n.*;

Here package name may denote a single package and * indicates that the
compiler should search the entire package. This means we can access all classes
contained in that package directly.

Classpath :

It is an environmental variable that determine where the JDK tools such as java
compiler and interpreter search for class files. It contains an ordered sequence of
directories as well as .jar and .jif files. It is an important to have the class path
variable set correctly when working with packages.
On a Windows platform user may set the value of an environment variable
by typing command such as :
set classpath = path
Eg :

set classpath = E:\raji\java\programs ( this command will erase the previous path
and sets the above path.

set classpath = %classpath%; E:\raji\java\programs

To display the path : E:\raji\java\programs > echo %classpath%


Creating and importing the package :

This process consists of 2 steps.

1. Creating a new package or Creating a class in already created package.


2. Importing the package in another package.

1. Creating a class in already created package :

Package name : pack

(cls1.java )

package pack;
import java.io.*;
public class cls1
{
public void disp()
{
System.out.print("My Package");
}
}

To compile the package :

E:\raji\java\programs > javac –d . filename.java

Eg : E:\raji\java\programs > javac –d . cls1.java

2. Importing the package :

(pktest2.java)

import java.io.*;
import pack.cls1;
public class pktest2
{
public static void main(String args[])
{
cls1 c1=new cls1();
c1.disp();
}
}

1. Creating sub package in already created package :

Package name : pack1

(cls2.java )

package pack.pack1;
import java.io.*;
public class cls2
{
public void display()
{
System.out.print("Welcome to Java Sub Package");
}
}

2. Importing the package :

(pktest3.java)

import java.io.*;
import pack.pack1.cls2;
public class pktest3
{
public static void main(String args[])
{
cls2 c2=new cls2();
c2.display();
}
}

1. Creating a package :
Package name : input

(datainput.java )

package input;
import java.io.*;
public class datainput
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));

public int readint() throws Exception


{
int n;
n=Integer.parseInt(br.readLine());
return n;
}
public char readchar() throws Exception
{
char c;
c=(char)br.read();
br.skip(2);
return c;
}
public float readfloat() throws Exception
{
float f;
f=Float.parseFloat(br.readLine());
return f;
}
public String readstring() throws Exception
{
String s;
s=br.readLine();
return s;
}
}

2. Importing the package :


(pktest4.java)

import java.io.*;
import input.datainput;
class pktest4
{
public static void main(String args[]) throws Exception
{
int n;
char c;
float f;
String s;
datainput d=new datainput();
System.out.print("Enter an Integer : ");
n=d.readint();
System.out.print("Enter a Float : ");
f=d.readfloat();
System.out.print("Enter a Character : ");
c=d.readchar();
System.out.print("Enter a String : ");
s=d.readstring();
System.out.println("Given Integer : "+n);
System.out.println("Given Float : "+f);
System.out.println("Given Character : "+c);
System.out.println("Given String : "+s);
}
}

1. Creating a package :

Package name : mypack

Creating more than one public class is not possible in java program. If we want to
create more than one class in the same package, we should create 2 public classes
separately i.e. write 2 java programs seperately, and import the package(with more
than one class) in other program.

(cl1.java )
package mypack;
import java.io.*;
public class cl1
{
public void disp()
{
System.out.println("Class-1");
}
}

(cl2.java )

package mypack;
import java.io.*;
public class cl2
{
public void disp()
{
System.out.println("Class-2");
}
}

2. Importing the package :

(pktest5.java)

import java.io.*;
import mypack.*;
class pktest5
{
public static void main(String args[])
{
cl1 c1=new cl1();
cl2 c2=new cl2();
c1.disp();
c2.disp();
}
}
In old Java compilers i.e. in JDK1.3, before executing this type of programs, first
we should set the class path at the command prompt as :

E:\raji\java\programs > SET CLASSPATH = E:\raji\java\programs

To see the path :

E:\raji\java\programs\> echo %classpath%

(Or)
Set the class path permanently in Environment Variables of MyComputer.

In the latest versions of Java compilers, we need not set the class path. But, if we
directly execute the above program in our own directory, the compiler will displays
an error message as : “ File does not contain class cl1. Please remove or make
sure it appears in the correct subdirectory of the class path “
i.e. to execute this type of programs, delete the classes that we are importing in the
package (cl1 and cl2) from our own directory ( E:\raji\java\programs ) and copy
these files (cl1 and cl2) in the package directory (mypack), and then execute the
program.

Exception Handling :

An exception is an abnormal condition that arises in a code sequence at run time.


Some computer languages that doesnot support exception handling. Errors must be
checked and handled manually, but java’s exception handling avoid these
problems.
Exception is an error state, it occurs during the execution of an instruction in a
program. For an exception occurs generally the system may be in any one of the
following states.
1. Unstable or hang
2. System may went into a infinite loop
3. Breaking the execution of an application by showing an error message

But because of these states of a system, it is not possible to execute any application
properly. So when an exception occurs it is possible to raise an exception by the
system and when an exception is raised a set of instructions will be executed and
these instructions are referred as exception handler.
Java exception handling managed via 5 keywords. They are :
1. try
2. catch
3. throw
4. throws
5. finally

System generated exceptions are automatically thrown by the java runtime system.
If an exception occurs within a try block, it is thrown, your code can catch this
exception. To manually thrown an exception we use the keyword throw. Any
exception that is thrown out of the method, we must specify throws. The finally
block will execute whether or not an exception occurs.

1. try :

It is used to write instructions which are having a chance to raise exception.

Syntax :

try
{
statements
}

2. catch :

It is used to write exception handler which consists a set of instructions which are
required to execute in response to the error condition.

Syntax :

catch (exception_type obj)


{
Statements
}

3. throw :
when an exception that is decided to be handle is detected, it is thrown using the
throw statement.

Syntax : throw throwable instance;

4. throws:

It is used to thrown exceptions outside the method.

Syntax : throws exception_type

return_type func_name([argument_list])throws exception_type


{
statements;
}

5. finally :

It creates a block of code that will be executed after try or catch block has
completed.

Syntax :
finally
{
statements;
}

Exception types :
All exceptions are the sub classes of the class exception, and exception is sub class
of class throwable.

Exception type Description


ArithmeticException Arithmetic operations

ArrayIndexOutOfBoundsException Array index out of bounds

ArrayStroreException Assignment to an incompatible data type

ClassCastException Invalid casting

NullPointerException Invalid use of null pointer

ClassNotFoundException Attempt to create an object of abstract


class or interface

IOException Data input and output operations

getMessage() :

It is a method that belongs to throwable class. It returns a description of the


exception.

Syntax : String getMessage();

Program : excp1.java

import java.io.*;
public class excp1
{
public static void main(String args[])
{
int n;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
try
{
System.out.print("Enter value of n : ");
n=Integer.parseInt(br.readLine());
System.out.println("Value of n : "+n);
}
catch(Exception e)
{
System.out.println("User Message : "+"Input Error");
System.out.println("System Message : "+e.getMessage());
}
}
}

Output

Enter value of n : 100


Given value : 100

If we give an integer value for n, the compiler will execute the try block, if there is
no error in the try block the compiler will not execute catch block and terminates
the program.

Otherwise if gives some other value(other than integer), i.e. there is error in try
block, hence the compiler will goes to catch block and executes the statements of
catch block and the output will be :

Enter value of n : RAJI


User Message : Input Error
System Message : For Input String “RAJI”

Program : excp2.java

import java.io.*;
public class excp2
{
public static void main(String args[])
{
int n;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
try
{
System.out.print("Enter value of n : ");
n=Integer.parseInt(br.readLine());
System.out.println("Value of n : "+n);
}
catch(Exception e)
{
System.out.println("User Message : "+"Input Error");
System.out.println("System Message : "+e.getMessage());
}
finally
{
System.out.println(“Program is terminated”);
}
}
}

If the program does not having finally block and if there is any error in try block,
then the program will be terminated without executing any other statements. If
there is finally block in our program, and if there is any error in the try block, in
this situation the program will not be terminated and the compiler will execute the
statements of finally block then only the program will be terminated. Hence the
main usage of finally block is in case of data base oriented programs, some
connections are opened in try blocks and if there is any errors the program will be
terminated and the connections remains opened and cause some connection errors.
Hence we will write the coding for the closing of data base connections in the
finally block, then if there is any error in try block, the compiler will execute the
finally block and hence it will close all the opened data base connection and then
only come out from the program.

Output

1) Enter value of n : 100


Given value : 100
Program is terminated

2) Enter value of n : RAJI


User Message : Input Error
System Message : For Input String “RAJI”
Program is terminated
Program : excp3.java

import java.io.*;
public class excp3
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
try
{
System.out.print("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a/b;
System.out.println("Division Value : "+c);
}
catch(ArithmeticException ae)
{
System.out.println("User Message : "+"Division Error");
System.out.println("System Message : "+ae.getMessage());
}
}
}

Output

1) Enter 2 values : 10 3
Division Value : 3

2) Enter 2 values : 10 0
User Message : Division Error
System Message : \ by zero

Program : excp4.java
import java.io.*;
class excp4
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
int a[]=new int[5];
int i,n;
System.out.print("Enter number of Elements : ");
n=Integer.parseInt(br.readLine());
try
{
System.out.println("Enter array elements : ");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("Given array elements : ");
for(i=0;i<n;i++)
{
System.out.println("a["+i+"] : "+a[i]);
}
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("User Message : "+"Array Index Exceeds");
System.out.println("System Message : "+ae.getMessage());
}
}
}

Throwing the exception manually :

Program : excp5.java)

import java.io.*;
public class excp5
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.println("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
if(b==0)
throw new ArithmeticException("Error in Dividing With Zero");
c=a/b;
System.out.println("Division : "+c);
}
catch(ArithmeticException ae)
{
System.out.println(ae.getMessage());
}
}
}

Creating instance for ArithmeticException class

Here we are throwing the exception manually, if there is any message in the
instance of ArithmeticException (“Error in Dividing with Zero”), we will get the
error message as “null”, i.e. here user is throwing the exception.

Rethrowing the exception :

If there are any functions in main() function and if there is any exception in
function block, we have to throw that exception also from the main() function. This
is possible by rethrowing the exception of function block to main() function block.

Program : excp6.java

import java.io.*;
public class excp6
{
static float division(int x,int y)
{
float d;
try
{
if(y==0)
throw new ArithmeticException();
d=(float)x/y;
}
catch(ArithmeticException ae)
{
System.out.println("Error in Function Block");
throw ae; // rethrowing the exception //
}
return d;
}
public static void main(String args[]) throws IOException
{
int a,b;
float c;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.println("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=division(a,b);
System.out.println("Division : "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Division Error");
}
}
}

Multiple catch :

Program : excp7.java
import java.io.*;
public class excp7
{
public static void main(String args[])
{
int a,b,c;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.println("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a/b;
System.out.println("Division : "+c);
}
catch(NumberFormatException ne)
{
System.out.println("Invalid Data");
}
catch(IOException ie)
{
System.out.println("Input Error");
}
catch(ArithmeticException ae)
{
System.out.println("Division Error");
}
}
}

Output

1) Enter 2 values :
20
2

Division : 10
2) Enter 2 values :
20
0

Division Error

3) Enter 2 values :
R

Invalid Data

Nested try :

The try statements can be nested i.e. a try statement can be used inside another try.

Program : excp8.java

import java.io.*;
public class excp8
{
public static void main(String args[])
{
int a[]=new int[5];
int n,i;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.print("Enter number of elements : ");
n=Integer.parseInt(br.readLine());
try
{
System.out.println("Enter Elements : ");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("Given Elements : ");
for(i=0;i<n;i++)
{
System.out.println("a["+i+"] : "+a[i]);
}
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("Array Index Outof Bounds");
}
}
catch(IOException ie)
{
System.out.println("Input Error");
}
catch(NumberFormatException ne)
{
System.out.println("Invalid Data");
}
}
}

Output

1) Enter number of elements : 5


Enter elements : 1
2
3
4
5
Given elements : 1 2 3 4 5

2) Enter number of elements : 6


Enter elements : 1
2
3
4
5
6
Array Index out of bounds

3) Enter number of elements : R


Invalid Data

Creating our own Exception :

Although java’s build in exception handles most common errors. We will probably
want to create our own exception type to handle situation specific to our
application. This is quite easy to do, just define a sub class of exception (which is
ofcourse a sub class of throwable ). Our subclass need to implement anything.

Program : excp9.java

import java.io.*;
class MyException extends Exception
{
public MyException() our own Exception
{
super("Error Occured");
}
} refers to super class constructor ( Exception )
public class excp9
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.println("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
if(b==0)
throw new MyException();
c=a/b;
System.out.println("Division : "+c);
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
}
}

Output

1) Enter 2 values :
20
2

Division : 10

2) Enter 2 values :
20
0

Error Occurred

Program : excp10.java

import java.io.*;
class MyException extends Exception
{
public MyException(String st)
{
super(st);
}
}
public class excp10
{
public static void main(String args[])
{
int a,b,c;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try
{
System.out.println("Enter 2 values : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
if(b==0)
throw new MyException("Division Error");
c=a/b;
System.out.println("Division : "+c);
}
catch(IOException ie)
{
System.out.println("Input Error");
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
}
}

Output

1) Enter 2 values :
20
2

Division : 10

2) Enter 2 values :
20
0

Division Error

Multithreading :

Thread :
A way to execute set of instructions in a program is called as thread.
Unlike most computer languages, java provides built in support for
multithreading programming. A multi threaded program consists 2 or more parts
that can run concurrently. Each part of such a program is called thread and each
thread defines a separate part of execution. Multithreading allows us to write very
efficient programs. The java runtime system depends on threads for many things
and all of the class libraries are designed with multithreading.

Main thread:

When a java program startsup, i.e.already one thread is running, this is usually
called main thread of our program.

Life cycle of a thread :

Thread moves several states from its creation to its ultimate death. These states
are :

1. New state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

new thread
stop()

start()

active thread

stop()
stop()
suspend() resume()
sleep()

1 ) new state :

A thread is in the new state, immediately it is created. At this stage we can do the
following things.
1. Schedule it for running using start() method
2. Kill it using stop() method

2) runnable state :

It means thread is ready for execution and it is waiting for the availability of the
processor. i.e. the thread has joined in the queue of threads that are waiting for
execution.

3) running state :

It means the processor has given its time to the thread for its execution.

4) blocked state :

A thread is set to the blocked state, when it is prevented from entering into the
runnable state and subsequently in running state.

5) dead state :

A running thread ends its life at any state, we can kill it using stop() method.

Fields :
1) static int MAX_PRIORITY :
The maximum priority that a thread can have.

2) static int MIN_PRIORITY :


The minimum priority that a thread can have.

3) static int NORM_PRIORITY :


The default priority that is assigned to the thread.

Note :

In java priorities are given from 1 to 10


Max priority : 10
Min priority : 1
Default priority : 5

Constructors :

1) Thread :
Allocates a new thread object.

2) Thread(Runnable target) :
Allocates a new thread object.

3) Thread(Runnable target,String name) :


Allocates a new thread object.

4) Thread(String name) :
Allocates a new thread object with specified name.

Methods :

1) static Thread currentThread() :


Returns a reference to the currently executing Thread object.

2) void destroy() :
Destroys this thread, without any cleanup.

3) String getName() :
Returns this thread’s name.

4) int getPriority() :
Returns this thread’s priority number.

5) void interrupt() :
Interrupts this thread.

6) static Boolean interrupted() :


Tests whether the current thread has been interrupted.

7) boolean isAlive() :
Tests if this thread is alive.

8) boolean isInterrupted() :
Tests whether this thread has been interrupted.

9) void join() :
Waits for this thread to die.

10) void join(long millis) :


Waits atmost millis milliseconds for this thread to die.

11) void run() :


If this thread was constructed using a separate Runnable run object, then
that Runnable object’s run method is called, otherwise, this method does
nothing and returns.

12) void setName(String name) :


Changes the name of this thread to be equal to the argument name.

13) void setPriority(int newPriority) :


Changes the priority of the thread.

14) static void sleep(long millis) :


Causes the currently executing thread to sleep ( temporarily ceases
execution) for the specified number of milli seconds.

15) void start() :


Causes this thread to begin execution; the java virtual machine calls the
run method of this thread.

16) void stop() :


Depricated method, used to stop a thread.

17) void suspend() :


Deprecated method used to suspend the thread.

Program : th1.java

import java.io.*;
public class th1
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(t);
}
}

Output

Thread[main,5,main]

Note that the above output produced when t is used as an argument to println()
method. It displays in the order name of the thread, its priority and its thread group.
By default the name of main thread is name, its default priority is 5 and its
group name is also main.

Note :

The main thread must be the last thread to finish the execution, when the main
thread stops, our program terminates.
Program : th2.java

import java.io.*;
public class th2
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread Name : "+t.getName());
System.out.println("Current Thread Priority : "+t.getPriority());
t.setName("My Thread");
t.setPriority(1);
System.out.println("Current Thread Name : "+t.getName());
System.out.println("Current Thread Priority : "+t.getPriority());
}
}

Interrupted Exception :

It is thrown when a thread is waiting, sleeping or paused for a long time and thread
interrupts using the interrupt() method.

Program : th3.java

import java.io.*;
public class th3
{
public static void main(String args[]) throws IOException
{
int i,n;
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
Thread t=Thread.currentThread();
System.out.print("Enter any value : ");
n=Integer.parseInt(br.readLine());
System.out.println("Currently Exccuting Thread : "+t.getName());
try
{
for(i=0;i<10;i++)
{
if(i==n)
t.interrupt();
Thread.sleep(1000);
System.out.println(i);
}
}
catch(InterruptedException ie)
{
System.out.println(t.getName() + " Thread is Interrupted");
}
System.out.println(t.getName() + " Thread is Completed");
}
}

User defined threads :

Threads can be created in 2 ways.

1. By extending Thread class


2. By implementing Runnable interface

By extending Thread class :

Steps :

1. Declare a class as extending Thread class.


2. Implement run() method, i.e. responsible for executing the sequence of code
of that thread.
3. Create the thread object and call start() method to run the thread.

Program : th4.java

import java.io.*;
class userthread extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("User thread : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th4
{
public static void main(String args[])
{
userthread ut=new userthread();
ut.start();
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main thread : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}

Program : th5.java

import java.io.*;
class userthread extends Thread
{
/* Thread t;
public userthread(String name)
{
t=new Thread(name);
} */

public userthread(String name)


{
this.setName(name);
}
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
// System.out.println(t.getName()+i); //
System.out.println(this.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th5
{
public static void main(String args[])
{
userthread ut1=new userthread("User Thread 1 : ");
userthread ut2=new userthread("User Thread 2 : ");
ut1.start();
ut2.start();
ut1.setPriority(Thread.MIN_PRIORITY); //ut1.setPriority(1);
ut2.setPriority(Thread.MAX_PRIORITY); //ut2.setPriority(10);
}
}

By implementing Runnable interface :

Steps :

1. Declare a class implementing Runnable interface.


2. Implement run() method in the class.
3. Create thread by defining an object. i.e. it is instantiated from Runnable
class as the target of that thread.
4. Call the thread’s start() method to run the thread.

Program : th6.java

import java.io.*;
class userthread implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("User Thread : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th6
{
public static void main(String args[])
{
userthread ut=new unserthread();
Thread t=new Thread(ut);
t.start();
try
{
for(int i=1;i<=5;i++)
{
System.out.println("User Thread : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}

Here we are implementing Runnable interface, hence we cannot call the method
start() directly with the help of Thread object, because start() method is in Thread
class, but not in Runnable interface. Hence create an instance of Thread class and
pass this instance as target object to the user defined thread creating by Runnable
interface.

Program : th7.java

Write a program to create 2 threads, the first thread prints from 1 to 10 and second
from 10 to 1. The first thread is creating using Thread class and second thread is
creating using Runnable interface.
import java.io.*;
class thread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println("Thread 1 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class thread2 implements Runnable
{
public void run()
{
try
{
for(int i=10;i>=1;i--)
{
System.out.println("Thread 2 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th7
{
public static void main(String args[])
{
thread1 ut1=new thread1();
thread2 ut2=new thread2();
Thread t=new Thread(ut2);
ut1.start();
t.start();
}
}

Making the Thread to strart immediately, when we create an instance of thread :


Program : th8.java

import java.io.*;
class thread1 extends Thread
{
public thread1(String name)
{
this.setName(name);
this.start();
}
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println(this.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class thread2 implements Runnable
{
Thread t;
public thread2(String name)
{
t=new Thread(this,name);
t.start();
}
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println(t.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}

}
}
public class th8
{
public static void main(String args[])
{
thread1 t1=new thread1("Thread 1 : ");
thread2 t2=new thread2("Thread 2 : ");
}
}

Program : th9.java

Example for suspend() and resume() methods

import java.io.*;
class userthread extends Thread
{
public userthread(String name)
{
this.setName(name);
this.start();
}
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println(this.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
System.out.println("Exit from : "+this.getName());
}
}
public class th9
{
public static void main(String args[])
{
userthread t1=new userthread("First Thread ");
userthread t2=new userthread("Second Thread ");
try
{
Thread.sleep(3000);
t1.suspend();
System.out.println("Thread : 1 is suspended");
Thread.sleep(5000);
t1.resume();
System.out.println("Thread : 1 is resumed");
t2.suspend();
System.out.println("Thread : 2 is suspended");
Thread.sleep(5000);
t2.resume();
System.out.println("Thread : 2 is resumed");
}
catch(InterruptedException ie)
{
ie.getMessage();
}
}
}

Program : th10.java

Example for isAlive() and join() methods


import java.io.*;
class thread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread - 1 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class thread2 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread - 2 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th10
{
public static void main(String args[])
{
thread1 t1=new thread1();
thread2 t2=new thread2();
t1.start();
t2.start();
if(t1.isAlive())
System.out.println("First Thread is Alive");
else
System.out.println("First Thread is Dead");
if(t2.isAlive())
System.out.println("Second Thread is Alive");
else
System.out.println("Second Thread is Dead");
try
{
t1.join();
t2.join();
for(int i=1;i<=5;i++)
{
System.out.println("Main Thread : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
if(t1.isAlive())
System.out.println("First Thread is Alive");
else
System.out.println("First Thread is Dead");
if(t2.isAlive())
System.out.println("Second Thread is Alive");
else
System.out.println("Second Thread is Dead");
}
}

To start thread2 after finishing thread1 :


Program : th11.java

import java.io.*;
class thread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println("Thread-1 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class thread2 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println("Thread-2 : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th11
{
public static void main(String args[])
{
thread1 t1=new thread1();
thread2 t2=new thread2();
t1.start();
try
{
t1.join();
t2.start();
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}

Synchronization :

When 2 or more threads need to access shared resources, they need some
way to ensure that the resources will be used by only one thread at a time. The
process by which this is achieved is called synchronization.
In Java, synchronization can be achieved in 2 ways.
1) Synchronized methods.
2) Synchronization block.

Synchronized methods :

synchronized returntype func_name ([arg_list])


{
statements;
}

Program : th12.java

class mythread
{
String name;
void func(String st)
{
name=st;
try
{
for(int i=1;i<=5;i++)
{
System.out.println(name+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class uthread extends Thread
{
mythread mt;
String name;
public uthread(mythread t,String st)
{
mt=t;
name=st;
}
public void run()
{
mt.func(name);
}
}
public class th12
{
public static void main(String args[])
{
mythread mt=new mythread();
uthread t1=new uthread(mt,"Thread-1 : ");
uthread t2=new uthread(mt,"Thread-2 : ");
t1.start();
t2.start();
}
}

In the above program t1 and t2 shares the same resources (i.e. object mt).
Without the keyword synchronized in the function declaration, we will get the
output with 2 threads running simultaneously. But here we are using synchronized
method, hence first Thread-1 will be completed after that Thread-2 starts its
execution. This is alternative method for join(), which is a deprecated method.

Synchronized block :

synchronized (object)
{
statements;
}

In case of synchronized block, we are using some methods belongs to some


specific class. The object of that specific class is passed as parameter here.

Program : th13.java

import java.io.*;
class mythread
{
String name;
void func(String st)
{
name=st;
try
{
for(int i=1;i<=5;i++)
{
System.out.println(name+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
class uthread extends Thread
{
mythread mt;
String name;
public uthread(mythread t,String st)
{
mt=t;
name=st;
}
public void run()
{
synchronized(mt)
{
mt.func(name);
}
}
}
public class th13
{
public static void main(String args[])
{
mythread mt=new mythread();
uthread t1=new uthread(mt,"Thread-1 : ");
uthread t2=new uthread(mt,"Thread-2 : ");
t1.start();
t2.start();
}
}

Dead locks : (thread locked but not become dead)

A dead lock is an error which occurs when 2 threads are in circular dependency
and a pair of synchronized objects.
Whenever a dead lock occurs, the program will not be terminated, JVM protects
it from abnormal termination. But we need to press ctrl+c to end the program.

Program : th14.java
import java.io.*;
class cl1
{
synchronized void disp(cl2 c)
{
String name=Thread.currentThread().getName();
System.out.println(name+"Entered cl1 disp");
try
{
for(int i=1;i<=5;i++)
{
System.out.println(name+" : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
System.out.println("Trying to call cl2 last");
c.last();
}
synchronized void last()
{
System.out.println("Inside cl1 last");
}
}
class cl2
{
synchronized void disp(cl1 c)
{
String name=Thread.currentThread().getName();
System.out.println(name+"Entered cl2 disp");
try
{
for(int i=1;i<=5;i++)
{
System.out.println(name+" : "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
System.out.println("Trying to call cl1 last");
c.last();
}
synchronized void last()
{
System.out.println("Inside cl2 last");
}
}
public class th14 implements Runnable
{
cl1 obj1=new cl1();
cl2 obj2=new cl2();
th14()
{
Thread.currentThread().setName("Thread-1");
Thread t=new Thread(this,"Thread-2");
t.start();
obj1.disp(obj2);
}
public void run()
{
obj2.disp(obj1);
}
public static void main(String args[])
{
new th14();
}

Current thread means main thread and we set the name of the thread as Thread : 1,
and this thread starts when we call the main() method, and we have create another
thread Thread : 2 and this thread starts when we call start() method, and start()
method calls run() method immediately. It will call obj2’s disp() method and obj1
starts whenever we creates an instance of th14. i.e. if we creates instance for th14,
it will calls the constructor and hence obj1’s disp() will starts.
Types of Threads :

There are 2 types of threads in Java


1) Daemon Threads
2) Non-Daemon Threads

A thread that is used for internal operations of JVM is called as Daemon thread,
whereas a thread that is used for the completation of java application is called as
Non-Daemon thread.

Program : th15.java

import java.io.*;
class mythread extends Thread
{
mythread(String name)
{
this.setName(name);
}
public void run()
{
if(this.isDaemon())
System.out.println(this.getName()+ "is Daemon Thread");
else
System.out.println(this.getName()+ "is Non-Daemon Thread");
try
{
for(int i=1;i<=5;i++)
{
System.out.println(this.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
public class th15
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
t.setName("Main Thread");
mythread mt=new mythread("User Thread");
mt.start();
if(t.isDaemon())
System.out.println(t.getName()+ "is Daemon Thread");
else
System.out.println(t.getName()+ "is Non-Daemon Thread");
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t.getName()+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}

Java IO Streams :

Java programs perform IO operations through streams. A stream is an abstraction


that either produces or consumes information. Streams are classified into 2 basic
types.

1) Input streams
2) Output streams

An input stream extracts data from the file or input device and sends it to the
program. An output stream takes data fro the program and sends it to the file or
output device.
Input stream may refer to a disk file, key board and a network socket. Output
stream refer to the console (monitor), disk file and network connection.

Java defined 2 types of stream operations.

1) Byte stream operations


2) Character stream operations

Byte streams :

It provides an efficient way for handling input and output bytes. Byte stream are
used for reading and writing binary data.
Java byte stream classes are derived from 2 abstract classes input stream and
output stream. Each of these abstract classes has several sub class that handle
various devices such as file, network connections, etc.

InputStream classes :

Input stream classes are used to read 8 bit bytes of information. It supports number
of sub classes for supporting various input related functions. These classes are :

1) ByteArrayInputStream
2) BufferedInputStream
3) FileInputStream
4) DataInputStream etc.

OutputStream classes :

Output stream classes are derived from the class OutputStream. The several sub
classes of this class can be used to perform output operations. They are :

1) ByteArrayOutputStream
2) BufferedOutputStream
3) FileOutputStream
4) DataOutputStream etc.

Character streams :

Character streams are used for handling input and output characters. Character
streams uses Unicode character set. Java program represents characters internally
in the 16 bit Unicode character encoding. There are 2 kinds of character streams.
Namely,
1. Reader
2. Writer

Reader class :

This class is a character input stream that reads a sequence of Unicode characters.
Several sub classes of this class can be used for performing input operations. These
sub classes are :

1) BufferedReader
2) CharArrayReader
3) InputStreamReader
4) FileReader etc.

Writer class :

This class is a character output stream that writes a sequence of Unicode


characters. Several sub classes of this class can be used for performing output
operations. These sub classes are :

1) BufferedWriter
2) CharArrayWriter
3) InputStreamWriter
4) PrintWriter
5) FileWriter etc.

ByteStream operations :

Class ByteArrayInputStream :

A ByteArrayInputStream contains an internal buffer that contains bytes that may


be read from the stream.

Constructor :
1) ByteArrayInputStream(byte[] buf) :
It creates a ByteArrayInputStream so that it uses buf as its buffer array

2) ByteArrayInputStream(byte[] buf,int offset,int length) :


It creates a ByteArrayInputStream that uses buf as its buffer array.

Methods :

1) void close() :
It closes a ByteArrayInputStream.

2) int read() :
It reads the next byte of data from the input stream

3) int read(byte [] b,int offset,int len) :


It reads data upto len bytes of data into an array of bytes from this input
stream.

4) long skip(long n) :
It skips n bytes of input from this input stream.

Program : io1.java

import java.io.*;
public class io1
{
public static void main(String args[])
{
byte bt[]={65,66,67,68,69,70};
byte b1[]=new byte[10];
byte b2[]=new byte[10];
ByteArrayInputStream bt1,bt2;
bt1=new ByteArrayInputStream(bt);
bt2=new ByteArrayInputStream(bt,2,4);
bt1.read(b1,0,5);
bt2.read(b2,0,3);
String s1=new String(b1);
String s2=new String(b2);
System.out.println(s1);
System.out.println(s2);
}
}

Output

ABCDE
CDE

Program : io2.java

(Storing the data in object b and read data from that object)

import java.io.*;
public class io2
{
public static void main(String args[])
{
byte bt[]={65,66,67,68,69,70};
int ch;
ByteArrayInputStream b=new ByteArrayInputStream(bt);
System.out.println("Reading data from the ByteArrayInputStream");
while((ch=b.read())!=-1)
{
System.out.println((char)ch+" ");
}
}
}

read() returns integer data type and hence type cast it to character type.

Class BufferedInputStream :

A BufferedInputStream adds functionality to another input stream, when a


BufferedInputStream is created an internal buffer array is created.

Constructors :
1) BufferedInputStream(InputStream in) :
Creates a BufferedInputStream and saves its argument, the InputStream in
for later use.

2) BufferedInputStream(InputStream in, int size) :


Creates a BufferedInputStream with specified size and saves its argument,
the InputStream in for later use.

Methods :

1) void close() :
It closes this InputStream and releases any system resources associated
with the stream .

2)int read() :
See the general contract of the read method of InputStream.

3) int read(byte [] b,int offset,int len) :


It reads bytes from this byte input stream into the specified byte array,
starting at the given index.

4) long skip(long n) :
It skips n bytes from this input stream.

Program : io3.java

import java.io.*;
public class io3
{
public static void main(String args[]) throws Exception
{
byte bt[]=new byte[80];
char ch;
BufferedInputStream bs=new BufferedInputStream(System.in);
System.out.print("Enter any character : ");
ch=(char)bs.read();
bs.skip(2);
System.out.print("Enter any bytes : " );
bs.read(bt,0,80);
String s=new String(bt);
System.out.println("Given Character : "+ch);
System.out.println("Given String : "+s);
}
}

Class DataInputStream :

A DataInputStream lets an application read primitive java data types from an


underlying input stream in a machine independent way. An application uses a data
input stream to write data that can later be read by a data input stream.

Constructors :

DataInputStream(System.in) :

Creates a DataInputStream that uses the specified underlying input stream.

Methods :

1) int read(byte[] b) :
Reads some number of bytes from the contained input stream and stores
them into the buffer array b.

2) int read(bytes []b, int off, int len) :


Reads upto len bytes of data from the contained input stream into an array
of bytes.

3) boolean readBooloea() :
Reads boolean.

4) byte readByte() :

5) char readChar() :

6) double readDouble() :

7) float readFloat() :

8) int readInt() :
9) String readLine() :
A deprecated method, which reads a string.

10) long readLong() :

11) short readShort() :

12) String readUTF() :


Returns string in UTF (Unicode Transformation Format)

13) int skipBytes(int n) :

14) int skip(int n) :

Program : io4.java

import java.io.*;
public class io4
{
public static void main(String args[]) throws Exception
{
char ch;
String st;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter a character : ");
ch=(char)ds.read();
ds.skip(2);
System.out.print("Enter a String : ");
st=ds.readLine();
System.out.println("Given Character : "+ch);
System.out.println("Given String : "+st);
}
}

Output stream :

Class ByteArrayOutputStream :
This class implements an output stream in which the data is written into a byte
array. The buffer automatically grows as data is written to it. The data can be
retrieved using toByteArray() and toString().

Constructors :

1) ByteArrayOutputStream :
Creates a new byte array output stream.

2) ByteArrayOutputStream(int size) :
Create a new byte array output stream, with a buffer capacity of specified
size in bytes.

Methods :

1) void close() :
Closes a ByteArrayOutputStream

2) byte[] toByteArray() :
Creates a newly allocated byte array

3) String toString() :
Converts the buffer’s contents into a string, translating bytes into chars
According to the platform’s default character encoding.

4) void write(byte[]b, int off, int len) :


Write len bytes from the specified byte array starting at offset to this byte
array output stream.

5) void write(int n) :
Writes the specified byte to this byte array output stream

6) void writeTo(outputstream out) :


Writes the complete contents of byte array output stream to the specified
output stream.

Program : io5.java

import java.io.*;
public class io5
{
public static void main(String args[]) throws Exception
{
byte b[]=new byte[80];
BufferedInputStream bis=new BufferedInputStream(System.in);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
System.out.print("Enter array of bytes : ");
bis.read(b,0,80);
bos.write(b,0,80);
String s=bos.toString();
System.out.println("Given data : "+s);
}
}

Here we are reading the data from keyboard and store it in object b and read the
same data from the object b.

Class BufferedOutputStream :

The class implements a buffered output stream. By setting up such an output


stream, an application can write bytes to the underlying output stream.

Constructors :

1) BufferedOutPutStream(outputstream out) :
Creates a new buffered output stream to write data to the specified under-
lying output stream with a default 512-byte buffer size.

2) BufferedOutputStream(outputstream out,int size) :


Creates a new buffered output stream to write data to the specified under-
lying output stream with the specified buffer size.

Methods :

1) void flush() :
Flushes the buffered output stream.

2) void write(byte []b, int off, int len) :


Writes len bytes from the specified byte array starting at offset to this
Buffered output stream.
3) void write(int b) :
Writes the specified bytes to this buffered output stream.

Program : io6.java
import java.io.*;
public class io6
{
public static void main(String args[]) throws Exception
{
int n;
byte b[]=new byte[80];
BufferedInputStream bs=new BufferedInputStream(System.in);
System.out.print("Enter any byte : ");
n=bs.read();
bs.skip(2);
System.out.print("Enter array of bytes : ");
bs.read(b,0,80);
BufferedOutputStream bos=new BufferedOutputStream(System.out);
bos.write(n);
System.out.print("Given byte : ");
bos.flush(); outputstream object
bos.write(b,0,b.length);
System.out.print("\nGiven byte array : ");
bos.flush();
}
}

write() method get the data from the output stream, but it will not print the data
from the console. Hence we should use flush() method which flushed out the data
from the console.(It is like in C++ programming)

Eg :

char ch;
ch=cin.get();
cout.put(ch);

Here we should press Alt+F5 to see the output, and if we use cout.flush()
method no need to press Alt+F5 to see the output.
Program : io7.java

import java.io.*;
public class io7
{
public static void main(String args[]) throws Exception
{
byte b[]=new byte[80];
BufferedInputStream bis=new BufferedInputStream(System.in);
ByteArrayOutputStream boas=new ByteArrayOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(System.out);
System.out.print("Enter array of bytes : ");
bis.read(b,0,80);
boas.write(b,0,80);
boas.writeTo(bos);
System.out.print("Given data : ");
bos.flush();
}
}

Writes the data of ButeArrayOutputStream to the console buffered output stream


(also we can write to the file streams or net word sockets)

Class DataOutputStream :

DataOutputStream lets an application write primitive java data types to an


output stream.

Constructors :

DataOutputStream(outputstream out) :

Creates a new data output stream to write data to the specified underlying
output stream.

Methods :

1) void flush() :
Flushes this data output stream.

2) void write(byte []b, int off, int len) :


Writes len bytes from the specified byte array starting at offset to the
underlying output stream.

3) void write(int b) :
Write the specified byte to the underlying output stream.

4) void write Boolean(boolean v) :

5) void writeByte(int v) :

6) void writeByte(String s) :

7) void writeChar(int v) :

8) void writeChars(String s) :

9) void writeDouble(double v) :

10) void writeFloat(float v) :

11) void writeLong(long v) :

12) void writeShort(short v) :

13) void writeUTF(String str) :


Writes a string to the underlying output stream using java modified UTF-8
encoding in a machine independent way

Note :

In DataOutputStream, it automatically flushed the specified output stream, when


we are using the object of console output stream (System.out)

Program : io8.java

import java.io.*;
public class io8
{
public static void main(String args[]) throws Exception
{
int n;
byte b[]=new byte[80];
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter any byte : ");
n=ds.read();
ds.skip(2);
System.out.print("Enter array of bytes : ");
ds.read(b,0,80);
DataOutputStream dos=new DataOutputStream(System.out);
System.out.print("Given byte : ");
dos.write(n);
System.out.print("\nGiven byte array : ");
dos.write(b,0,b.length);
}
}

Here we are using outputstream DataOutputStream, it directly write the data to the
console(i.e. to the monitor), hence no need to flush the data.

Character streams :

Class InputStreamReader :

An InputStreamReader is a bridge from Byte stream to Character stream. It reads


bytes and decode them into characters.

Constructors :

InputStreamReader(InputStream in) :
Creates an InputStreamReader that used the default charset.

Methods :

1) void close() :
It closes the stream.
2) int read() :
Reads a single character.

3) int read(char[] cbuf, int offset, int length) :


Reads characters into a portion of an array.

4) long skip(long n) :

Program : io9.java
import java.io.*;
public class io9
{
public static void main(String args[]) throws Exception
{
char ch;
char c[]=new char[80];
InputStreamReader isr=new InputStreamReader(System.in);
System.out.print("Enter any character : ");
ch=(char)isr.read();
System.out.print("Enter characters into char array : ");
isr.skip(2);
isr.read(c,0,80);
System.out.print("Given character : "+ch);
String s=new String();
System.out.print("\nGiven character array: "+s);
}
}

Class BufferedReader :

Reads text from a character input stream, buffering characters so as to provide for
the efficient reading of characters, arrays and lines.

Constructors :

1) BufferedReader(Reader in) :
Create a buffering character input stream that uses a default sized input
buffer.

2) BufferedReader(Reader in, int size) :


Creates a buffering characters input stream that used an input buffer of the
specified size.

Methods :

1) void close() :
It closes a stream.

2) int read() :
Reads a single character.

3) int read(char[] buf, int off, int len) :


Read characters into a portion of array.

4) String readLine() :
Reads a line of text.

5) long skip(long n) :

Program : io10.java

import java.io.*;
public class io10
{
public static void main(String args[]) throws Exception
{
char ch;
char c[]=new char[80];
String s;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("Enter any character : ");
ch=(char)br.read();
System.out.print("Enter characters into char array : ");
br.skip(2);
br.read(c,0,80);
System.out.print("Enter any string : ");
s=br.readLine();
System.out.print("Given character : "+ch);
String st=new String(c);
System.out.print("\nGiven character array: "+st);
System.out.print("\nGiven string : "+s);
}
}

Class CharArrayReader :

This class implements a character buffer that can be used as a character input
stream.

Constructors :

1) CharArrayReader(char[] buf) :
Create a CharArrayReader from the specified array of characters.

2) CharArrayReader(char[] buf, int offset, int length) :


Create a CharArrayReader from the specified array of characters.

Methods :

1) void close() :
It closes a stream.

2) int read() :
Reads a single character.

3) int read(char[] buf, int off, int len) :


Read characters into a portion of array.

4) long skip(long n) :

Program : io11.java

import java.io.*;
public class io11
{
public static void main(String args[]) throws Exception
{
char c1[]=new char[80];
char c2[]=new char[80];
char c3[]=new char[80];
InputStreamReader ir=new InputStreamReader(System.in);
System.out.print("Enter characters into character array : ");
ir.read(c1,0,80);
CharArrayReader cr=new CharArrayReader(c1);
CharArrayReader cr1=new CharArrayReader(c1,0,7);
cr.read(c2,0,c2.length);
cr1.read(c3,0,c3.length);
String s1=new String(c2);
String s2=new String(c3);
System.out.println(s1);
System.out.println(s2);
}
}

Reading data from another input stream and store it in char array, again read and
write the char array from CharArrayReader object.

Output streams :

Class CharArrayWriter :

This class implements a character buffer that can be used as a writer. The buffer
automatically grows when data is written to the stream. The data can be retrieved
using toCharArray() and to String().

Constructors :

1) CharArrayWriter() :
Create a CharArrayWriter.

Methods :

1) void flush() :
It flushes the stream.

2) char[] toCharArray() :
Returns a copy of the input data.
3) String toString() :
Converts input data to a string.

4) void write(char []c, int off, int len) :


Writes characters to the buffer.

5) void write(int c) :
Writes a character to the buffer.

6) void writeTo(writer out) :


Writes the contents of the buffer to another character stream.

7) void close() :

Program : io12.java

import java.io.*;
public class io12
{
public static void main(String args[]) throws Exception
{
char ch[]=new char[80];
int c;
InputStreamReader ir=new InputStreamReader(System.in);
CharArrayWriter cw=new CharArrayWriter();
System.out.print("Enter any character : ");
c=ir.read();
ir.skip(2);
System.out.print("Enter characters into character array : ");
ir.read(ch,0,80);
cw.write(c);
cw.write(ch,0,ch.length);
System.out.println("Data in the stream : "+cw.toString());
}
}

Class PrintWriter :

Print formatted representation of objects to a text output stream. This class


implements all of the print methods found in print stream.
Constructors :

1) PrintWriter(outputstream out) :
Creates a new print writer without automatic line flushing from existing
output stream.

2) PrintWriter(outputstream out, boolean autoflush) :


Creates a new print writer from an existing output stream.

3) PrintWriter(writer out) :
Creates a new print writer without automatic line flushing.

4) PrintWriter(writer out, boolean autoflush) :


Creates a new print writer.

Methods :

1) void flush() :
It flushes the stream.

2) void close() :

3) print() or println() :
Used to print any type of data including objects.

4) void write( char[] buf) :


Writes an array of characters.

5) void write(char []buf, int off, int len) :


Writes a portion of an array of characters.

6) void write(int c) :
Writes a character to the buffer.

7) void write(String s) :
Writes a string.

8) void write(String s, int off, int len) :


Writes a portion of string.
Program : io13.java

import java.io.*;
public class io13
{
public static void main(String args[]) throws Exception
{
char ch[]=new char[80];
String st;
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
PrintWriter p=new PrintWriter(System.out);
System.out.print("Enter characters into character array : ");
br.read(ch,0,80);
System.out.print("Enter a string : ");
st=br.readLine();
p.println("Given character array : "+String.valueOf(ch));
p.println("Given string : "+st);
p.print("\nData in the stream : ");
p.write(st);
p.flush();
p.write(ch);
p.flush();
}
}

Class OutputStreamWriter :

An OutputStreamWriter is a bridge from character streams to byte stream.


Characters written to it are encoded into bytes.

Constructors :

1) OutputStreamWriter(outputstream out) :
Creates an outputstreamwriter that used the default char encoding.

Methods :
1) void flush() :
It flushes the stream.

2) void close() :

3) void write(char []cbuf, int off, int len) :


Writes a portion of an array of characters.

4) void write(int c) :
Writes a character to the buffer.

5) void write(String s, int off, int len) :


Writes a portion of string.

Program : io14.java

import java.io.*;
public class io14
{
public static void main(String args[]) throws Exception
{
char ch[]=new char[80];
InputStreamReader ir=new InputStreamReader(System.in);
System.out.print("Enter characters into character array : ");
ir.read(ch,0,80);
OutputStreamWriter ow=new OutputStreamWriter(System.out);
System.out.print("Given character array : ");
ow.write(ch,0,ch.length);
ow.flush();
}
}

Class BufferedWriter :

Writes text to a character – output stream buffering characters so as to provide for


the efficient writing of single character, arrays and strings.

Constructors :
1) BufferedWriter(writer out) :
Creates a new buffered character output stream that used the default sized
output buffer.

Methods :

1) void flush() :

2) void close() :

3) void write(char [] cbuf, int off, int len) :

4) void write(int c) :

5) void write(String s, int off, int len) :

Program : io15.java

import java.io.*;
public class io15
{
public static void main(String args[]) throws Exception
{
char ch[]=new char[80];
InputStreamReader ir=new InputStreamReader(System.in);
System.out.print("Enter characters into character array : ");
ir.read(ch,0,80);
OutputStreamWriter ow=new OutputStreamWriter(System.out);
BufferedWriter br=new BufferedWriter(ow);
System.out.print("Given character array : ");
br.write(ch,0,ch.length);
br.flush();
} pass output stream object
}

Program : io16.java

import java.io.*;
public class io16
{
public static void main(String args[]) throws Exception
{
int ch;
String st;
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
System.out.print("Enter any character : ");
ch=br.read();
br.skip(2);
System.out.print("Enter a string : ");
st=br.readLine();
OutputStreamWriter ow=new OutputStreamWriter(System.out);
BufferedWriter b=new BufferedWriter(ow);
System.out.print("Given character : ");
b.write(ch);
b.flush();
System.out.print("\nGiven string : ");
b.write(st,0,st.length());
b.flush();
}
}
for strings use length() method

Files :

A file is a collection of related data or records.

Class File :

An abstract representation of file and directory path names.

Constructors :

1) File(String pathname) :
Creates a new file instance by converting the given path name string into
an abstract path name.

Methods :
1) boolean createNewFile() :
Atomically creates a new, empty file named by this abstract path name, if
and only if a file with this name does not yet yields.

2) boolean exists() :
Tests whether the file / directory denoted by this abstract path name
exists.

3) String getName() :
Returns the name of the file / directory denoted by this abstract path name

4) String getPath() :
Converts this abstract path name into a path name string.

5) boolean isDirectory() :
Tests whether the file denoted by this abstract path name is a directory.

6) boolean isFile() :
Tests whether the file denoted by this abstract path name is a normal file.

7) long length() :
Returns the length of the file denoted by this abstract path name.

8) String[] list() :
Returns an array of strings naming the files and directories in the directory
denoted by this abstract path name.

9) boolean mkdir() :
Creates the directory named by this abstract path name.

Program : file1.java

import java.io.*;
public class file1
{
public static void main(String args[]) throws Exception
{
File f=new File("E:\\raji\\java\\programs\\r1.txt");
if(f.exists())
System.out.println("File already exists");
else
{
boolean b=f.createNewFile();
if(b)
System.out.println("File created successfully");
else
System.out.println("Unable to create a file");
}
}
}

Program : file2.java

import java.io.*;
public class file2
{
public static void main(String args[]) throws Exception
{
File f=new File("E:\\raji\\java\\programs\\raji1");
if(f.exists())
System.out.println("Directory already exists");
else
{
boolean b=f.mkdir();
if(b)
System.out.println("Directory created successfully");
else
System.out.println("Unable to create a Directory");
}
}
}

Program : file3.java

import java.io.*;
public class file3
{
public static void main(String args[]) throws Exception
{
int count=0;
String path;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.println("Enter path : ");
path=br.readLine();
File f=new File(path);
if(f.exists())
{
if(f.isDirectory())
{
String st[]=f.list();
System.out.println("List of files and directories : ");
for(int i=0;i<st.length;i++)
{
File f1=new File(st[i]);
if(f1.isFile())
System.out.println(f1.getName()+ "is a File");
if(f1.isDirectory())
System.out.println(f1.getName()+ "is a Directory");
count++;
if(count%20==0)
System.in.read();
}
}
}
else
System.out.println("Directory is not exists");
}
}

Class FileOutputStream :

A FileOutputStream is an output stream for writing data to a file.

Constructors :

1) FileOutputStream(File file) :
Creates a file output stream to write to the file represented by the specified
file object.
2) FileOutputStream(File file, boolean append) :
Creates a file output stream to write to the file represented by the specified
file object

3) FileOutputStream(String name) :
Creates an output file stream to write to the file with the specified name.

4) FileOutputStream(String name, boolean append) :


Creates an output file stream to write to the file with the specified name.

Methods :

1) void close() :
Closes this file output stream.

2) void write(int b) :
Writes the specified byte to this file output stream.

Note :

eof : It is a constant which refers to end of file indicator, its constant value
is -1. To get this character from keyboard press Ctrl + Z.

Program : file4.java

import java.io.*;
public class file4
{
public static void main(String args[]) throws Exception
{
File f=new File("r2.txt"); // or “r2.dat”
int ch;
boolean b=f.exists();
if(b==false)
f.createNewFile();
FileOutputStream fos=new FileOutputStream(f);
// FileOutputStream fos=new FileOutputStream(f,true);
System.out.println("Enter data to the file (Ctril+Z to stop) ");
ch=System.in.read();
while(ch!=-1)
{
fos.write(ch);
ch=System.in.read(); if not end of file
}
fos.close();
}
}

Executing the program :

1) C: > javac file4.java


C:> java file4

abcdefgheabcdefg
fghikklmnfghijklm
Ctrl+Z

Output : 1 (if the boolean value of append is false)

C:>type r2.txt or notepad r2.txt

abcdefgheabcdefg
fghijklmnfghijklm

C:> java file4

nopqrtstnopqrts
tuvwxyztuvwxyz
Ctrl+Z

C:>type r2.txt or notepad r2.txt

nopqrtstnopqrts
tuvwxyztuvwxyz

2) C: > javac file4.java


C:> java file4

abcdefgheabcdefg
fghikklmnfghijklm
Ctrl+Z

Output : 2 (if the boolean value of append is true)

C:>type r2.txt or notepad r2.txt

abcdefgheabcdefg
fghijklmnfghijklm

C:> java file4

nopqrtstnopqrts
tuvwxyztuvwxyz

C:>type r2.txt or notepad r2.txt

abcdefgheabcdefg
fghijklmnfghijklm
nopqrtstnopqrts
tuvwxyztuvwxyz

i.e. if the boolean value is true, new data will be appended to old data.

Program : file5.java

import java.io.*;
public class file5
{
public static void main(String args[]) throws Exception
{
int ch;
// FileOutputStream fos=new FileOutputStream("r3.txt");
FileOutputStream fos=new FileOutputStream("r3.txt",true);
System.out.println("Enter data to the file (Ctril+Z to stop) ");
ch=System.in.read();
while(ch!=-1)
{
fos.write(ch);
ch=System.in.read();
}
fos.close();
}
}

Note :

The main difference between writing data to the file through file object and
through string file name is :
By writing data to the file through file object, we will check whether the given
file is exists or not. If the file doesnot exists then only we will create the specified
file. Where as by writing data to the file through string file name, no matter to
check whether the file is exists or not, directly it will creates the file.

Class FileInputStream :

A FileInputStream is obtains input bytes from a file in file system.

Constructors :

1) FileInputStream(File file) :
Creates a file input stream by opening a connection to an actual file, the
file named by the file object in the file system.

2) FileInputStream(String name) :
Creates a file input stream by opening a connection to an actual file, the
file named by the path name name in the file system.

Methods :

1) void close() :
Closes this file input stream.
2) int read() :
Reads a byte of data from this input stream.

Program : file6.java

import java.io.*;
public class file6
{
public static void main(String args[]) throws Exception
{
File f=new File("r2.txt");
int ch;
boolean b=f.exists();
if(b==false)
{
System.out.println("File not Found");
System.exit(0);
}
FileInputStream fis=new FileInputStream(f);
System.out.println("Reading data from the file");
ch=fis.read();
while(ch!=-1)
{
System.out.print((char)ch);
ch=fis.read();
}
fis.close();
}
}

Program : file7.java

import java.io.*;
public class file7
{
public static void main(String args[]) throws Exception
{
FileInputStream fis=new FileInputStream("r3.txt");
int ch;
System.out.println("Reading data from the file");
ch=fis.read();
while(ch!=-1)
{
System.out.print((char)ch);
ch=fis.read();
}
fis.close();
}
}

[read() reads only integer data, so for printing character data typecast it to char data
type]

Note :

The main difference between reading data from the file through file object and
through string file name is :
By reading data from the file through file object, we will check whether the
given file is exists or not. If the file doesnot exists then manually we will give the
message “File not Found”. Where as by reading data to the file through string file
name, if the file is not found, then the system will raise the exception “File Not
Found”. Because here no matter to check whether file is exists or not.

Class FileWriter :

Convenience class for writing character files.

Constructors :

1) FileWriter(File file) :

2) FileWriter(File file, boolean append) :

3) FileWriter(String fileName) :

4) FileWriter(Strin fileNname, boolean append) :

Methods :
1) void close() :

2) void write(int b) :

Program : file8.java

import java.io.*;
public class file8
{
public static void main(String args[]) throws Exception
{
File f=new File("r4.txt");
int ch;
boolean b=f.exists();
if(b==false)
f.createNewFile();
FileWriter fw=new FileWriter(f);
// FileWriter fw=new FileWriter(f,true);
System.out.println("Enter data to the file (Ctril+Z to stop) ");
ch=System.in.read();
while(ch!=-1)
{
fw.write(ch);
ch=System.in.read();
}
fw.close();
}
}

Program : file9.java

import java.io.*;
public class file9
{
public static void main(String args[]) throws Exception
{
int ch;
// FileWriter fw=new FileWriter("r5.txt");
FileWriter fw=new FileWriter("r5.txt",true);
System.out.println("Enter data to the file (Ctril+Z to stop) ");
ch=System.in.read();
while(ch!=-1)
{
fw.write(ch);
ch=System.in.read();
}
fw.close();
}
}

Class FileReader :

Convenience class for reading character files.

Constructors :

1) FileReader (File file) :

2) FileReader(String fileName) :

Methods :

1) void close() :

2) int read() :

Program : file10.java

import java.io.*;
public class file10
{
public static void main(String args[]) throws Exception
{
File f=new File("r4.txt");
int ch;
boolean b=f.exists();
if(b==false)
{
System.out.println("File not Found");
System.exit(0);
}
FileReader fr=new FileReader(f);
System.out.println("Reading data from the file");
ch=fr.read();
while(ch!=-1)
{
System.out.print((char)ch);
ch=fr.read();
}
fr.close();
}
}

Program : file11.java

import java.io.*;
public class file11
{
public static void main(String args[]) throws Exception
{
FileReader fr=new FileReader("r5.txt");
int ch;
System.out.println("Reading data from the file");
ch=fr.read();
while(ch!=-1)
{
System.out.print((char)ch);
ch=fr.read();
}
fr.close();
}
}

Utility Packages :

Class Random :

An instance of this class is used to generate a stream of pseudorandom numbers.


Constructors :

1) Random() :
Creates a new random number generator.

2) Random(long seed) :
Creates a new random number generator using a single long seed.

Methods :

1) int nextInt() :
Returns the next pseudorandom, uniformly distributed int value from this
random number generator’s sequence.

2) int nextInt(int n) :
Returns the next pseudorandom, uniformly distributed int value between
0 (inclusive) and the specified value (exclusive) drawn from this random
number generator’s sequence.

3) void setseed(long seed) :

Program : ran1.java

To generate 10 random numbers between 0 and 100

import java.io.*;
import java.util.*;
public class ran1
{
public static void main(String args[])
{
int n;
// Random r=new Random();
// Random r=new Random(1);
for(int i=0;i<10;i++)
{
n=r.nextInt(100);
System.out.println(n);
}
}
}

Note :

1 If we set the seed value, we will get same set of 10 numbers, when
compiling again and again.

2 The seed value may be any integer.

3 If we didn’t specify seed value, we will get different set of 10 numbers,


when compiling again and again.

Program : ran2.java

To generate 10 random numbers between 0 and 100, avoiding duplicated


numbers

import java.io.*;
import java.util.*;
public class ran2
{
public static void main(String args[])
{
int n,i,id=0,ck;
int a[]=new int[10];
Random r=new Random();
while(id<10)
{
n=r.nextInt(100);
ck=0;
for(i=0;i<id;i++)
{
if(a[i]==n)
{
ck=1;
break;
}
}
if(ck==0)
{
a[id]=n;
id++;
}
}
System.out.println("Random Numbers : ");
for(i=0;i<10;i++)
{
System.out.print(a[i]+" ");
}
}
}

Class Math :

The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root and trigonometric functions.

Methods :

1) static double E :
The double value that is closer than any other to e, the base of the natural
logarithms.

2) static double PI :
Double value that is closer than any other to pi, the ratio of circumference
of a circle to its diameter.

3) static double abs(double a) :

4) static double ceil(double a) :


Rounds up the given value

5) static double floor(double a) :


Rounds down the given value.

6) static double pow(double a, double b) :

7) static double random() :


Returns a double value with a positive sign >= 0.0 and less than 1.0
8) static double sqrt(double a) :
Returns the correctly rounded positive square root of a double value.

Program : math1.java

import java.io.*;
import java.util.*;
public class math1
{
public static void main(String args[]) throws Exception
{
int a,b;
double d;
BufferedReader br=new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Enter any integer (abs) : ");
a=Integer.parseInt(br.readLine());
System.out.println("Given value : "+a);
System.out.println("Absolute value : "+Math.abs(a));
System.out.print("\nEnter any integer (sqrt) : ");
a=Integer.parseInt(br.readLine());
System.out.println("Given value : "+a);
System.out.println("Square root : "+Math.sqrt(a));
System.out.print("\nEnter 2 integers (pow) : ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
System.out.println("Exponential value : "+Math.pow(a,b));
System.out.print("\nEnter any double (floor & ceil) : ");
d=Double.parseDouble(br.readLine());
System.out.println("Given value : "+d);
System.out.println("Ceil value : "+Math.ceil(d));
System.out.println("Floor value : "+Math.floor(d));
}
}

Class stack :

The class stack represents a last in first out (LIFO) of stack of objects.
Constructors :

1) stack () :
Creates an empty stack.

Methods :

1) boolean empty() :
Tests if this stack is empty.

2) Object peek() :
Looks at the object at the Object at the top of this stack without removing
it from stack.

3) Object pop() :
Removes the object at the top of this stack and returns the object as the
value of this function.

4) Object push(Object item) :


Pushes an item onto the top of the stack.

5) int search(Object obj) :


Returns the one-based position where an object is on this stack.

6) Object[] toArray() :
Returns an array containing all elements in this stack.

Program : stk1.java

import java.io.*;
import java.util.*;
public class stk1
{
public static void main(String args[]) throws Exception
{
int n,opt;
Stack s=new Stack();
Object obj;
BufferedReader br=new BufferedReader(new InputStreamReader(
System.in));
while(true)
{
System.out.println("\nSTACK MENU");
System.out.println("--------------------");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Peek");
System.out.println("4.Display");
System.out.println("5.Search");
System.out.println("6.Exit");
System.out.println("--------------------\n");
System.out.print("Enter your option : ");
opt=Integer.parseInt(br.readLine());
switch(opt)
{
case 1:
System.out.print("\nEnter element to insert : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
s.push(obj);
System.out.println("\nElement inserted\n");
break;
we can create any type of instance for Object class
case 2:
if(s.empty())
System.out.println("\nStack is empty\n");
else
{
obj=s.pop();
System.out.println(obj+" is removed\n");
}
break;

case 3:
if(s.empty())
System.out.println("\nStack is empty\n");
else
{
obj=s.peek();
System.out.println("\nPeek element : "+ obj);
}
break;

case 4:
if(s.empty())
System.out.println("\nStack is empty\n");
else
{
System.out.println("\nStack elements : ");
Object obj1[]=s.toArray();
for(int i=obj1.length-1;i>=0;i--)
{
System.out.println(obj1[i]+" ");
}
}
break;

case 5:
if(s.empty())
System.out.println("\nStack is empty\n");
else
{
System.out.print("\nEnter element to search : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
int k=s.search(obj);
if(k==-1)
System.out.print("\nElement not found\n");
else
System.out.println("\nElement found at : "+k);
}
break;
case 6:
System.exit(0);
break;
}
}
}
}
Class Vector :

The vector class implements a growable array of objects. Like an array, it contains
components that can be accessed using an integer index. However the size of
vector can grow or shrink as needed to accommodate adding and removing items
after the vector has been created.

Constructors :

1) Vector() :
Constructs an empty vector so that its internal data array has size 100 and
its standard capacity increment is zero.

2) Vector(int initialcapacity) :
Constructs an empty vector with the specified initial capacity and with its
capacity increment = 0.

3) Vector(int initialcapacity, int capacityincrement) :


Constructs an empty vector with the specified initial capacity or capacity
increment.

Methods :

1) void add(int index, Object element) :


Inserts the specified element at the specified position in this vector.

2) boolean add(Object o) :
Appends the specified element to the end of this vector.

3) void addElement(Object obj) :


Adds the specified component to the end of this vector, increasing its size
by one.

4) int capacity() :
Returns the current capacity of vector.

5) void clear() :
Removes all these elements from this vector.

6) Object elementAt(int index) :


Returns the component at the specified index.

7) Object firstElement() :

8) Object get(int index) :


Returns the element at the specified position in this vector.

9) int indexOf(Object element) :


Searched for the first occurrence of the given argument, beginning the
search at index, and testing for equality using the equals method.

10) void insertElementAt(Object obj, int index) :


Inserts the specifed object as a component in this vector at the specified
index.

11) boolean isEmpty() :


Tests if the vector has no components.

12) Object remove(int index) :


Removes the element at the specified position in this vector.

13) boolean remove(Object o) :


Removes the first occurrence of the specified element in this vector. If
the vector doesnot contain the element, it is unchanged.

14) void removeAllElements() :


Removes all components from this vector and sets its size to zero.

15) void setElementAt(Object obj, int index) :


Set the component at the specified index of this vector to be the specified
object.

16) Object[] toArray() :


Returns an array containing all of the elements in this vector in correct
order.

Program : vtr1.java

import java.io.*;
import java.util.*;
public class vtr1
{
public static void main(String args[]) throws Exception
{
int opt,n,pos,k,i;
Vector v=new Vector();
Object obj;
BufferedReader br=new BufferedReader(new InputStreamReader(
System.in));
while(true)
{
System.out.println("\nVECTOR MENU");
System.out.println("-------------------");
System.out.println("1.Add");
System.out.println("2.Display");
System.out.println("3.Insert");
System.out.println("4.Delete");
System.out.println("5.Search");
System.out.println("6.Replace");
System.out.println("7.Exit");
System.out.println("-------------------");
System.out.print("\nEnter your option : ");
opt=Integer.parseInt(br.readLine());
switch(opt)
{
case 1:
System.out.print("\nEnter element to add : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
v.addElement(obj);
System.out.println("\nElement added");
break;
case 2:
if(v.isEmpty())
System.out.println("\nVector is empty");
else
{
Object obj1[]=v.toArray();
System.out.println("\nGiven Vactor elements : \n");
for(i=0;i<obj1.length;i++)
{
System.out.println(obj1[i]+" ");
}
}
break;
case 3:
System.out.println("\nEnter element to insert : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
System.out.println("\nEnter position : ");
pos=Integer.parseInt(br.readLine());
v.insertElementAt(obj,pos);
System.out.println("\nElement is inserted");
break;
case 4:
if(v.isEmpty())
System.out.println("\nVector is empty");
else
{
System.out.println("\nEnter element to delete : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
boolean b=v.remove(obj);
if(b)
System.out.println("\nElement is deleted");
else
System.out.println("\nElement not found");
}
break;
case 5:
if(v.isEmpty())
System.out.println("\nVector is empty");
else
{
System.out.println("\nEnter element to search : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
k=v.indexOf(obj);
if(k==-1)
System.out.println("\nElement not found");
else
System.out.println("\nElement found at position : "+k);
}
break;
case 6:
System.out.println("\nEnter element to replace : ");
n=Integer.parseInt(br.readLine());
obj=new Integer(n);
System.out.println("\nEnter position : ");
pos=Integer.parseInt(br.readLine());
v.setElementAt(obj,pos);
System.out.println("\nElement is replaced");
break;
case 7:
System.exit(0);
break;
}
}
}
}

Class Date :

The class Date represents a specific instant in time with milli second precision.

Constructors :

1) Date() :
Allocates a Date object and initializes it with the default system date and
time.

2) Date(int year, int month, int date) : (depricated method)


Allocates a Date object and initializes it with the specified date.

Year : Year – 1990


Month : Starts from 0

3) Date(int year, int month, int date, int hrs, int min, int sec) :
Allocates a Date object and initializes it with the specified date and time.
Methods :

1) boolean after(Date when) :


Tests if this date is after the specified date.

2) boolean before(Date when) :


Tests if this date is before the specified date.

3) int compareTo(Date anotherDate) :


Compares 2 dates for ordering.

Returns :

0  2 dates are equal


> 0  first date is greater than second date
< 0  first date is less than second date
Program : date1.java

import java.io.*;
import java.util.*;
public class date1
{
public static void main(String args[])
{
Date d1=new Date();
Date d2=new Date(112,11,21);
Date d3=new Date(107,5,17,5,55,0);
System.out.println(d1);
System.out.println(d2); represents June month
System.out.println(d3);
} 1990 + 107 = 2007
}

Program : date2.java

import java.io.*;
import java.util.*;
public class date2
{
public static void main(String args[])
{
int n;
boolean b;
Date d=new Date();
Date d1=new Date(); we can specify our own date also
Date d2=new Date(115,4,25);
Date d3=new Date(112,11,21,12,30,20);
n=d.compareTo(d1);
if(n==0)
System.out.println("d = d1");
else
System.out.println("d != d1");
b=d1.before(d2);
if(b)
System.out.println("d1 < d2");
else
System.out.println("d1 > d2");
b=d1.after(d3);
if(b)
System.out.println("d1 < d3");
else
System.out.println("d1 > d3");

}
}

Class Calendar :

Calendar is an abstract base class for converting between a Date object and a set of
integer fields such as YEAR, MONTH, DAY, HOURS and so on.

Fields :

1 static int JANUARY


2 static int DECEMBER
3 static int SUNDAY
4 static int SATURDAY
5 static int AM
6 static int AM_PM
7 static int DATE (day of the month)
8 static int DAY_OF_MONTH (day of the month)
9 static int DAY_OF_WEEK
10 static int DAY_OF_WEEK_IN_MONTH
11 static int DAY_OF_YEAR
12 static int HOUR
13 static int MINUTE
14 static int SECOND
15 static int WEEK
16 static int WEEK_OF_MONTH
17 static int WEEK_OF_YEAR

Methods :

1) static Calendar getInstance() :


Gets a Calendar using the default time zone and locale.

2) String toString() :
Returns a String representation of the Calendar.
Program : cal1.java

import java.io.*;
import java.util.*;
public class cal1
{
public static void main(String args[])
{
Calendar c=Calendar.getInstance();
System.out.println(c);
}
}

Program : cal2.java

import java.io.*;
import java.util.*;
public class cal2
{
public static void main(String args[])throws IOException
{
Calendar c=Calendar.getInstance();
String s=c.toString();
String s1[]=s.split(",");
for(int i=0;i<s1.length;i++)
{
System.out.println(s1[i]);
if(i%20==0)
System.in.read();
}
}
}
This is to print the data in next page after printing 20 records

You might also like