Kishan Java Notes
Kishan Java Notes
Kishan Java Notes
This allows the Java code to call or be called by the libraries and the native
applications (i.e. the programs specific to the hardware and the OS of a system).
This component is a collection of native C, C++ libraries which are required by the
execution engine.
JVM vs. JRE vs. JDK
Java Virtual Machine (JVM):
JVM is a virtual machine which provides a runtime environment for executing the Java
bytecode
public int hashCode() Returns a hash code value for the object
Variable:
A variable provides identity to memory location
Using variables we can process the information easily
Variables can also be called as References & Identifiers
Understanding Identifier :
➢ A name in JAVA program is called identifier.
➢ It may be class name, method name, variable name.
Rules [8]:
✓ The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _(underscore) and $
✓ If we are using any other symbols we will get compile time error.
✓ We can’t start a JAVA Identifier with number.
✓ Java Identifiers are case sensitive (Actually JAVA itself is a case sensitive)
✓ We can take our own length for the name of an JAVA identifier.
✓ We can’t use JAVA language keywords (50) as identifiers.
✓No space is allowed between the characters of an identifier
✓ All predefined JAVA class names and interface names we can use as identifiers (X)
Which of the following are valid Java Identifiers?
➢ _$_
➢ Mou$e
➢ Java4All
➢ Student@NareshIt
➢ 999aaa
➢ Display#
➢ String
➢ Byte
➢ byte
➢ Integer
➢ pro1
Understanding Separators
Separator Description
{} Braces Define a block of code, for classes, methods and values of arrays
6. The data type of the return value must match the method's declared return
type.
Objects
Note: return statement need not to be last statement in a method, but it must
public : Anything declared as public can be accessed from anywhere, main method
should be available for other classes in the project. So main method “has” to be public
static : Static methods can be called directly with out creating a class object. So
when java execution starts, JVM will be able to start the main method.
void: A java program execution starts from main() method and ends with main()
method. So if main() method returns something there is no way of catching that
return statement. So always main() method return type is void.
main: This is the name of java main() method. It’s fixed and when we start a java
program, JVM checks for the main method.
String []args: Java main method accepts a “single” argument of type String array. This
is also called as java command line arguments.
Which of the following main() method syntax are valid?
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String [] args)
4. public static void main(String args [])
5. public static void main([]String args)
6. public static void main(String[] Kishan)
7. static public void main(String[] args)
8. public static int main(String[] args)
9. public final static void main(String[] args)
10. Public static void main(String[] args)
11. final public static void main(String[] args)
12. Final public static void main(String[] args)
13. public static void main(String… args)
14. public static void mian(String[] args)
15. public static void main(String[8] args)
16. public static void main(int[] args)
17. public static void main()
18. public void main(String[] args)
19. public static void Main(String[] args)
Java Data Types
Data type specifies the size and type of values that can be
stored in an identifier
They are use full to represent how much memory is
required to hold the data.
Represents what type of data to be allowed.
Java data types are classified in to 2 types
--->Primitive Data types
---> User Defined Data types (Reference)
(String, Array, class, abstract class, interface…etc)
byte:
Size: 1byte (8bits)
➢
➢ Max-value: +127
➢ Min-value:-128
➢ Range:-128to 127[-27 to 27-1]
short:
➢ Size: 2 bytes
➢ Range: -32768 to 32767(-215 to 215-1)
int:
➢ Size: 4 bytes
➢ Range:-2147483648 to 2147483647 (-231 to 231-1)
long:
➢ Size: 8 bytes
➢ Range:-263 to 263-1
float:
➢ If we want 5 to 6 decimal places of accuracy then we
should go for float.
➢ Size:4 bytes.
double:
➢ If we want to 14 to 15 decimal places of accuracy then we
should go for double
➢ Size:8 bytes
char:
➢ Size:2 bytes
➢ Range: 0 to 65535
Note:
➢Arithmetic operations return result in integer format
(int/long).
Understanding Java Keywords
There are 50 Java language keywords.
We cannot use any of the following as identifiers in your
programs.
1) Keywords for data types: (8)
2) Keywords for flow control:(11)
3) Keywords for modifiers:(11)
4) Keywords for exception handling:(6)
5) Class related keywords:(6)
6) Object related keywords:(4)
7) Void keyword(1)
8) Enum (1)
9) Reserved keywords (2)
,case
When the compiler sees //, it ignores all text after // in the
same line.
When it sees /*, it scans for the next */ and ignores any text
between /* and */.
Variables:
Variables are nothing but reserved memory locations to
store values.
Variables are divided in to three types
1. Instance variables
2. Static variables
3. Local variables
Instance Variable:
The variables which are declared within the class but
outside of any method or block or constructor are called
“Instance Variables”
Instance variables can’t be accessed from static area
Static Variable:
A variable which is declared static is known as static variable.
The access modifier for the default constructor provided by the compiler will
be SAME as the access modifier as class. (If the class is public then
constructor is also public OR If the class is default then constructor is also
default).
The default constructor given by the compiler will have only ‘2’ access
modifiers ie., public & default.
➢Arithmetic Operators
➢Relational Operators
➢Logical Operators
Increment & Decrement operators (2)
➢ ++ is used as Increment operator (increases value by 1)
➢ -- is used as Decrement operator (decreases by 1)
➢ Both Increment & Decrement operators are classified in to
2 types.
Arithmetic Operators (5)
These are used to perform common mathematical
operations.
Operator Name Description Example
== Equal to x == y
!= Not equal x != y
The static variable can be used to refer the common property of all objects.(eg:
company name of employees).
In java applications it is possible to access the static variables either by using the
respective class object reference (or) by using respective class name directly.
Static variables never be ‘local variables’.
Static block and static variable will have equal priorities, so these execute in
defined order.
If a static variable and a local variable is having same name, Then compiler will
first search for local variable and then static variable.
For the static variables it is not required to perform
initialization explicitly jvm will always provide default
values.
If we declare a static variable as final then 100% we
should perform initialization explicitly whether we are
using or not otherwise we will get compile time error.
For final static variables JVM won't provide any default
values, JVM will provide default values only for static
variables.
Final static variables can be initialized inside a static
block. (any where else we will be getting compile time
error)
Static Method
If you apply static keyword with any method, it is known as static method
A static method can be invoked without the need for creating an instance of
a class.
static method can access static data member and can change the value of it.
In java applications it is possible to access the static methods either by
using the respective class object reference (or) by using respective class
name directly.
Restrictions for static method:
➢ The static method can not use non static data member or call non-static
method directly.
Static Method Vs Instance Method
Static Method Instance Method
A method i.e. declared as static is known as A method i.e. not declared as static is
static method. known as instance method
Object is not required to call static method. Object is required to call instance methods.
Non-static (instance) members cannot be static and non-static variables both can be
accessed in static context (static method, accessed in instance methods.
static block and static nested class) directly.
Static Block:
Is used to initialize the static data member.
We can not invoke a static block, rather JVM invokes the static block at the time of
class loading.
It is executed before main method at the time of class loading.
We can define more than one static block in the java program.
public class Demo
{
static
{
System.out.println("hi Static block is Invoked");
System.exit(0);
}
public static void main(String[] args)
{
System.out.println("hi from main method");
}
}
Understanding Type Casting
➢Converting one data type into another data type is
called casting.
➢In general there are two types of casting procedures.
Note: We can assign a number variable to character datatype but it should be in the
range between 0 to 65535 (Uni code character set range)
Understanding Wrapper Classes
In java technology if we want to represent a group of
objects in the form of an object then we have to use
“Collection objects”, like
➢ Array List
➢ Vector
➢ Stack
In java applications collections objects are able to allow
only group of other objects, not primitive data directly.
If we want to store primitive data in collection objects,
first we need to convert the primitive data in object
form then we have to store, that object data in collection
objects.
Java Technology has provided the following ‘8’ number of
Wrapper classes w.r.t to ‘8’ number of primitive data
types.
Points to remember…
All most all wrapper classes define 2 constructors one can
take corresponding primitive as argument and the other
can take String as argument.
(except Character)
Character class defines only one constructor which can
take char primitive as argument there is no String
argument constructor.
If we are passing String as an argument in Boolean
wrapper class then :
---> If the argument is true then the result also will be true
irrespective of the data and case sensitiveness
---> If the argument is false then the result also will be false
irrespective of the data and case sensitiveness
---> Other than true/false any other data will give you the
result as false.
Understanding Control Statements
Control flow statements, change or break the flow of
execution by implementing decision making, looping, and
branching your program to execute particular blocks of code
based on the conditions.
In condition statement we can take any java expression which returns 'boolean' as
result.
If we are not taking any expression compiler will give 'true' as default value.
If we our condition is always true then the code written out side the loop will be "Un-
reachable code" (Compile time error).
If we our condition is always false then the code written in side the loop will be "Un-
reachable code" (Compile time error).
Understanding for-each loop
For each Introduced in 1.5version, It acts as an alternative to
for loop, while loop etc for retrieving the elements in the array.
By using for-each loop we can easily retrieve the elements
easily from the arrays.
It cannot traverse the elements in reverse order because it does
not work on index values
For-each also acts as alternative for iterator when retrieving
elements from collections.
Syntax:
Step 1 :-Declare a variable that is the same type as the base type of
the array
Step 2 :-Write the Colon (:)
Step 3 :-Then write the array name
Step 4 :-In the loop body we have to use the variable which we
have created
Jump Statements
blocks"., other than this if you are using any where you will be
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
We can access the members of one class from another class of same package.
packages.
Some Important Packages
Package Description
java.lang Lang stands for ‘language’ ,this got primary classes and interfaces essential for
developing a basic java program
java.util Util stands for ‘utility’, This package contains useful classes and interfaces like
Stack, LinkedList, Hashtable, etc … These classes are called collections.
java.io Io stands for ‘input and output’. This package contains streams.
java.awt awt stands for ‘abstract window toolkit’. This package helps to develop GUI.
javax.swing This package helps to develop GUI like java.awt. The ‘x’ in javax represents that
it is an extended package.
java.net net stands for ‘network’. Client-Server programming can be done by using this
package.
java.applet Applets are programs which came from a server into a client and get executed
on the client machine on a network.
java.text This package has two important classes, DateFormat and NumberFormat.
java.sql Sql stands for ‘structured query language’. This package helps to connect to
databases.
Structure of a package
Simple example of package
The package keyword is used to create a package.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside
the package.
✓import packageName.*;
✓import packageName.classname;
Output:Hello
Using packagename.classname
If you import packagename.classname then only declared class
of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
If you use fully qualified name then only declared class of this
package will be accessible.
Now there is no need to import.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Understanding Access Modifiers
Access modifiers determine whether other classes can use
a particular field or invoke a particular method.
There are '2' levels of access modifiers.
1. At Class level: public & default
2. At member level: public, private, protected and default
At Class level:
➢ If a class is declared as public then that is visible to all the
classes everywhere.
➢ If a class is declared as default (package-private)then that is
visible to only within its own package.
At Member level:
At the member level, we can also use the public or default
(package-private) just as with class level, and with the same
meaning.
PUBLIC:
If a method, variable or constructor is declared as public then
we can access them from anywhere.
When we are accessing the public member its class also should
be public otherwise will be getting compile time error.
DEFAULT:
If a method, variable or constructor is declared as default then
we can access them from current package only. So it is also
called "PACKAGE -PRIVATE“
PRIVATE:
If a method, variable or constructor is declared as private then
we can access them in the current class only.
Private is the most restricted access modifier.
If a constructor is declared as private we can’t create a object
for that class in other classes.
PROTECTED:
If a method, variable or constructor is declared as
protected then we can access them with in the current
package.
We can use PROTECTED members outside the package
only in child class, and we can access them by using child
class reference only not from parent class reference.
Understanding ‘this’ Keyword
There will be situations where a method wants to refer
to the object which invoked it.
To perform this we use ‘this’ keyword.
'this' is used to refer current class instance variable (which
resolves ambiguity problem).
'this' is used to invoke current class method.
'this' is used to invoke current class parameterized
constructor from a default constructor() and vice versa.
'this' is used to return the current class instance from the
method.
Understanding Arrays
An array is an indexed collection of fixed number of
homogeneous data elements.
An array stores multiple data items of the same data type,
in a continuous block of memory, divided into a number
of slots.
The main advantage of arrays is we can represent multiple
values with the same name so that readability of the code
will be improved.
The main disadvantage of arrays is its fixed length.
It means once we created an array there is no chance of
increasing or decreasing the size based on our requirement
that is to use arrays compulsory, we should know the size
in advance which may not possible always.
We can resolve this problem by using collections.
How to declare an Array?
To declare an array, write the data type, followed by a set
of square brackets[], followed by the identifier name.
int []rollNumber; //valid
int rollNumber[];//valid
At the time of declaration we can't specify the size of an
array.
int []rollNumber;
int [5]rollNumber; //error
How to Instantiate an array?
To instantiate (or create) an array, write the new keyword and
the datatype of the array, followed by the square brackets
containing the number of elements you want the array to have.
Every array in java is an object hence we can create by using
new keyword.
int []rollNumber;
rollNumber=new int[5]; //valid 1st way
(or)
int []rollNumber=new int[5];// valid 2nd way
(or)
int []rollNumber=new int[]{10,20,30,40,50};// valid 3rd way
(or)
int []rollNumber={10,20,30,40,50}; //valid 4th way
• The length of an array starts with ‘1’
• The index position of an array starts with ‘0’
Rules for Array Instantiation:
1. At the time of array initializing an array compulsory we
should specify the size otherwise we will get compile
time error.
2. We can give array size as zero also.
3. We can’t have negative values as array size.
4. The allowed data types to specify array size are byte,
short, char, int.
5. The maximum allowed array size in java is maximum
value of int size.
6. Whenever we are creating an array every element is
initialized with default value automatically
Note: Anonymous array is an array without reference.
Eg: new int[]{10,20,30}.length;
How to access an array element?
To access an array element, or a part of the array, you use
a number called an index or a subscript.
Difference between length Vs length():
length length()
It is the final variable applicable only for It is a final method applicable for String
arrays. objects.
String substring(int begin) Return the substring from begin index to end of
the string
String substring(int begin, int end) Returns the substring from begin index to end-1
index.
String replace(char old, char new) To replace every old character with a new
character.
String Buffer:
• If a user wants to change the content frequently then it is
recommended to go for StringBuffer.
• StringBuffer objects are mutable, so they can be modified.
• We can create a StringBuffer object by using new operator and
pass the string to the object, as:
StringBuffer sb = new StringBuffer (“Sujatha");
• The default initial capacity of a StringBuffer is"16".
• After reaching its maximum limit it will be increased to
(currentcapacity+1)*2. ie; (16+1)*2.
StringBuffer Methods
Method Description
➢ Use String if you require immutability use Stringbuffer in java if you need
without thread-safety.
How to create an immutable class?
Class must be public and final.
Properties must be private and final.
Initialization of these variables must be done using a
parameterized Constructor.
Public setter methods are allowed.
Public getters are allowed to access the information of
Immutable object.
Introduction to OOPs
Languages like Pascal, C, FORTRAN, and COBOL are called
procedure-oriented programming languages. Since in these
languages, a programmer uses procedures or functions to
perform a task. When the programmer wants to write a
program, he will first divide the task into separate sub tasks,
each of which is expressed as functions/ procedures. This
approach is called procedure-oriented approach.
The languages like C++ and Java use classes and object in their
programs and are called Object Oriented Programming
languages. The main task is divided into several modules and
these are represented as classes. Each class can perform some
tasks for which several methods are written in a class. This
approach is called “Object Oriented approach”.
OOP Vs POP
OOP POP
Programs Divided into small chunks called Divided into small parts based on
objects which are instances of the functions.
classes.
Accessing Four accessing modes are used No such accessing mode is required
Mode in OOP to access attributes or
methods – ‘Private’, ‘Public’,
‘default’ , and ‘Protected’
Execution Various methods can work Follows a systematic step-by-step
simultaneously approach to execute functions.
Security It is of high secure because of it There is no such way of data hiding
data hiding feature in POP, thus making it less secure.
Features of OOP
There are mainly ‘4’ features of OOP’s are there, which
are listed below.
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
Encapsulation: Wrapping up of data (variables) and methods
into single unit is called Encapsulation. Class is an example for
encapsulation. Encapsulation can be described as a protective
barrier that prevents the code and data being randomly
accessed by other code defined outside the class. Encapsulation
is the technique of making the fields in a class private and
providing access to the fields via methods. If a field is declared
private, it cannot be accessed by anyone outside the class.
Abstraction: Providing the essential features without its inner
details is called abstraction (or) hiding internal implementation
is called Abstraction. Abstraction provides security
Encapsulation Vs Abstraction
Encapsulation Abstraction
Encapsulation is a technique which is used Abstraction shows only the necessary details
for hide the code and data. to the user.
Encapsulation = Datahiding + Abstraction
For simplicity Encapsulation means hiding For simplicity Abstraction means hiding
data using getters and setters etc implementation using abstract
class/interfaces
What is a POJO class?
POJO stands for Plain Old Java Object.
It is an ordinary Java class/object, not bound by any
special restriction.
POJOs are used for increasing the readability and re-
usability of a program.
Rules:
A pojo should not
First Form:
Encapsulation is a technique that packages related data and
behaviors into a single unit.
Here, the common characteristics and behaviors of a student
are packaged into a single unit: the Studentclass.
This is the process of encapsulation.
It is Keyword It is a Keyword
Used to access current class object Used to access the parent object
functionality functionality from child class
We can use these to invoke super class & We can use refers parent class and current
current constructors directly class instance members.
We should use only inside constructors as We can use anywhere (i.e., instance area)
first line, if we are using outside of except static area , other wise we will get
constructor we will get compile time error compile time error .
Understanding Method Signature
A method signature represents method name, method
return type and its parameter.
The method present in super class is called overridden method and the
method present in the sub class is called over ridding method.
➢ After jdk 1.5 return types may not be same in co-variant return
types. (Co-variant return type concept is applicable only for
object types but not for primitives)
➢ The access level must not be more restrictive that that of the over
ridden method. (private < default < protected < public)
In Overloading Return type need not be In Overriding Return type must be same
the same
Parameters must be different when we do Parameters must be same
Overloading
In Overloading one method can’t hide In Overriding sub class method hides the
another method super class methods
Understanding Java Abstraction
Abstraction:
“Abstraction is a process of hiding the
implementation details and showing only
functionality to the user”.
Another way, it shows only important things to the user
and hides the internal details for example sending a
WhatsApp message, we just type the text and send the
message. We don't know the internal processing about the
message delivery. Abstraction lets you focus on what the
object does instead of how it does it.
Ways to achieve ‘Abstraction’:
In general there are two ways to achieve Abstraction:
class interface
We can instantiate a class, i.e. we can create an We can’t instantiate an interface.
object reference for a class
A class is declared using a keyword ‘class’ An interface is declared by using a keyword
class <class name> { } ‘interface’.
interface <interface name>{ }
The members of a class can have the access The members of an interface are
modifiers like public, private, protected. always public. Up to (1.7v)
Inside a class you can have method In interfaces we can’t write method body,
implementation. because all the methods are by default
public abstract methods. Up to (1.7v)
Multiple inheritance is not possible Multiple inheritance is possible
However, these sleep times are not guaranteed to be precise, because they are
limited by the facilities provided by the underlying OS.
Understanding interrupt() method
An interrupt is an indication to a thread that it should stop what
it is doing and do something else.
For the interrupt mechanism to work correctly, the interrupted
thread must be in either sleep state or wait state.
If the selected Thread is not in sleep mode then interrupt() will
wait until it went in to sleep mode, and then it will cause
interruption for that thread.
Example:
ClassA a=new ClassA();
Thread t=new Thread(a);
t.start();
t. interrupt();
Understanding yield() method
yield() provides a mechanism to inform the “thread
scheduler” that the current thread is willing to hand over
its current use of processor, but it'd like to be scheduled
back soon as possible.
If we are using the yield method then the selected thread
will give a chance for other threads with same priority to
execute.
If there are several waiting Threads with same priority,
then we can't expect exactly which Thread will get chance
for its execution.
We can’t guess again when the yielded thread will resume
its execution.
Getting and setting name of a Thread:
Every Thread in java has some name it may be provided
explicitly by the programmer or automatically generated
by JVM.
priority.
method.
where.
In this constructor, simply call the super constructor and pass the
String parameter.
Understanding ‘Final’ keyword
The final keyword in java is used to restrict the user.
‘final’ keyword is used in three ways:
It is used to declare constants as:
✓ Final double Pi=3.14159; //PI is constant
It is used to prevent inheritance as:
✓ Final class A // sub class to A cant be created
It is used to stop method Overriding as:
✓ Final sum() // sum() method can’t be overridden
‘final’ Method:
If you make any method as final, you cannot override it.
Because they are not available to sub classes. So only
overloading is possible.
‘final’ Class:
If you make any class as final, you cannot extend it. It
means sub classes can’t be created to final class
Understanding Singleton class
A singleton class is a class that can have only one object (an instance of
1)Write a class & then Create a static object for the class.
3)Create a static method which returns the static instance which you have
Runtime r=Runtime.getRuntime();
r.gc();
IO Streams
In java a stream represents a sequence of objects (byte,
characters, etc.) which we can access them in a sequential
order.
In java, I/O streams represents either an Input source or an
output destination.
There are mainly '4' types of streams
Name Description
java.io.InputStream java.io.OutputStream
FileInputStream Class:
FileInputStream Class is a normal class which extends
InputStream class which is a abstract class.
This class is always used to open the file in read mode.
(int read() is an abstract method in InputStream class, in
FileInputStreamClass it has been overridden).
Syntax:
FileInputStream fis=new FileInputStream("abc.txt");
In the above syntax if the file is not available at the given
URL the FileInputStream object will throw a
FileNotFoundException
The read() method on success will returns the ASCII value
of the character(ie., int datatype), If failed returns '-1'
FileOutputStream Class
FileOutputStream class is a normal class which extends
OutputStream class which is a abstract class.
This class is always used to open the file in write mode.
Syntax:
FileOutputStream(String filePath)
FileOutputStream(File fileObject)
FileOutputStream(String filePath,boolean append)
If we are trying to write some data in to the file by using write()
method, then compiler will check if there is any file present in that
given URL.
If the file is present then the file will be opened and the existing
content will be deleted in the file.
If the file is not present then a new file will be created with the name
given in the path.
While using FileOutputStream if we don’t want to override the
existing data in the file the we should use append mode.(set it as
true).
1) WAP to copy the contents of source file in to the destination file.
2) WAP to write the file using FileOutputStream and use append
mode.
3) WAP to copy source Image in to destination Image.
Understanding Character Streams:
In character Streams data is transferred in the form of
characters.
In character Streams the length of each data packet is 2
bytes.
All character stream classes are sub classes for Reader &
Writer classes which are abstract classes. (present in
'java.io.Reader' & 'java.io.Writer' )
FileReader Class:
It is the child class for InputStreamReader.
We can use this class to read the data character by character from the stream.
Data like images, audio, video etc we can't read by using FileReader class.
(We are supossed to use Byte Streams)
FileReader fr=new FileReader ("abc.txt");
FileWriter Class:
It is the child class for OutputStreamWriter.
We can use this class to write the data character by character in the from of
stream in to destination file.
Same as FileOutput Stream class in FileWriter Class also We can use append
mode.(By setting the second parameter as ‘true’).
FileWriter fw=new FileWriter ("abc.txt");
Byte Streams Vs Character Streams
Understanding Data Streams:
These Streams handle binary I/O operations on primitive data types.
BufferedOutputStream:
BufferedOutputStream br=new BufferedOutputStream(new FileOutputStream(“FilePath"));
flush() : When you write data to a stream, it is not
written immediately, and it is buffered. So use flush()
when you need to be sure that all your data from buffer is
written.
BufferedReader:
BufferedReader br=new BufferedReader(new FileReader(" FilePath "));
BufferedWriter :
BufferedWriter bw= new BufferedWriter(new FileWriter(" FilePath "));
Understanding Serialization
The process of saving (or) writing state of an object to a file is called
serialization.
In other words it is a process of converting an object from java
supported version to network supported version (or) file supported
version.
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(“File Path"));
By using FileOutputStream and ObjectOutputStream classes we can
achieve serialization.
The process of reading state of an object from a file is called
DeSerialization.
By using FileInputStream and ObjectInputStream classes we can
achieve DeSerialization.
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(“File Path"));
Important Points to remember
We can perform Serialization only for Serializable objects.
An object is said to be Serializable if and only if the
corresponding class implements Serializable interface.
Serializable interface present in java.io package and does not
contain any methods. It is marker interface. The required
ability will be provided automatically by JVM.
We can add any no. Of objects to the file and we can read all
those objects from the file, but in which order we wrote objects
in the same order only the objects will come back ie, reterving
order is important.
If we are trying to serialize a non-serializable object then we
will get RuntimeException saying "NotSerializableException".
Transient keyword
‘transient’ is the modifier applicable only for variables.
Syntax
Arrays can hold only homogeneous data Collections can hold both homogeneous
types elements. and heterogeneous elements.
Arrays can hold both object and primitive Collection can hold only object types
List: Lists are like sets but allow duplicate values to be stored.
All the above mentioned methods are the most common general methods
which can be applicable for any Collection object
Understanding List Interface
The Java.util.List is a child interface of Collection.
A List is an ordered Collection of elements in which insertion ordered
is preserved.
Lists allows duplicate elements.
ArrayList :
ArrayList is available since jdk1.2V
It allows duplicates & insertion order is maintained.
Default capacity when creating an ArrayList is 10.
If the ArrayList is full then its capacity will be increased automatically.
New capacity=(current capacity*3/2)+1
It is not synchronized by default.
ArrayList al=new ArrayList();
List al=collections.synchronizedList(al);
It is synchronized by default.
Linked List
Node Structure
LinkedList Methods
Description
Methods
Object getFirst(); Returns the first element in this list
Object removeFirst(); Removes and returns the first element from this list
Object removeLast(); Removes and returns the last element from this list.
void addFirst(Element e); Inserts the specified element at the beginning of this
list.
addLast(Element e); Appends the specified element to the end of this list.
Understanding Set Interface
It is the child interface of Collection.
A Set is a Collection that cannot contain duplicate elements
The Set interface contains only methods inherited
from Collection and adds the restriction that duplicate elements are
prohibited.
HashSet:
HashSet is available since jdk1.2V
Underlying data structure for HashSet is HashTable.
It doesn’t allows duplicates & insertion order is not maintained.
Default capacity when creating an HashSet is 16.
Load Factor for HashSet is 0.75 (No of elements/ Size of the hashTable)
Keys are unique in Map interface, duplicate keys are not allowed but
duplicate values are allowed.
Each key can map to at most one value.
boolean containsKey Returns true if this map contains a mapping for the
(Object key); specified key.
boolean containsValue Returns true if this map maps one or more keys to the
(Object value); specified value
V get(Object key) Returns the value to which the specified key is mapped
V put(K key, V value) Associates the specified value with the specified key in
this map
V remove(Object key) Removes the mapping for a key from this map if it is
present
Set<K> keySet() Returns a Set view of the keys contained in this map
HashMap:
HashMap is available since jdk1.2V.
It allows duplicate values with unique keys & insertion order is not
maintained. (Duplicate keys are replaced)
Default capacity is 16 & load factor is 0.75.
Not Maintained
Insertion order Not Maintained (But keys are Not
Maintained sorted in Maintained
ascending order)
Null
Keys/Values Allowed Allowed Not Allowed Not Allowed
(Null Values are
allowed)
Set will not allow duplicate values to be List will allow duplicate values.
stored.
Accessing elements by their index Accessing elements by index is possible
(position number) is not possible in case in lists.
of sets.
ArrayList (Vs) Vector
ArrayList Vector
ArrayList increases its size every time Vector increases its size every time by
by 50 percent (half). doubling it.
HashMap (Vs) HashTable
HashMap HashTable
HashMap object is not synchronized by Hashtable object is synchronized by
default. default.
In case of a single thread, using HashMap In case of multiple threads, using
is faster than the Hashtable. Hashtable is advisable, with a single
thread, Hashtable becomes slow.
HashMap allows null keys and null values Hashtable does not allow null keys or
to be stored. values.
Understanding Applets & AWT
Applets allows java programmer to implement GUI in the
programming.
An applet is a Java program that runs in the context of a web page.
Like an image or hyperlink it "owns" some rectangular area of the
user's screen.
The java.applet.Applet class defines the core functionality of an
applet.
Every user defined applet class must extends pre-defined Applet
class.
Syntax:-
public class FirstApplet extends Applet
{
//statements
}
Abstract Window Tool Kit (AWT):
AWT contains large number of pre defined (abstract)classes,
methods & Interfaces that allows you to create and manage
graphical user interface ( GUI ) applications.
The java.awt package provides classes for AWT api such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.
First Applet Program:
Applets are defined to be embedded in to HTML
pages.(Most of the browsers now stopped support for
applets).
Applet do not use main() because when applet is loaded it
automatically calls certain methods of applet class to start
and executes the applet code.
Applets and Servlets do not start their own process.
Instead they run inside a container.
Therefore, they do not need a static main method (which
starts the process).
public void paint() method is the pre-defined method in
Applet class.
Graphics class is the predefined class in java.awt
Applet Life Cycle:
GUI based java application can be invoked either by
"appletviewer" or "browser interpreter".
When an applet execution starts, it will be instantiated
implicitly.
We can check the instantiation by using a default constructor in
the Applet class.
Methods participate in Applet Life Cycle:
❖ Constructor()
❖ init()
❖ start()
❖ paint()
❖ stop()
❖ destroy()
Diagrammatic Representation
Components:
The objects or elements which are displayed on the applet
window are called "Components" (Ex: Button, Checkbox,
Radio button etc).
All the Component classes are available in java.awt
package only.
Event Listeners:
An Event is a action which is performed by a component.
When an action is performed Component fires an event.
Listener can collect event information and react according to
the defined logic.
Listener is a predefined interface having different sub
interfaces like, ActionListener, TextListener, MouseListener
etc.
Swings API
Swings acts as an updated API for developing standalone
GUI applications.
The classes which are available in applet package are
platform dependent.
Applet components are generally of heavy weight.
Swing components are platform independent, because the
entire logic for the components are written in java
language only.
Swing components are of light weight components.
If you want to create standalone GUI application by using
Swings API then your class should extends “JFrame”
Applets Vs Swings
Applets Swings
Applet components are of heavy weight Swing Components are light weight
client.
Java socket forms the base for data transfer between two
The socket specifies the site address and the connection port.