Untitled
Untitled
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 :
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.
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");
}
}
Data Types
Primitive Derived
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.
■ 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.
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:
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.
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:
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.
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.
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.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit Logical OR
&& Short-circuit Logical AND
! Logical unary NOT
Objects:
Classes:
1.Encapsulation:
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
Polymorphism:
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:
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:
JRE:
[Document section]
[Package statements]
Import statements
[Interface statements]
Class definition
Document 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:
Interface statements:
Class definitions:
Package java.lang:
Package java.io:
Class System:
The static fields are invoked directly with the help of class
name without declaring any object of the class.
Syntax: classname.fieldname
print / println:
Syntax:
print(data) or print(data-1+data-2+……+data-n);
or
println(data) or println(data -1+data-2+…………+data- n);
Example:
2. int n=10;
System.out.println(“Value of n = “ + n);
Note:
Variable:
1) Local variables:
These variables are declared and used inside the methods. They are not
accessible outside the methods.
2) Instance variables:
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[])
{
/*
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
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:
skip:
IOException:
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():
class Float:
Methods:
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:
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);
}
}
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.
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");
}
}
}
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:
=======for===========
----
----
for(initialization;condition;incrementation)
{
-----
-----
}
---
---
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
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.
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;
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
}
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
{
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
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;
}
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 :
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.
Note :
.
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 :
final variables :
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 :
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 :
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);
}
}
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 :
-----------
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 :
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");
}
}
Abstract methods :
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);
}
}
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
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.
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.
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
}
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
{
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...)
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()
{
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(.)
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();
}
}
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.
import package_name.class_name;
or
import packagename_1.packagename_2………packagename_n.class_name;
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.
(cls1.java )
package pack;
import java.io.*;
public class cls1
{
public void disp()
{
System.out.print("My Package");
}
}
(pktest2.java)
import java.io.*;
import pack.cls1;
public class pktest2
{
public static void main(String args[])
{
cls1 c1=new cls1();
c1.disp();
}
}
(cls2.java )
package pack.pack1;
import java.io.*;
public class cls2
{
public void display()
{
System.out.print("Welcome to Java Sub 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));
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 :
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");
}
}
(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 :
(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 :
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 :
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 :
3. throw :
when an exception that is decided to be handle is detected, it is thrown using the
throw statement.
4. throws:
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.
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
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 :
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
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());
}
}
}
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());
}
}
}
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.
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
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.
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.
Note :
Constructors :
1) Thread :
Allocates a new thread object.
2) Thread(Runnable target) :
Allocates a new thread object.
4) Thread(String name) :
Allocates a new thread object with specified name.
Methods :
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.
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.
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");
}
}
Steps :
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);
} */
Steps :
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();
}
}
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
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
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 :
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;
}
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();
}
}
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 :
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 :
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.
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 :
1) BufferedWriter
2) CharArrayWriter
3) InputStreamWriter
4) PrintWriter
5) FileWriter etc.
ByteStream operations :
Class ByteArrayInputStream :
Constructor :
1) ByteArrayInputStream(byte[] buf) :
It creates a ByteArrayInputStream so that it 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
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 :
Constructors :
1) BufferedInputStream(InputStream in) :
Creates a BufferedInputStream 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.
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 :
Constructors :
DataInputStream(System.in) :
Methods :
1) int read(byte[] b) :
Reads some number of bytes from the contained input stream and stores
them into the buffer array b.
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.
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.
5) void write(int n) :
Writes the specified byte to this byte array 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 :
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.
Methods :
1) void flush() :
Flushes the 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();
}
}
Class DataOutputStream :
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.
3) void write(int b) :
Write the specified byte to the underlying output stream.
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) :
Note :
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 :
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.
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.
Methods :
1) void close() :
It closes a stream.
2) int read() :
Reads a single character.
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.
Methods :
1) void close() :
It closes a stream.
2) int read() :
Reads a single character.
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.
5) void write(int c) :
Writes a character to the buffer.
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 :
1) PrintWriter(outputstream out) :
Creates a new print writer without automatic line flushing from existing
output stream.
3) PrintWriter(writer out) :
Creates a new print writer without automatic line flushing.
Methods :
1) void flush() :
It flushes the stream.
2) void close() :
3) print() or println() :
Used to print any type of data including objects.
6) void write(int c) :
Writes a character to the buffer.
7) void write(String s) :
Writes a string.
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 :
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() :
4) void write(int c) :
Writes a character to the buffer.
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 :
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() :
4) void write(int c) :
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 :
Class File :
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 :
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.
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();
}
}
abcdefgheabcdefg
fghikklmnfghijklm
Ctrl+Z
abcdefgheabcdefg
fghijklmnfghijklm
nopqrtstnopqrts
tuvwxyztuvwxyz
Ctrl+Z
nopqrtstnopqrts
tuvwxyztuvwxyz
abcdefgheabcdefg
fghikklmnfghijklm
Ctrl+Z
abcdefgheabcdefg
fghijklmnfghijklm
nopqrtstnopqrts
tuvwxyztuvwxyz
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 :
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 :
Constructors :
1) FileWriter(File file) :
3) FileWriter(String fileName) :
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 :
Constructors :
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 :
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.
Program : ran1.java
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.
Program : ran2.java
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.
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.
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.
Methods :
2) boolean add(Object o) :
Appends the specified element to the end of this vector.
4) int capacity() :
Returns the current capacity of vector.
5) void clear() :
Removes all these elements from this vector.
7) Object firstElement() :
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.
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 :
Returns :
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 :
Methods :
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