Ilovepdf Merged (1)
Ilovepdf Merged (1)
Java Lecture-1
Topic: Chapter-1 Introduction
JAVA History:
Java is certainly a good programming language. There is no doubt that it is
one of the better language available to serious programmers.
This goal had a strong impact on the development team to make the
language simple, portable and highly reliable. The Java team, which
included Patrick Naughton, discovered that the existing languages like C
and C++ had limitations in terms of both reliability and portability.
However, they modeled the new language Java on C and C++ but removed
a number of features of C and C++ that were considered as sources of
problems and thus made Java a really simple, reliable, portable, powerful
language.
Advantage of JAVA:
One obvious advantage is a runtime environment that provides platform
indepen-dence: you can use the same code on Windows, Solaris, Linux,
Macintosh, and so on.
Java is also fully object oriented — even more so than C++. Everything in
Java, except for a few basic types like numbers, is an object.
The key point is this: It is far easier to turn out bug-free code using Java
than using C++.
Java Lecture-2
Topic: Features of Java
Features of JAVA:
The inventors of Java wanted to design a language which could offer solutions to
some of the problems encountered in modern programming. They wanted the
language to be not only reliable, portable and distributed but also simple,
compact and interactive. Sun Microsystems officially describes Java with the
following features:
3. Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A platform
is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based.
Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it
is a software-based platform that runs on the top of other hardware-
based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming
Interface)
Java code can be run on multiple
platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler
and converted into bytecode. This
bytecode is a platform-independent
code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere(WORA).
6. Distributed
It is design as a distributed language for creating applications on
network. It has ability to share both data and program.
Java application can open and access remote objects on internet as
easily as they can do in local system.
7. Multithreaded
A thread is an independent path of execution within a program,
executing concurrently. Multithreaded means handling multiple tasks
simultaneously or executing multiple portions (functions) of the same
program in parallel.
This means that we need not wait for the application to finish one task
before beginning others.
1. Application:
An application is a program that runs on your computer under the
operating system of that computer. That is, an application created by
Java is same as an application created in C and C++.
When java is used to create application, it is not much different from
any other computer language.
2. Applet
An applet is a java program designed to be transmitted over the internet
and executed by a java comp[atatible web browser.
Applets are program that requires a browser to run. Applet always
embedded in web page.
Java Lecture-3
Topic: Difference between C++ and Java
Types of Java Programs
Java can be used to create two types of program.
1. Application
2. Applet
1. Application:
An application is a program that runs on your computer under the
operating system of that computer. That is, an application created by
Java is same as an application created in C and C++.
When java is used to create application, it is not much different from
any other computer language.
2. Applet
An applet is a java program designed to be transmitted over the internet
and executed by a java comp[atatible web browser.
Applets are program that requires a browser to run. Applet always
embedded in web page.
C++ Java
Text Editor
Javac Compiler
Java Header
Class javah
Files
File
java Interpreter
Java
Program
Output
6. Applet Package(java.applet) :
This includes a set of classes that allows us to create Java applets.
Java Lecture-4
Topic: JDK, JRE, JVM, GC, Bytecode
Byte Code :
In Java Byte Code is an intermediate code generated by the Java
compiler.
It is executed by JVM.
Byte code is a compiled format of Java Program and it has (.class)
extension.
Java Lecture-5
Topic: Chapter-2 Beginning With Java
class First
{
public static void main(String[] args)
{
System.out.println ( "Hello Java World”);
}
}
First and foremost, Java is case sensitive. If you made any mistakes in
capitalization (such as typing Main instead of main), the program will not
run.
The keyword class is there to remind you that everything in a Java program
lives inside a class.
You need to make the file name for the source code the same as the name
of the class, with the extension .java appended. Thus, we must store this
code in a file called First.java
6) Type variable name as Path and Paste the bin folder address by
clicking right click and selecting paste menu.
7) Click on ok - ok - ok
Java Lecture- 6
Topic: Primitive Data Types in Java And Operators
Variable:
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in the
memory.
Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.
Operators:
Operators are special symbol which represents particular operation in
program.
Java provides a rich set of operators to manipulate variables. We can divide
all the Java operators into the following groups.
Arithmetic Operators:
In Java there are five arithmetic operators they are as follows
+ Addition
- Substraction
* Multiplication
/ Division (Gives Quotient)
% Modulus (Gives Remainder)
Relational Operator:
In Java there are six relational operators. Relational operators always
evaluate either true or false. Following are the relational operators
< Less than
> Greater than
<= Less than or equals to
>= Greater than or equals to
== Equals to
!= Not Equal to
Logical Operators:
Logical operators are use to take a decision from more than one condition.
Or They are use combine multiple condition. There are three logical
operators in Java. They are as follows
Operator Name Description
&& Logical Returns true if both statements are
and true
|| Logical or Returns true if one of the statements
is true
! Logical Reverse the result, returns false if the
not result is true
Conditional Operator:
The conditional operator is also known as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean
expressions.
The goal of the operator is to decide; which value should be assigned to
the variable. The operator is written as:
Syntax:
Variable = (Boolean expression) ? value if true : value if false;
For example following program finds maximum between two numbers
using ternary operator
class Test
{
public static void main(String [] args)
{
int x=10,y=20,max;
max = (x>y) ? x : y;
System.out.println(“Max=”+max);
}
}
Java Lecture-7
Topic: Type Casting Operator
Type casting is nothing but assigning a value of one primitive data type to
another.
The cast is performed by placing the desired type in parenthesis to the left of
the value to be converted.
For Ex :
int n = (int) 23.135; // converts double (23.135) to an integer
Destina Source
tion
Rules in type casting
(a) If source and destination of the same type. No casting is required.
(b) If source is of smaller size than destination then no casting is
required.
e.g. int to long or float to double
(c) If destination is of smaller size than source then casting is
required.
e.g. long to int or double to float
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Widening Casting:
This type of casting takes place when two data types are automatically
converted. It is also known as Implicit Conversion.
This happens when the two data types are compatible and also when we
assign the value of a smaller data type to a larger data type.
For Example int type to long type or float type to double type.
Narrowing Casting:
In this case, if you want to assign a value of larger data type to a smaller
data type, you can perform Explicit type casting or narrowing.
For Example long type to int type or double type to float type.
System.out.println(ch);
}
}
Output: A
Java Lecture- 8
Topic: Reading Input from Console
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
class Sqaure
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,s;
s=n*n;
System.out.println("Sqaure = "+s);
}
}
Output
import java.util.*;
class Addition
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int x,y,add;
add=x+y;
System.out.println("Addition="+add);
System.out.println("Addition of "+x+" and "+ y +" is "+add);
System.out.println(x + "+" + y +" = "+add);
}
}
Output:
Control Structures
If for
If..else while
Nested If else do..while
Switch case for..each
if
if statement is the most simple decision making statement.
It is used to decide whether a certain statement or block of
statements will be executed or not
i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
if(n>0)
System.out.println(n+" is +ve number ");
if(n<0)
System.out.println(n+ " is -ve number ");
}
}
OUTPUT
Course: Java Programming Prepared By: Atul Kabra, 9422279260
if-else:
In if else, if the condition is true then if part is executed and if
condition is false then else part is executed.
We can use the else statement with if statement to execute a block
of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
class PN
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
if(n>0)
System.out.println(n+" is +ve number ");
else
System.out.println(n+ " is -ve number ");
}
}
Course: Java Programming Prepared By: Atul Kabra, 9422279260
nested-if:
A nested if is an if statement that is the target of another if or else.
Nested if statements means an if statement inside an if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
import java.util.*;
class MaxThree
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
if(x>y)
{
if(x>z)
System.out.println("Max = "+x);
else
System.out.println("Max = "+z);
}
else
{
Course: Java Programming Prepared By: Atul Kabra, 9422279260
if(y>z)
System.out.println("Max = "+y);
else
System.out.println("Max = "+z);
}
}
}
OUTPUT:
if-else-if ladder:
Here, a user can decide among multiple options.
The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the
ladder is bypassed.
If none of the conditions is true, then the final else statement will be
executed.
Syntax
if (condition)
Course: Java Programming Prepared By: Atul Kabra, 9422279260
statement;
else if (condition)
statement;
.
.
else
statement;
Course: Java Programming Prepared By: Atul Kabra, 9422279260
switch-case
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
The java for loop is used to iterate a part of the program several times. If
the number of iteration is fixed, it is recommended to use for loop.
The java while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed, it is recommended to use
while loop.
The java do-while loop is used to iterate a part of the program several
times. Use it if the number of iteration is not fixed and you must have to
execute the loop at least once.
Course: Java Programming , Prepared By: Atul Kabra, 9422279260
For Loop:
Syntax:
for(initialization; condition; incr/decr)
{
//statement or code to be executed
}
for loop is the same as C/C++. We can initialize the variable, check
condition and increment/decrement value.
class TableN
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,i;
System.out.println("Enter the number ");
n= in.nextInt();
System.out.println("Multiplication Table of "+ n);
for(i=1;i<=10;i++)
{
System.out.println(n*i);
}
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260
for(i=100;i<=200;i++)
{
if(i%7==0)
System.out.println(i);
}
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260
class SumN
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,i,sum=0;
System.out.println("Enter the number ");
n= in.nextInt();
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println("Sum="+sum);
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260
class Factorial
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,i,fact=1;
System.out.println("Enter the number ");
n= in.nextInt();
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("Factorial="+fact);
}
}
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-11
Topic: break statement , while loop
break Statement:
The break statement has the following two usages
If you are using nested loops, the break statement will stop the
execution of the innermost loop and start executing the next line of
code after the block.
break;
Example Output:
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
if(i==5)
break;
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class Prime
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,i;
System.out.println("Enter the number ");
n = in.nextInt();
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
While Loop :
Loops are used to execute a set of statements repeatedly until a
particular condition is satisfied.
while(condition)
{
statement(s);
}
In while loop, condition is evaluated first and if it returns true then the
statements inside while loop execute.
When condition returns false, the control comes out of loop and jumps
to the next statement after while loop.
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.println("Info Planet");
i++;
}
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class SumOfDigits
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n, r, sum=0;
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
System.out.println("Sum of Digits = "+sum);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class PalindromeNumber
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n, r, rev=0,temp;
System.out.println("Enter the number ");
n = in.nextInt();
temp=n;
while(n!=0)
{
r=n%10;
rev = rev*10+r;
n=n/10;
}
if(temp==rev)
System.out.println(temp+" is Palindrome Number");
else
System.out.println(temp+" is not a Palindrome Number");
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
do-while :
Unlike for and while loops, which test the loop condition at the top of
the loop, the do...while loop checks its condition at the bottom of the
loop.
Syntax
do {
statement(s);
} while( condition );
Notice that the Boolean expression appears at the end of the loop, so
the statements in the loop execute once before the Boolean is
tested.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class DoWhile
{
public static void main(String args[])
{
int i=1;
do{
System.out.println(i + " Info Planet");
i++;
}while(i<=10);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
while do-while
While loop is executed only when given Whereas, do-while loop is executed
condition is true. for first time irrespective of the
condition. After executing while
loop for first time, then condition is
checked.
While is entry controlled loop. do-while is exit controlled loop.
In while loop condition is checked at In do-while condition is checked at
top of loop. bottom of loop.
Syntax : Syntax:
while(condition){ do{
Statement(s); Statement(s);
} }while(condition);
The advantage of each loop is that its elements the possibility of error
and makes the code more readable.
Syntax
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class ForEach
{
public static void main(String args[])
{
int [] a = {10,20,30,40,50};
for(int x : a)
{
System.out.println(x);
}
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Nested Loop:
Nesting of loops is the feature in Java that allows the looping of
statements inside another loop.
Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops.
The nesting level can be defined at n times. You can define any type of loop
inside another loop; for example, you can define 'while' loop inside a 'for'
loop.
Syntax
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class NestedFor
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
} // end of inner for
System.out.println();
}// end of outer for
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-13
Topic: String class
String:
Strings are sequence of characters or collection of characters.
Java does not have a built-in string type instead the standard java library
contains a pre-defined class called "String"
"String" class is declared in "java.lang" package.
Java string is immutable (not changeable).
Each quoted string is an object of the String class:
String e = ""; // an empty string
String greeting = "Hello" ;
String Concatenation :
Java allows you to use '+' sign to concatenate two strings together.
For Ex.:
(a) We can concatenate two strings using +
e.g. String s1 = "Info Planet", s2 = "Jalgaon",s3;
String s3=s1+s2;
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-14
Topic: Constructor and Methods of String Class
2. String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the
platform's default charset.
3. String(char[] value)
Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.
4. String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently
contained in the string buffer argument.
2. charAt ( )
This method returns the character from specified index of the string
Syntax : char charAt (int index)
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
3. indexOf()
This method is used to find the index of character in the String. It is
overloaded.
(a) indexOf ( )
This method returns an index of first occurrences of character in
the string. If character is not present in the string, then it returns -1.
Syntax : int indexOf (char ch)
For ex : String s = "Hello World";
int x = s.indexOf ('o');
System.out.prinln ("x=" +x);
Output: x=4
4. lastIndexOf ( )
Returns the index within the string of the last occurrence of the
specified character.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
5. equals ( )
This method compares two strings for equality. Returns True, if strings
are equal, otherwise returns false.
Syntax : boolean equals (String other)
For ex : String s1 = "Hello", s2 = "Info";
If (s1.equals (s2))
System.out.println ("strings are equal");
else
System.out.println ("strings are not equal");
Output: Strings are not equal.
6. equalsIgnoreCase ( )
This method compares two strings for equality, ignoring case consideration.
Syntax : boolean equalIgnoreCase (String other)
For ex : String s1 = "Hello", s2 = "HELLO";
if (s1.equalsIgnoreCase (s2))
System.out.println ("Strings are equal");
else
System.out.println ("Strings are not equal");
Output: Strings are equal
7. compareTo ( )
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
8. endsWith ( )
Test if the string ends with specified string.
Syntax : boolean endsWith (String str)
For Ex. : String s = "xyz@gmail.com";
if (s.endsWith ("gmail.com"))
System.out.println(“Gmail Account”);
else
System.out.println(“Not a Gmail Account”);
Output: Gmail Account
9. startsWith ( )
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
10. getBytes ( )
Rerutns the string into a sequence of bytes using platforms default
character set.
Syntax : byte[] getBytes()
For Ex: String str = "Hello";
byte [ ] b = str.getBytes ( ) ;
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
11. toLowerCase ( )
Converts all the Upper Case letters of the string in to lower case
Syntax : String toLowerCase ( )
12. toUpperCase( )
Converts all the lowerCase letters of the string into Uppercase.
Syntax : String toUpperCase ( )
13. trim( )
Removes any leading and trailing spaces from String.
Syntax: String trim()
14. substring ( )
This method returns a string that is a substring of this string.
substring ( ) method has two forms :
(a) Syntax: String substring (int beginindex)
This method returns a substring from begin index up to
end of string.
(b) Syntax: String substring (int beginindex, int endindex)
This method returns substring from begin index up to end
index-1 because End index is exclusive.
For ex. : String s ="Info Planet";
String t = s.substring (5);
String p = s.substring(5,9);
System.out.println(t);
System.out.println (p);
Output: Planet
Plan
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class StringLength
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int x = str.length();
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class StringVowel
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int c=0;
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
c++;
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class StringPalindrome
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
String rev="";
for(int i=str.length()-1;i>=0;i--)
{
char ch = str.charAt(i);
rev=rev+ch;
}
if(str.equals(rev))
System.out.println(str+ " is Palindrome String");
else
System.out.println(str+ " is not a Palindrome String");
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming,Prepared By: Atul Kabra, 9422279260
Java Lecture- 16
Topic: StringBuffer Class
2. insert()
This method inserts one string into another.
Syntax: StringBuffer insert(int index, T value)
Here the first parameter gives the index at which position the
string will be inserted and T representation of second
parameter is inserted into StringBuffer object.
Here T can be any type like String, int , float, char etc.
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.insert(5, “Java”);
System.out.println(sb);
Ouput: HelloJavaWorld
3. delete ()
This method removes the characters from the string.
Syntax: StringBuffer delete (int start, int end)
This method is used to delete the string from specified
startIndex and endIndex. Here endindex is exclusive.
Example: StringBuffer sb = new StringBuffer(“HelloJavaWorld”);
sb.delete(5,9);
System.out.println(sb);
Ouput: HelloWorld
4. deleteCharAt()
This method removes the character at the specified index character from
the string.
Syntax: StringBuffer deleteCharAt (int index)
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.deleteCharAt(4);
System.out.println(sb);
Ouput: HellWorld
5. replace ()
This method replaces the specified string from specified start index to the
end index.
Syntax: StringBuffer replace (int start, int end, String newString)
Example: StringBuffer sb = new StringBuffer(“HelloJavaWorld”);
sb.replace(5,9,”InfoPlanet”);
System.out.println(sb);
Ouput: HellInfoPlanetWorld
6. reverse()
This method reverses the characters within a StringBuffer object.
Syntax: StringBuffer reverse ()
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.reverse();
System.out.println(sb);
Ouput: dlroWolleH
Java Lecture-18
Topic: Array
An array is a data structure that stores a collection of values of the same type.
You can access each individual vale through an integer index.
The first element of array is at 0th index, second is at 1st index and so on…
In Java, array is manipulated by reference variable of appropriate type.
Syntax to create an Array:
length Field :
In Java, we can use "length" field with array reference to find the length
(number of elements of an array)
For Example :
int [ ] a = new int [5];
int [ ] b = new int [3];
System.out.println(a.length);
System.out.println(b.length);
Output: 5
3
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Array Initialization :
Implicit Initialization :
In Java, the default values for any numeric array is zero.
For character array, default value is null ('\0').
For boolean array, default value is false.
Explicit Initialization :
Bounds Checking :
When your program is running and it tries to access an element of an
array, the Java virtual machine checks that the array element actually
exists. This is called bounds checking.
If your program tries to access an array element that does not exist, the
Java virtual machine will generate an: ArrayIndexOutOfBoundsException
For Example:
int [] a ={10,20,30,40,50};
System.out.println(a[8]);
Output: ArrayIndexOutOfBoundsException
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-19
Topic: Programs on Array
1) Write a program to create an array of size 5 and then read and print the
numbers of an array.
import java.util.*;
class ArrayInput
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
import java.util.*;
class ArraySum
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Sum = "+sum);
System.out.println("Average = "+avg);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-20
Topic: Programs on Array of Strings
1) Write a program to read five strings and then print the length of each
string.
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String [] s = new String[5]; //Array of String
System.out.println("Enter "+s.length+" Strings");
for(int i=0;i<s.length;i++)
s[i] = in.nextLine();
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
2. Write a program to read five names (Strings) and then print only those
names which are starts with A or a.
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String [] s = new String[5]; //Array of String
System.out.println("Enter "+s.length+" Names");
for(int i=0;i<s.length;i++)
s[i] = in.nextLine();
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-21
Topic: Arrays Class
Arrays class :
This class contain various methods for manipulating arrays such as sorting
and searching. This class declared in java.util package.
Methods of Arrays class.
i) binarySearch ():
Syntax :
static int binarySearch (int [ ] a, int key)
This method searches the specified array of integers for the specified
value using binary search algorithm.
It returns an index of the key value if it returns an index of the key value
if it present, otherwise it returns negative number. This method is
overloaded for all numeric types.
For Example
import java.util.*;
class Sample
{
public static void main(String [] args)
{
int[] a = {10,20,30,40,50,60,70,80,90,100};
int n=60;
int x = Arrays.binarySearch(a,n);
if(x>=0)
System.out.println(n+" is found at "+x +" index");
else
System.out.println(n+" is not found in the array");
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Output
ii) equals ( )
Syntax :
static boolean equals (int [ ] a1, int [ ]a2)
This method returns true if the two specified arrays of integers are
equal to one another.
For Example
import java.util.*;
class Sample
{
public static void main(String[] args)
{
int [] a1 = {10,20,30,40,50};
int [] a2 = {10,20,30,40,50};
if( Arrays.equals(a1,a2))
System.out.println("Both Array are equal");
else
System.out.println("Both Array are not equal");
}
}
Output
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
iii) fill ( )
Syntax :
static void fill (int [ ], int val)
This method assigns the specified int value to each element of the
specified array of integers.
iv) sort ( )
Syntax :
static void sort (int [ ] a)
This method sorts the specified array into ascending numerical order.
It uses quick sort algorithm.
v) toString ( )
Syntax :
static String toString (int [ ] a)
This method returns a string representation of the contents of the
specified array.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Arrays.sort(a);
}
}
Output
Note: All above methods are overloaded for all data types
like float, double, char etc.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-22
Topic: Command Line Arguments
Any argument provided on command line passed to the array args as its
element.
We can write the program that can receive and use the arguments
provided on the command line.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class CmdLine
{
public static void main(String [] args)
{
System.out.println("Number of command line arguments =
"+args.length);
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class CmdConcat
{
public static void main(String [] args)
{
String s1=args[0];
String s2=args[1];
String s3=s1+s2;
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class CmdSum
{
public static void main(String [] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int add=x+y;
System.out.println("Addition = "+add);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-23
Topic: Math Class
Math class:
The class "Math" contains methods for performing basic numeric
operations such as exponential logarithm, square root and trigonometric
functions.
The math class is declared in java.lang package.
This class has two constants E(Eural) and PI.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
2) exp () method :
Syntax :
static double exp (double a)
This method returns number e raised to the power of a specified value,
where e is the Euler constant.
For Example
class Test
{
public static void main (string args [ ])
{
System.out.println (Math.exp(5));
}
}
Output: 148.413159
3) log ( ) method
Syntax :
static double log (double a)
This method returns the natural logarithm (base e) of a specified value.
For Example
class Test
{
public static void main (String args [ ])
{
System.out.println (Math.log(50));
}
}
Output: 3.912
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
4) log 10 ( ) method
Syntax :
static double log10 (double a)
This method returns the base 10 logarithm of a specified value.
ForExample
class Sample
{
public static void main (String args [ ])
{
System.out.println (Math.log10(50));
}
}
Output
5) max ( )
Syntax :
static T max (T a, T b)
This method returns the greater between the specified value a & b.
Here T can be any number type like int, float etc.
6) min ( )
Syntax :
static T min (T a, T b)
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
7) pow ( ) method
Syntax :
static double pow (double a, double b)
This method returns the value of the first arg raised to the power of the
second argument i.e. a^b.
For Exmaple
class Sample{
public static void main (String args [ ])
{
System.out.println ("2 ^ 5 ="+ Math.pow(2,5));
}
}
Output: 2^5 = 32.0
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
8) sqrt ( ) method
Syntax :
static double sqrt (double a)
This method returns the square root of a specified value.
For Example
import java.util.*;
class Sample
{
public static void main (String args [ ])
{
Scanner in = new Scanner (System.in);
System.out.println ("Enter the no");
int n = in.nextInt();
System.out.println ("Square root of "+n+" is "+Math.sqrt (n));
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
9) floor ( ) method
Syntax :
static double floor (double a)
This method returns the double value that is less than or equal to
the argument and is equal to the nearest mathematical integer.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Trignometric Methods
11) cos ()
Syntax:
static double cos(double a)
This method returns the trigonometric cosine of an angle.
12) sin ( )
Syntax:
static double sin (double a)
This method returns the trigonometric sin of an angle.
13) tan ( )
Syntax:
static double tan (double a)
This method returns the tan of an angle.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-24
Topic: Chapter-3 Classes And Objects
Encapsulation :
Encapsulation is nothing more than combining data and functions in one unit
and hiding the implementation of the data from the user of the object.
Class :
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are
common to all objects of one type.
It is a logical entity. It can't be physical.
A class in Java can contain: Fields, Constructors, Methods
Syntax for class declaration :
class <Class_name>
{
Fields;
Constructors();
Methods();
}
The data in an object are called its instance fields, and the functions and
procedures that operate on the data are called its methods.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Object:
An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
//methods declaration
public void getData()
{
Scanner in = new Scanner(System.in);
Java Lecture-25
Topic: Array of Objects, Constructor
Array of Objects:
If you want to store a single object in your program, then you can do so
with the help of a variable of type object. But when you are dealing with
numerous objects, then it is advisable to use an array of objects.
Actually it is not the object itself that is stored in the array but the
references of the object.
The following program shows the initialization of array objects using the
constructor.
import java.util.*;
class Emp
{
int emp_no;
String name;
double salary;
void getData()
{
Scanner in = new Scanner(System.in);
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
void putData()
{
System.out.println("\t"+emp_no+"\t\t"+name+"\t\t"+salary);
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Field Intialization :
1) Default Field Initialization :
If we don't set a field explicitly, then it is automatically initialize
to default value,
Numeric field is initialize with 0,
Character field is initialize with '\0',
Boolean field is initialize with false and
Object reference field is initialize with null.
class MyDate
{
int day=25; //Explicit field initialization
String month="January";
int year=2020;
void display()
{
System.out.println("Date is : "+day+" "+month+" "+year);
}
public static void main(String [] args)
{
MyDate d = new MyDate();
d.display();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Constructor :
Constructor which construct the object in the memory of the computer it is
also used to initialize the fields of an object.
Properties of Constructor
Name of constructor is as same that of class name.
It does not have any return data type.
It may take '0' or more argument.
It can be overloaded.
Constructor is invoked, whenever an object is created.
Types of Constructor :
There are two types of constructor in Java.
1) Default constructor :
A constructor which does not take any parameter is referred as default
Constructor.
2) Parametorized Constructor :
A constructor which takes one or more parameter, is referred as
parameterize constructor.
Note :
i) Java does not support copy constructor.
ii) Default constructor is automatically added when we does not define
any constructor in a class.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
void show()
{
System.out.println("Time is : "+hours+":"+minutes+":"+seconds);
}
t1.show();
t2.show();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-26
Topic: Static Field And Static Method, Final Field And Finalize method.
Static field :
Sometimes there may be a situation when objects of a particular class
may share some common item of data. In such situation static field is
use.
A field of class which share common value among all objects, then it
declared as static field.
Syntax :
static <datatype> <field>;
Static method :
A method of class can be declared as static method by preceding it’s
declaration with keyword "static".
Syntax to declare static method:
Final field :
We can define a field as final. Such a field must be initialize when the
object is constructed.
Final field, promising that we won't change the value of it during program
execution.
finalize ( ) method
Java does automatic garbage collection. So, manual memory de-allocation
is not needed and therefore, java does not support destructors.
Of course, some object utilize a resource other than memory, such as file
or a graphic resource, network connection, database connection.
The finalize method will be called before the garbage collector, destroy
the object from the memory.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-27
Topic: Packages
Package
In small projects, all the java files have unique names. So, it is not difficult
to put them in a single folder.
But, in the case of huge projects where the number of java files is large, it is
very difficult to put files in a single folder because the manner of storing
files would be disorganized.
Moreover, if different java files in various modules of the project have the
same name, it is not possible to store two java files with the same name in
the same folder because it may occur naming conflict.
Package in Java
A package is nothing but a physical folder structure (directories) that
contains a group of related classes, interfaces, and sub-packages according
to their functionality.
It provides a convenient way to organize your work. The Java language has
various in-built packages.
For example, java.lang, java.util, java.io, and java.net. All these packages
are defined as a very clear and systematic packaging mechanism for
categorizing and managing.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
2. User-defined Package
The package which is defined by the user is called a User-defined
package. It contains user-defined classes and interfaces.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-28
Topic: Creating Our Own Package
ii) Define the class that is to be put in the package and declare it public.
iii) Create a subdirectory under the directory where the main source file is
stored.
vi) Provide the import statement in the main program to import the
classes of our package.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
import Statements :
There are two methods to create an object of class declared in other
package.
1) By using full qualified Name :
In this method, we have to add the full package name in front of every
classname. For Example
class test
{
public static void main (String [] args)
{
java.util.Date d = new java.util.date();
System.out.println(d);
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-29
Topic: Inheritance
Inheritance :
Creating a new class from existing class is referred as Inheritance. OR
When one class acquires the properties of another class then it is referred
as inheritance.
Existing class from which new class is created is referred as super class.
Syntax of Inheritance :
Base Class
Super class
Derived Class
Sub Class
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Types of Inheritance
There are three types of Inheritance in Java
(1) Single Inheritance
(2) Multi-level Inheritance
(3) Hierarchical Inheritance
Note : Java does not support multiple and hybrid inheritance. But this
concept is implemented by using an interface.
1) Single Inheritance :
If there is only one subclass and only one super class then it is referred
as single inheritance
Super class
Sub Class
void setX(int a)
{
x=a;
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class B extends A
{
int y;
void setY(int a)
{
y=a;
}
void display()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
public static void main(String [] args)
{
B b = new B();
b.setX(10);
b.setY(20);
b.display();
}
}
Output: x=10
y=20
2) Multi-level Inheritance
When a class extends a class, which extends another class then this is
called multilevel inheritance. For example class C extends class B and
class B extends class A then this type of inheritance is known as
multilevel inheritance.
A
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
3) Hierarchical Inheritance :
It two or more classes are derived from same base class, then it is referred as
hierarchical inheritance.
B C
class B extends A class C extends A
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-30
Topic: ‘super’ keyword
Use of Super :
Whenever a subclass needs to refer to its immediate super class, it can do so
by use of the keyword "super".
There are two uses of super
1) Using super() method to call a super class constructor.
2) Using super keyword to access the hidden member of super class in
subclass.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
int age;
Person(String s, int a)
{
name=s;
age=a;
}
}
class Employee extends Person
{
double salary;
Employee(String s, int a, double sal)
{
super(s,a); // calls super class constructor
salary=sal;
}
void display()
{
System.out.println("Emp_Name : "+name);
System.out.println("Emp_Age : "+age);
System.out.println("Emp_Salary: "+salary);
}
}
class SuperTest
{
public static void main(String [] args)
{
Employee e = new Employee("Atul",45,50000.0);
e.display();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-31
Topic: Method Overloading and Method Overriding
Method Overloading :
Overloading occurs if several methods have the same name but different
parameters.
The compiler call the correct method by matching the parameter types of
the various methods with the types of values used in the specific method
call.
A Compile Time error occurs if the compiler cannot match the parameter.
Example:
class sample
{
int max (int a, int b)
{
if (a > b)
return (a);
else
return (b);
}
double max (double a, double b)
{
if (a>b)
return (a);
else
return (b);
}
public static void main(String [] args)
{
Sample s = new Sample ( );
System.out.println (“Maximum between 10 & 20 is” + s.max (10, 20));
System.out.println (“Maximum between 3.4 and 1.7 is” + s.Max (3.4, 1.7));
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Method Overriding :
In Inheritance, when a method in a subclass has the same name and
same parameters list as a method in it super class, then the method in
the subclass is said to override the method in the super class.
Example :
class A
{
void display ( )
{
System.out.println(“From A class display”) ;
}
}
class B extends A
{
void display ( )
{
System.out.println (“From B class display”);
}
public static void main(String [] args)
{
B b = new B ( );
b.display ( ) ;
}
}
Output: From B class display.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-32
Topic: Dynamic Method Dispatch
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class DMDTest
{
public static void main(String [] args)
{
A ref ; //super class reference
ref = new A(); //refers to A class Object
ref. display (); //calls A class display()
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-33
Topic: Abstract Method And Abstract Class
Abstract Method :
In Inheritance, we have some methods which must be overridden by the
subclass.
In this case, we want some way to ensure that a subclass must override all
necessary methods.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Abstract Class :
(i) Any class that contains one or more abstract method must also be
declared as an abstract.
(iii) We can't create an object of an abstract class but we can create the
reference.
Shape(double a, double b)
{
dim1=a;
dim2=b;
}
abstract void area();
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class AbstractTest
{
public static void main(String [] args)
{
Shape s; //s is reference
//s=new Shape(10,10); Error, can't create object of abstract class
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-34
Topic: final keyword
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
System.out.println ("illegal");
}
}
3) To prevent Inheritance :
Sometimes we want to prevent a class from being inherited. To do this
precedes the class declaration with keyword final. Declaring a class as
final, implicitly declares all of its method as final too.
For example :
final class A
{ ----
----
----
}
class B extends A // error can't subclass A
{ ----
----
----
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-35
Topic: Access Specifiers in Java
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-36
Topic: Object class
The object class is the parent class of all the classes in Java by default.
Every class of Java is either directly or indirectly inherited from object class.
The object class is beneficial, if you want to refer any object whose type you
don’t know at run-time.
2. equals()
This method checks whether two objects are equal or not.
3. finalize()
This method is called by the garbage collector when object is destroyed
form the memory.
4. getClass ()
Returns the run-time class of an object.
5. toString ()
Returns a string representation of an object.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class Employee
{
int emp_no;
String name;
double salary;
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-37
Topic: Chapter-5 Interface And Inner Classes
Interface
An interface is just same as abstract class.
The main difference between an interface and abstract class is, interface
is fully unimplemented, whereas abstract class is partially
unimplemented.
interface interface_name
{
void method1 ();
void method2 ();
……….
}
Properties of an interface
1. By default all the methods in an interface are abstract.
2. The default access specifier for an interface is public.
3. Object of an interface cannot be created.
4. Reference of an interface can be created.
5. Inside interface the field is static by default.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Implementing an Interface :
Implementing on interface is similar to deriving from class except that
you are required to implement all methods defined in the interface.
Area Shape
<<interface>> <<class>>
extends
implements
Rectangle Triangle
<<class>> <<class>>
interface Area
{
void compute();
}
class Shape
{
double dim1, dim2;
Shape(double a, double b)
{
dim1=a;
dim2=b;
}
}
class InterfaceTest
{
public static void main(String [] args)
{
Area ref;
ref = new Rectangle(10,10);
ref.compute();
Extending An Interface
Like classes interfaces can also be extended.
That is an interface can be sub interfaced from other interfaces.
The new interface will inherit all the member of the super interface in
the manner similar to subclass. This is achieved using the keyword
extends.
Syntax
Points to Remember:
One class can extends another class.
One interface can extends another interface.
Class can implements other interfaces.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-38
Topic: Inner Classes
Inner class
If the class is declared inside another class, then it is referred as inner
class.
OR
Inner class means one class which is a member of another class.
class Outer
{
class Inner
{
………..
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class Outer
{
void method ()
{
class LocalInnerClass
{
………………………..
}
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class Test
{
public static void main(String[] args)
{
A a = new A()
{ //Anonymous class
public void display()
{
System.out.println("Display Method");
}
public void info()
{
System.out.println("Info Method");
}
};
a.display();
a.info();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-39
Topic: Chapter-6 Wrapper Classes And Vector
Wrapper Class :
A wrapper class is a class whose object wraps or contains primitive data
type.
In other words we can wrap a primitive data type into a wrapper class
object.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-40
Topic: Vector
Vector
The vector class implements a growable array of objects or Vector
implements a dynamic array that means, it can grow during program
execution.
Vector cannot store primitive types but using wrapper classes, we can
convert primitive type to object and then store in the vector.
Constructors of Vector
1) Vector()
Construct an empty vector with default size of 10 and capacity
increment is double.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
4) int capacity ()
Returns the current array size of the vector.
5) int size ()
Returns the current number of elements in the vector.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Array Vector
1) Size of Array need to be 1) No need to declare the size of
declared in advanced. vector.
2) Once declared array can't grow 2) Vector can always grow in size.
in size.
3) Array can store primitive types 3) Vector can store only objects.
like int, float etc.
4) No built-in methods are 4) Vector class has numbers of
provided to add, remove, and methods to add, remove, and
search the element in array. search the element which saves
the development time.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
WAP program to create a vector with seven elements as [10, 30, 50, 20, 40, 80,
60]. Remove element at 3rd position. Insert 100 at 3rd position. Display the
current size of the vector.
import java.util.*;
class Test {
public static void main(String[] args)
{
Vector<Integer> v = new Vector<Integer>(); //create an empty vector
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-41
Topic: Colletion Framework Part-A
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Collection Hierarchy
List Interface
List interface is the child interface of Collection interface.
It inhibits a list type data structure in which we can store the ordered
collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector,
and Stack.
Set Interface
Set Interface in Java is present in java.util package.
It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store
the duplicate items.
Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-42
Topic: Colletion Framework Part-B
ArrayList
The ArrayList class implements the List interface.
It uses a dynamic array to store the duplicate element of different data
types.
The ArrayList class maintains the insertion order and is non-synchronized.
The elements stored in the ArrayList class can be randomly accessed.
Vector
Vector uses a dynamic array to store the data elements.
It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the
part of Collection framework.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
5) ArrayList uses the Iterator 5)A Vector can use the Iterator
interface to traverse the elements. interface or Enumeration
interface to traverse the elements
LinkedList
LinkedList implements the Collection interface.
It uses a doubly linked list internally to store the elements.
It can store the duplicate elements.
It maintains the insertion order and is not synchronized.
In LinkedList, the manipulation is fast because no shifting is required.
For Example
import java.util.*;
class Test
{
public static void main(String [] args)
{
LinkedList <String> list = new LinkedList<String>();
System.out.println(list);
list.add("Atul");
list.add("Ajay");
list.add("Kedar");
list.add("Nilesh");
System.out.println(list);
list.add(1,"Info");
System.out.println(list);
System.out.println("Deleted item from index 1 is
:"+list.remove(1));
System.out.println(list);
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
ArrayList LinkedList
1) ArrayList internally uses a dynamic LinkedList internally uses a doubly
array to store the elements. linked list to store the elements.
2) Manipulation with ArrayList Manipulation with LinkedList
is slow because it internally uses an is faster than ArrayList because it
array. If any element is removed from uses a doubly linked list, so no
the array, all the elements are shifted shifting is required in memory.
in memory.
3) An ArrayList class can act as a LinkedList class can act as a list and
list only because it implements List queue both because it implements
only. List and Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Stack
The stack is the subclass of Vector.
It implements the last-in-first-out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o),
which defines its properties.
For Example:
stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
System.out.println(stk);
System.out.println("Popped item is :"+stk.pop());
System.out.println(stk);
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
HashSet
HashSet class implements Set Interface.
It represents the collection that uses a hash table for storage.
Hashing is used to store the elements in the HashSet.
It contains unique items.
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set
Interface.
It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements.
It maintains the insertion order.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage.
Like HashSet, TreeSet also contains unique elements.
However, the access and retrieval time of TreeSet is quite fast.
The elements in TreeSet stored in ascending order.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-43
Topic: Chapter-7 Exception Handling
Whenever the compiler displays an error, it will not create the .class file. It
is therefore necessary that we fix all the errors before we can successfully
compile and run the program.
Most of the compile time errors are due to typing mistakes. The most
common problems are
a. Missing semicolons
b. Missing (or mismatch) brackets in classes and methods.
c. Misspelling of identifiers and keywords.
d. Missing double quotes in string.
e. Use of undeclared variable.
f. Bad reference to object.
g. And many more
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
a) ArithmeticException
It occurs due to dividing number by zero.
Example:
class Test
{
public static void main(String[] args)
{
int a=10,b=5,c=5;
int x = a/(b-c);
System.out.println("x="+x);
int y = a/(b+c);
System.out.println("y="+y);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
b) ArrayIndexOutOfBoundsException
It occurs when we access an array element which is out of the bounds of an
array.
Example:
class Test
{
public static void main(String[] args)
{
int [] a = {10,20,30,40,50};
System.out.println(a[7]);
}
}
Output:
c) NegativeArraySizeException
It occurs when we use to create an array of negative size.
Example
class Test
{
public static void main(String [] args)
{
int [] a = new int[-5];
System.out.println("Array is created");
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
d) NullPointerException
It occurs by referencing null object.
Example
class Test
{
public static void main(String [] args)
{
String str=null; //referencing null object
System.out.println("Length of string is :"+str.length());
}
}
Output:
e) NumberFormatException
It occurs when conversion between string and number fails.
Example
class Test{
public static void main(String [] args) {
String str="ABCD";
int x = Integer.parseInt(str);
System.out.println("x="+x);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
f) StringIndexOutOfBoundsException
It occurs when a program attempts to access a nonexistent character
position in a string.
g) IOException
It occurs due to general input and output failure.
h) FileNotFoundException
It occurs due to opening a non existing file.
i) OutOfMemoryError
It occurs when there’s not enough memory to allocate for an array or
object.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-44
Topic: Exception handling using try-catch block.
Exception Handling
When the java interpreter encounters an Exception, it creates an
exception object and throws.
try-catch block
The Basic concept of Exception Handling is throwing and catching it. This is
illustrated in the following figure.
try block
Statement that Exception object Creator
causes an exception
Throws exception
object
catch block
Catch block Exception handler
statement that
handles an
exception.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Syntax of try-catch
try
{
Statement(s);
………. // generate an exception
}
catch (Exeptiontype e)
{
Statement(s); // process the exception
}
If any one statement within try block generates an exception, the remaining
statements in the try block are skipped and execution jumps to the catch
block. The catch block can have one or more statements that are necessary
to process the exception.
Following program demonstrate exception handling:
class Test
{
public static void main(String[] args)
{
int a=10,b=5,c=5;
try
{
int x = a/(b-c);
System.out.println("x="+x);
}
catch(ArithmeticException e)
{
System.out.println("Caught an exception");
System.out.println("Divide by zero");
}
int y = a/(b+c);
System.out.println("y="+y);
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Output:
for(int i=0;i<args.length;i++)
{
try
{
int n = Integer.parseInt(args[i]);
sum=sum+n;
}
catch(NumberFormatException e)
{
System.out.println("Invalid Integer: "+args[i]);
}
}
System.out.println("Sum="+sum);
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-45
Topic: Multiple catch block And finally Block
Syntax :
try
{
statement(s);
}
catch (ExceptionType 1 e1)
{
………
}
catch (ExceptionType 2 e2)
{
………
}
.
.
catch (ExceptionTypeN eN)
{
………
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
The first statement, whose parameter matches with the exception object,
will be executed and the remaining catch statement will skip.
Finally block :
Java supports another statement known as "finally".
It is guaranteed to be executed regardless of whether or not an exception is
occurred.
Finally block can be added after the last catch block or immediately after the
try block.
try try
{ {
Statement(s); Statement(s);
} }
catch (ExceptionType 1 e1) finally
{ {
……… ……………
} }
catch (ExceptionType 2 e2)
{
………
}
finally
{
………
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-46
Topic: Exception Hierarchy And Custom Exception
All exception and errors are the subclasses of class Throwable class, which is
base class in exception Hierarchy.
Another branch Error is used by the Java run-time system (JVM) to indicate
error to generate within JVM. We can't handle errors.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
if(age<18)
throw new InvalidAgeException("Not eligibal for voting");
else
System.out.println("Eligibal for voting");
}
catch(InvalidAgeException e)
{
System.out.println(e);
}
catch(InputMismatchException e)
{
System.out.println("Invalid Age");
}
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-47
Topic: throw and throws keyword
In Java, there are two types of exception.
1) Checked Exception :
All exceptions other than Runtime Exceptions are known as Checked
exceptions as the compiler checks them during compilation to see
whether the programmer has handled them or not.
1) Unchecked Exception :
Runtime Exceptions are also known as Unchecked Exceptions.
Compiler will never force you to catch such exception or force you to
declare it in the method using throws keyword.
Syntax :
throw new MyException ("Message");
The caller to this method has to handle the exception using try and catch
block, otherwise will get compile-time error we can handle the exception
by two ways.
Java Lecture-48
Topic: Chapter-8 Multithreading
Programs that can run more than one thread at once are said to be multi-
threaded program.
Main
Thread
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Creating Thread
Thread can be created by following two ways
1. By extending Thread class.
2. By implementing Runnable Interface
c) Create a Thread object and call the start() method to initiate thread
execution.
System.out.println("Exiting A Thread");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=30;j++)
System.out.println("B Thread : j = "+j);
System.out.println("Exiting B Thread");
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
System.out.println("Exiting C Thread");
}
}
class ThreadTest
{
public static void main(String [] args)
{
A a = new A();
B b = new B();
C c = new C();
a.start();
b.start();
c.start();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
After you create a class that implements Runnable create the object of
this class and then create the object of Thread class by using the
following constructor.
Thread (Runnable r)
Pass the object of the class which implements Runnable and then call
start() method, to initiate the execution of the thread.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class ThreadTest1
{
public static void main(String [] args)
{
Thread t1 = new Thread( new A());
Thread t2 = new Thread( new B());
Thread t3 = new Thread( new C());
t1.start();
t2.start();
t3.start();
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-49
Topic: Thread Life Cycle OR Thread States
Thread states/Thread life cycle is very basic question, before going deep
into concepts we must understand Thread life cycle.
start()
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
1. New State
When you create object of Thread with the new operator that means it
is in the born state, it does not start executing code inside the thread. It
remains in this state until we call the start () method.
2. Runnable State
The thread is in runnable state after invocation of start() method but the
thread scheduler has not selected it to be the running thread.
3. Running State
The thread is in running state, if the thread scheduler has selected it for
running.
5. Dead State:
A thread is considered dead when its run() method completes.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-50
Topic: Thread Constructors and Its Methods
Constructors
Thread()
Allocates a new Thread object.
Thread(Runnable target)
Allocates a new Thread object.
Thread(Runnable target, String name)
Allocates a new Thread object with specified
name.
Thread(String name)
Allocates a new Thread object with specified
name.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-51
Topic: Thread Synchronization
Key to synchronization is the concept of the monitor. Only one thread can own
a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor
will be suspended until the first thread exits the monitor. These other threads
are said to be waiting for the monitor.
class Table {
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Table t;
MyThread1(Table t) {
this.t=t;
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
There are two ways that you can synchronize your code.
1) Using synchronize Method:-
If you declare any method as synchronized, it is known as synchronized
method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the thread completes its task.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class SysnTest {
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Imagine that you want to synchronize access to objects of a class that was
not designed for multithreaded access. That is the class does not use
synchronized methods. Further, this class was not created by you, but by a
third party and you do not have access to the source code. Thus it is not
possible for you to add synchronized to the appropriate methods within the
class. In this situation, you simply put calls to the methods defined by this
class inside a synchronized block.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-52
Topic: Chapter-9 Files and Stream
Stream :
A flow of data is referred as Stream.
We can store the data permanently within the file, data stored in file
is often called as persistent data. To perform any input or output
operation we have to use the concept of stream.
To get input from any source we use input stream and to write or
send the data to any destination we use output stream.
Source Destination
InputStream OutputStream
Keyboard Monitor
File
File Program
Network
Network
Printer
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Streams
Binary Text
Input Output
Reader Writer
Stream Stream
Object
InputStream
DataInput BufferedInput
Stream Stream
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Object
OutputStream
ByteArray Object
FileOutputStream FilterOutputStream
OutputStream OutputStream
Buffered
DataOutputStream
OutputStream
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-53
Topic: FileInputStream and FileOutputStream
InputStream Class:
This abstract class is the superclass of all classes representing an input stream of
bytes.
Methods of InputStream
Return Type Method Name
int read() throws IOException
Reads the next byte of data from the input stream.
int read(byte[] b) throws IOException
Reads some number of bytes from the input stream and
stores them into the buffer array b.
int available() throws IOException
Returns an estimate of the number of bytes that can be
read
long skip(long n) throws IOException
Skips over and discards n bytes of data from this input
stream.
void close()throws IOException
Closes this input stream and releases any system
resources associated with the stream.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
OutputStream Class:
This abstract class is the superclass of all classes representing an output stream of
bytes.
Methods of OutputStream
Return Type Method Name
void write(byte b) throws IOException
Write the byte b to the output stream.
void write(byte[] b) throws IOException
Writes b.length bytes from the specified byte array to this
output stream.
void close()throws IOException
Closes this input stream and releases any system
resources associated with the stream.
A B C D
Program read() a b c d
FileInputStream Class :
Constructors :
1. FileInputStream (String filename) throws FileNotFoundException
Creates a FileInputStream by opening a connection on actual file. It throws
FileNotFound exception if the file does not exist.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
A B C D
Program write() a b c d
FileOutputStream Class :
Constructors :
1. FileOutputStream (String filename) throws IOException
Creates a FileOutputStream by opening a connection on actual file. If file
does not exists then it creates a new file.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Methods :
1. void write(byte b) throws IOException
Write a single byte to output stream.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-54
Topic: Programs on File Handling
try
{
//open a file with InputStream
FileInputStream fin = new FileInputStream(filename);
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
}
} // main
} // class
Output
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
class FileCopy
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter source file name ");
String sfile = in.nextLine();
try
{
FileInputStream fin = new FileInputStream(sfile);
System.out.println("Enter the destination file name ");
String dfile = in.nextLine();
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Output
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-55
Topic: BufferedInputStream and BufferedOutputStream
Hierarchy of BufferedInputStream
InputStream
FilterInputStream
BufferedInputStream
BufferedInputStream
The BufferedIntputStream class is a subclass of FilterlnputStream which reads
as many data as possible into its internal buffer (a protected byte array field
named buf) in a single read () call and then each read ()call reads data from
the buffer instead of the underlying stream.
When the buffer runs out of data, the buffered stream refills its buffer from
the underlying stream.
This class does not declare any new methods of its own, rather all the
methods are inherited from the InputStream class.
Buffered streams are always efficient and faster than non buffered stream.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
BufferedOutputStream
The BufferedOutputStream class is a subclass of FilterOutputStream that
stores written data in an internal buffer (a protected byte array field named
buf) until the buffer is full or the stream is explicitly flushed using the flush()
method.
Then it writes the data onto the underlying output stream all at once.
This class does not declare any new methods of its own, rather all the
methods are inherited from the OutputStream class.
Following program copies the contents of one file into another file using
BufferdInputStream and BufferedOutputStream. This program is much more
faster and efficient than any non buffered streams copying program.
import java.util.*;
import java.io.*;
class FastCopy{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
int b =fin.read();
while(b!=-1){
fout.write((byte)b);
b=fin.read();
}
fin.close();
fout.close();
long end_time = new Date().getTime();
System.out.println("File copied successfully in "+(end_time-
st_time)+" ms");
}
catch(FileNotFoundException e){
System.out.println("Can't copy! Source file does not exists");
}
catch(IOException e){
System.out.println(e);
}
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-56
Topic: DataInputStream and DataOutputStream
DataOuptutStream :
Following diagram shows how we create a DataOutputStream to write
primitive values into the file.
File: values.dat
Object of FileOutputStream
Constructor of DataOutputStream
DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying
output stream.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
DataInputStream :
Following diagram shows how we create a DataInputStream to read primitive
values from the file.
File: values.dat
Object of FileInputStream
Constructor of DataInputStream
DataInputStream(InputStream in)
Creates a new data input stream to read data from the specified underlying
input stream.
Methods of DataInputStream Class :
Following are the various methods to read any type of primitive value from
the input stream.
1. byte readByte ( )
2. short readShort ( )
3. int readInt ( )
4. long readLong ( )
5. float readFloat ( )
6. double readDouble ( )
7. char readChar ( )
8. boolean readBoolean ( )
9. String readUTF ( )
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Following program demonstrate how to write and read primitive values into the
file.
import java.io.*;
class ValuesIO
{
public static void main(String [] args)throws IOException
{
int x=12345;
double y=567.3455667;
char z='A';
dout.writeInt(x);
dout.writeDouble(y);
dout.writeChar(z);
dout.close();
int a = din.readInt();
double b = din.readDouble();
char c= din.readChar();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
din.close();
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-57
Topic: ObjectOutputStream and ObjectInputStream
Suppose we want to write Employee record to the file then using the
DataOutStream method then we have to write individual field value using
various method e.g. writeInt( ), writeUTF( ) etc. In this case, we may declare
records as object and use the object classes to write and read these objects
from the files. This process is known as object serialization.
ObjectOuptutStream :
Following diagram shows how we create a ObjectOutputStream to write
object into the file.
File: record.dat
Object of FileOutputStream
ObjectInputStream :
Following diagram shows how we create a ObjectInputStream to read
primitive object from the file.
File: record.dat
Object of FileInputStream
Then, retrieve the objects in the same order in which they were written,
using the readObject method.
Emp e1 = (Emp) in.readObject();
Emp e2 = (Emp) in.readObject();
When reading back objects, you must carefully keep track of the number of
objects that were saved, their order and their types. Each call to readObject
reads in another object of the type Object. You, therefore, will need to cast
it to its correct type.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
There is, however, one change you need to make to any class that you want
to save and restore in an object stream. The class must implement the
Serializable interface.
class Employee implements Serializable { . . . . . }
Following program demonstrate how to write and read object into the
file.
import java.io.*;
class ObjectIOTest
{
public static void main(String args[]) throws Exception
{
Emp e1 = new Emp(10,"XYZ",5000);
Emp e2 = new Emp(20,"ABC",6000);
Emp e3 = new Emp(30,"PQR",7000);
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-58
Topic: Text Streams
Character streams can be used to read and write 16 bit Unicode characters.
Like byte streams, there are two kinds of characters stream classes, namely,
reader stream classes and writer stream classes.
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Writer
BufferedReader class:
Java BufferedReader class is used to read the text from a character-
based input stream.
It can be used to read data line by line by readLine() method. It makes
the performance fast. It inherits Reader class.
try{
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
while(line!=null){
System.out.println(line);
line=fin.readLine();
}
fin.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-59
Topic: File Class
File Management
The File class is Java’s representation of a file or directory path name.
You have learned how to read and write data from a file using streams.
However, there is more to file management than reading and writing.
The File class encapsulate the functionality that you will need to work
with the file system or directory on the users machine.
The File class contains several methods for working with the path name,
deleting and renaming files, creating new directories, listing the
contents of a directory, and determining several common attributes of
files and directories.
For example, you use the File class to find out when a file was last
modified or to remove or rename the file.
The simplest constructor for a File object takes a (full) file name. If you
don’t supply a path name, then Java uses the current directory. For
example
File f = new File(“test.txt”);
gives you file object with this name in the current directory. A call to this
constructor does not create a file with this name if it doesn’t exist.
boolean canWrite( )
indicates whether the file is writable.
boolean delete( )
tries to delete the file, returns true if the file was deleted. false otherwise.
boolean exists( )
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
boolean isDirectory( )
returns true if the File represents a directory, false otherwise.
boolean isFile()
returns true if the File represents a file, false otherwise.
boolean isHidden( )
returns true if the File object represents a hidden file or directory.
long lastModified( )
returns the time the file was last modified or 0 if the file does not exist. Use the
Date(long) constructor to convert this value to a date.
long length( )
returns the length of the file in bytes, or 0 if the file does not exist.
String[] list( )
returns an array of strings that contain the names of the files and directories
contained by this File object, or null if this File was not representing a directory.
boolean mkdir( )
makes a subdirectory whose name is given by the File object. Returns true if the
directory was successfully created, false otherwise.
class Sample
{
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Following program obtains the list of files and subdirectory names from the
specified directory:
import java.io.*;
class Sample
{
public static void main(String [] args) throws IOException
{
File f = new File("c:\\Advanced Java ");
if(f.exists())
{
String [] names = f.list();
for(String t: names)
{
System.out.println(t);
}
}
else
System.out.println("Directory does not exists");
}
}
Output:
Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-60
Topic: Chapter-10 Applet
Applets are small programs that are primarily used in Internet computing.
They can be transported over the Internet from one computer to another and
run using the AppletViewer or any Web browser that supports Java.
An applet, like any application program, can do many things for us. It can
perform arithmetic operations, display graphics, play sounds, accept user
input, create animation etc.
Applet Basics:
Before Java, you used HTML to describe the layout of a web page. The basic idea
of how to use applets in a web page is simple, the HTML page must tell the
browser which applets to load and then where to put each applet on the web
page. As you might expect, the tag needed to use an applet must tell the browser
the following.
From where to get the class files.
How the applet sits on the web page. (size, location etc)
The browser then retrieves the class files from the Net ( or from the directory on
the user’s machine) and automatically runs the applet, using its Java Virtual
Machine.
All these restrictions and limitations are placed in the interest of security of
systems. These restrictions ensure that an applet cannot do any damage to the
local system.
Object
Component
Container
Window Panel
`
Frame Applet
As above mentioned, an applet is a Java class that runs in the web browser or
appletviewer.
Running the Applet:
To execute the applet, you need to carry out two steps.
Compile your source files into class files.
And then type Appletviewer <AppletCode.java> on command prompt and hit
enter key to start applet.
A Web page basically made up of text and HTML tags that can be interpreted
by a Web browser or an applet viewer.
Web pages are stored using a file extension .html such as MyApplet.html.
Such files are referred as HTML files. HTML files should be stored in the same
directory as the compiled code of the applets.
Applet tag:
The <APPLET> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. So test the above applet program,
we have to write the following
Hello.html file.
<HTML>
<APPLET CODE=”HelloWorldApplet.class” WIDTH=300 HEIGHT=300>
</APPLET>
</HTML>
Before viewing the applet in a browser, it is a good idea to test it in the
appletviewer program that is a part of the Java SDK. To use the applet viewer in
our example, enter
appletviewer Hello.html
at the command line.
The HelloWorldApplet implements just one method, the paint method. Most
applets need to handle the paint event.
This event occurs whenever a part of applet’s visible area is uncovered and
needs to be drawn again.
The paint method is passed a Graphics object which we have chosen to call g.
The Graphics class is defined in the java.awt.Graphics package which we have
imported.
Within the paint method we call Graphics class’s drawString( ) method to
draw the string “Hello World” at the coordinate (50,25). That’s 50 pixels across
and twenty five pixels down from the upper left hand corner of the applet.
Java Lecture-61
Topic: Methods of Graphics Class
The Graphics Class:
Java’s Graphics class includes methods for drawing many different types of
shapes, from simple lines to polygons to text in a variety of fonts.
To draw a shape on the screen, we may call one of the methods available in
the Graphics class.
All the drawing methods have arguments representing end points, corners, or
starting locations of a shape as values in the Frame or Applet coordinate
system.
To draw a shape, we only need to use the appropriate method with the
required arguments. Following is the list of Graphics class methods.
Method Description
clearRect(int x, int y, int width, int height) Clears the specified rectangle by
filling it with the background color
of the current drawing surface.
copyArea(int x,int y,int w, int height, int dx, Copies an area of the component
int dy) by a distance specified by dx and
dy.
drawArc(int x, int y, int width, int height, int Draws the outline of a circular or
startAngle, int arcAngle) elliptical arc covering the
specified rectangle.
drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current
color, between the points (x1, y1)
and (x2, y2) in this graphics
context's coordinate system.
drawOval(int x, int y, int width, int height) Draws the outline of an oval.
Java Lecture-62
Topic: Draw a Polygon in Java Applet
Polygon is a closed figure with finite set of line segments joining one vertex
to the other.
The polygon comprises of set of (x, y) coordinate pairs where each pair is the
vertex of the polygon.
The side of the polygon is the line drawn between two successive coordinate
pairs and a line segment is drawn from the first pair to the last pair.
Syntax:
drawPolygon(int[] xPoints, int[] yPoints, int numOfPoints);
import java.applet.Applet;
import java.awt.Graphics;
(100,50) (200,50)
1 2
(250,150) 6 3 (250,150)
5 4
(100,250) (200,250)
import java.applet.Applet;
import java.awt.Graphics;
Output
Output
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-63
Topic: Color and Font
Color:
We can also change the draw of fill color using setColor() method of Graphics
class.
Syntax:
void setColor (Color clr)
To set color we need to pass object of Color class which is declared in AWT
package. There are two methods to pass this object
(i) By calling color class constructor
Color (int red, int green, int blue)
Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
g.setColor(Color.YELLOW);
g.fillOval(50,180,100,100);
}
}
Font:
Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
We can also change the font of text using setFont() method of Graphics class.
Syntax:
void setFont (Font font)
To set font we need to pass the object of Font class which is declared in AWT
package. The constructor of Font class takes three arguments.
Font(String fontName, int style , int size)
import java.awt.*;
import java.applet.*;
g.setFont(new Font("Arial",Font.BOLD,30));
Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
g.setFont(new Font("Arial",Font.BOLD+Font.ITALIC,30));
g.drawString("Font Demo", 50,150);
}
}
Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-64
Topic: Applet Life Cycle
Applet lifecycle :
Every java applet inherits a set of default behavior from the applet class. As a
result when can applet is loaded it undergoes a series of changes in its state as
shown in the following figure-
Begin
(Load Applet) init ( )
Born
start ( )
paint ( ) stop ( )
Running Idle
start ( )
destroy ( )
End
Four method in applet class gives the framework on which we can build any
applet.
(i) init ( ) {initialization state}
This method is used for whatever initialization is needed for your applet. It is
automatically called by the browser when java creates the object for the first
time. The initialization occurs only once in the applet lifecycle.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
Java Lecture-65
Topic: Passing Information to Applet
As you seen, the CODE attributes gives the name of the class file and must
include the .class extension.
The WIDTH and HEIGHT attributes size the window that will hold the applet.
The text between the <APPLET> and </APPLET> tags is displayed only if the
browser cannot show applets.
These tags are required. If any are missing, the browser cannot load your
applet.
CODEBASE
This optional attribute tells the browser that your class files are found below
the directory indicated in the CODEBASE attribute.
WIDTH, HEIGHT
These attributes are required and give the width and height of the applet,
measured in pixels.
ALIGN
This attributes specified the alignment of the applet. Possible values are as follows
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
You then pick up the value of the parameter, using the getParameter ( ) method
of the Applet class, as in the following example
Example: Write an applet to accept username in the form of parameter and print
“Hello <username>” in the Applet.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
1) hello.html
<HTML>
<APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>
<param name="username" value="Atul">
</APPLET>
</HTML>
2) MyApplet.java
import java.applet.Applet;
import java.awt.*;
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260
String [] fontNames=GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames()
import java.awt.*;
public class ListOfFonts
{
Output: