Core Java Notes
Core Java Notes
Unit- I
Features of Java
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Portable
7. Dynamic
8. Compiled and Interpreted
9. Multithreaded
10. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access
right to objects.
Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is
the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development
tools.
1) Class loader:
Class loader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of
a Java virtual machine (JVM) to the instruction set of a specific CPU.
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
We will have detailed learning of these variables in next chapters.
Example to understand the types of variables
1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift operator,
bitwise operator, ternary operator and assignment operator.
Operators Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
assignment = += -= *= /= %=
Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Understanding first java program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to
all.
static is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
Internal Details of Hello Java Program
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
What happens at runtime?
At runtime, following steps are performed:
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
UNIT-II
Object and Class in Java
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Syntax to declare a class:
class <class_name>{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
}
}
Output:30
40
}
}
Output:21.0
40
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Output:
Bike is created
If there is no constructor in a class, compiler automatically creates a default constructor.
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
}
}
Output:1
1
1
Counter2(){
count++;
System.out.println(count);
}
}
}
Output:1
2
3
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: running...
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
Understanding the simple example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Example abstract method
abstract void printStatus();//no body and abstract
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Difference between method overloading and method overriding in java
No. Method Overloading Method Overriding
Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple);//true
}
}
Output: true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.
Another example of java instanceof operator
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why
we are using this keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
//example of this keyword
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Program where this keyword is not required
class Student12{
int id;
String name;
Student12(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}
Output:111 Karan
222 Aryan
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains
the chain between the constructors i.e. it is used for constructor chaining. Let's see the example
given below that displays the actual use of this keyword.
class Student14{
int id;
String name;
String city;
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java
obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59
Variable Argument (Varargs):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will have
to pass in the method, varargs is the better approach.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
return_type method_name(data_type... variableName){}
class VarargsExample1{
display();//zero argument
display("my","name","is","varargs");//four arguments
}
}
class VarargsExample2{
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}
class VarargsExample3{
display(500,"hello");//one argument
display(1000,"my","name","is","varargs");//four arguments
}
}
Output:number is 500
hello
number is 1000
my
name
is
varargs
UNIT-III
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
Output:Hello
interface Printable{
void print();
}
interface Showable{
void show();
}
Output:Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest o
f themethods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
Output:
I am a
I am b
I am c
I am d
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
3) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Private Y N N N
Protected Y Y Y N
Public Y Y Y Y
Java String
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
2) By new keyword
1. String s=new String("Welcome");
ava String Example
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4.
5. char ch[]={'s','t','r','i','n','g','s'};
6. String s2=new String(ch);//converting char array to string
7.
8. String s3=new String("example");//creating java string by new keyword
9.
10. System.out.println(s1);
11. System.out.println(s2);
12. System.out.println(s3);
13. }}
Test it Now
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
1 char charAt(int index) returns char value for the particular index
String substring(int beginIndex, int returns substring for given begin index and end
4
endIndex) index
7 String replace(char old, char new) replaces all occurrences of specified char value
Output:true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Test it Now
Output:false
true
Output:true
false
Output:0
1
-1
Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
Important methods of StringBuffer class
1. public synchronized StringBuffer append(String s): is used to append the specified
string with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public char charAt(int index): is used to return the character at the specified position.
5. public int length(): is used to return the length of the string i.e. total number of
characters.
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Vectors: Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Below given are the list of constructors provided by the vector class.
Vector( )
1
This constructor creates a default vector, which has an initial size of 10
Vector(int size)
2 This constructor accepts an argument that equals to the required size, and creates a
vector whose initial capacity is specified by size:
Vector defines the following methods:
void removeAllElements()
8
Removes all components from this vector and sets its size to zero.
int size()
10
Returns the number of components in this vector.
/*Write a program that accepts a shopping list of items from the command line and stores them
in
a vector. Also provide facility to perform following operations
a) To delete an item in the list.
b) To add an item at a specified location in the list.
c) To add an item at the end of the list.
d) To print the contents of the vector.
*/
import java.util.*;
import java.io.*;
class MenuDriven
{
public static void main(String args[])
{
Vector itemList = new Vector();
String str,item;
int i,j,len,choice,pos;
len=args.length;
for(i=0;i<len;i++)
itemList.addElement(args[i]);
while(true)
{
System.out.println("\n\nChoose your choice ...");
System.out.println("1) Delete Item");
System.out.println("2) Add Item at Specified Location ");
System.out.println("3) Add Item at the End of the list");
System.out.println("4) Print Vector List ");
System.out.print("Enter your choice : ");
item=sc.nextLine();
System.out.print("Enter
Position to insert item : ");
pos=sc.nextInt();
itemList.insertElementAt(item,pos-1);
break;
case 3 : System.out.print("Enter Item to be Insert : ");
item=sc.nextLine();
itemList.addElement(item);
break;
case 4 : len=itemList.size();
System.out.println("\nItem Display ");
for(i=0;i<len;i++)
{
System.out.println((i+1)+") "+itemList.elementAt(i));
}
break;
}
}
}
Output:
Choose your choice ...
1) Delete Item
2) Add Item at Specified Location
3) Add Item at the End of the list
4) Print Vector List
5) Exit
Enter your choice : 2
Enter Item to be Insert : soap
Enter Position to insert item : 1
Item Display
1) soap
2) sugar
3) oil
4) jaggery
5) tea
6) coffee
Java - Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
java.lang - bundles the fundamental classes
java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Package are categorized into two forms
Built-in Package:-Existing Java package for example java.lang, java.util etc.
User-defined-package:- Java package created by user to categorized classes and interface
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
package mypack;
public class employee
{
...statement;
}
class test
{
public static void main(String[] args)
{
Book bk = new Book("java","Herbert");
bk.show();
}
}
To run this program :
create a directory under your current working development directory(i.e. JDK directory),
name it as mypack.
compile the source file
Put the class file into the directory you have created.
Execute the program from development directory.
mport keyword
import keyword is used to import built-in and user-defined packages into your java source file.
So that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
1. Using fully qualified name (But this is not a good practice.)
Example :
class MyDate extends java.util.Date
{
//statement;
}
2. import the only class you want to use.
Example :
import java.util.Date;
class MyDate extends Date
{
//statement.
}
3. import all the classes from the particular package
Example :
import java.util.*;
class MyDate extends Date
{
//statement;
}
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by 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
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Section-II
UNIT-IV
Multithreaded Programming
As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
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
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
System.out.println("thread is running...");
t1.start();
Output:thread is running...
System.out.println("thread is running...");
}
public static void main(String args[]){
t1.start();
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
t1.start();
t2.start();
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Synchronization is built around an internal entity known as the lock or monitor. Every object has
an lock associated with it. By convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and then release the lock when it's
done with them.
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
Class Table{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
Table t;
MyThread1(Table t){
this.t=t;
t.printTable(5);
Table t;
MyThread2(Table t){
this.t=t;
t.printTable(100);
}
class TestSynchronization1{
t1.start();
t2.start();
Output: 5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
class Table{
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
Table t;
MyThread1(Table t){
this.t=t;
t.printTable(5);
Table t;
MyThread2(Table t){
this.t=t;
t.printTable(100);
t1.start();
t2.start();
Output: 5
10
15
20
25
100
200
300
400
500
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
What is an exception?
An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such cases
we get a system generated error message. The good thing about exceptions is that they can be
handled.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
Advantages of Exception Handling
Exception handling allows us to control the normal flow of the program by using
exception handling in program.
It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can get
terminated and system prints a non user friendly error message.
Ex:-Take a look at the below system generated exception
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
Hierarchy of Java Exception classes
a[10]=50; //ArrayIndexOutOfBoundsException
NoMatchException(String message)
{
Super(message);
}
}
class NoMatch
{
public static void main(String args[])
{
try
{
if(args[0].compareTo("India") == 0)
{
System.out.println("\nString is equal to 'India'.");
}
else
{
throw new NoMatchException("Arguments is not equal to 'India'.");
}
}
catch(NoMatchException e)
{
System.out.println("\nException Caught: ");
System.out.println(e.getMessage());
}
}
}
Unit – V
Applet and Graphics Programming
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
These are the different stages involved in the life cycle of an applet:
Initialization State
Running state
Idle or stopped state
Dead state
Initialization State : This state is the first state of the applet life cycle. An applet is created by
the method init(). This method initializes the created applet. It is Called exactly once in an
applet's life when applet is first loaded, which is after object creation, e.g. when the browser
visits the web page for the first time.Used to read applet parameters, start downloading any other
images or media files, etc.
Running State : This state is the second stage of the applet life cycle. This state comes when
start() method is called. Called at least once.Called when an applet is started or restarted, i.e.,
whenever the browser visits the web page.
Idle or Stopped State : This state is the third stage of the applet life cycle. This state comes
when stop() method is called implicitly or explicitly.stop() method is called implicitly. It is called
at least once when the browser leaves the web page when we move from one page to another.
This method is called only in the running state and can be called any number of times.
Dead State : This state is the fourth stage of the applet life cycle. This state comes when
destroy() method is called. In this state the applet is completely removed from the memory. It
called exactly once when the browser unloads the applet.Used to perform any final clean-up. It
occurs only once in the life cycle.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
/*
<applet code="GrpStringEx.class" width="400" height="400">
</applet
*/
public class GrpStringEx extends Applet
{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawString("welcome-to-appletworld-in-java", 150, 150);
}
}
Output
To execute our code by the appletviewer tool, write in the command prompt:
javac GrpStringEx.java
appletviewer GrpStringEx.java
2. Draw a rectangle
In this example, we draw a simple rectangle.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpRectEx.class" width="400" height="400">
</applet
*/
public class GrpRectEx extends Applet
{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawRect(100,50,150,150);
}
}
Output
6. Draw a line
In this example, we draw a simple line with specified co-ordinates.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpLineEx.class" width="400" height="400">
</applet
*/
*/
Output
Display Numerical Values in Applet
In applets, we can display numerical values by first converting them into strings and then using
the drawstring() method of Graphics class we can do this easily by calling the valueOf() Method
of String class. Let us consider an example:
import java.awt.*;
import java.applet.*;
/*<APPLET Code="DisplayNumericalValues.class" Width=400 Height=300>
</APPLET>
*/
public class DisplayNumericalValues extends Applet
{
public void paint(Graphics g)
{
int val1 = 10;
int val2 = 20;
int sum = val1 + val2;
String str_sum = "Sum="+String.valueOf(sum);
g.drawString(str_sum,100,200);
}
}
Output
Getting Input from the User in Java Applet
Applets work in graphical environment. Therefore applets treat input as text strings. We must
first create an area of the screen in which user can type and edit input items. We can do this by
using the TextField class of the applet package. The values of the fields can be given even editer
after the creation of input fields. Next step is to retrieve the items from the fields for display of
calculations.
For any kinds of computation on the input field, we must convert it to the right form and the
resuls again converted back to strings for display.
Let us consider an example
import java.awt.*;
import java.applet.*;
/*<APPLET Code="GettingInputfromtheUser.class" Width=400 Height=300>
</APPLET>*/
public class GettingInputfromtheUser extends Applet
{
TextField t1, t2;
public void init()
{
t1 = new TextField(10);
t2 = new TextField(10);
add(t1);
add(t2);
t1.setText("0");
t2.setText("0");
}
public void paint(Graphics g)
{
int a=0,b=0,c=0;
String str1,str2,str;
try
{
str1=t1.getText();
a=Integer.parseInt(str1);
str2=t2.getText();
b=Integer.parseInt(str2);
}
catch(Exception e)
{
}
c=a+b;
str=String.valueOf(c);
g.drawString("Sum is",10,15);
g.drawString(str,100,75);
}
}
Output
Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change of state of any object. Example : Pressing
a button, Entering a character in Textbox.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because
it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Commonly used methods of OutputStream class
Method Description
1) public void write(int)throws IOException: is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException: stream.
4) public void close()throws IOException: is used to close the current output stream.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream.It returns -1 at
IOException: the end of file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException: from the current input stream.
Constructor Description
1) SequenceInputStream(InputStream s1, creates a new input stream by reading the data of two
InputStream s2) input stream in order, first s1 and then s2.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
}
}
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
success...
System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
Sachin is my favourite player
Java FileWriter and FileReader (File
Handling in java)
Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to
read and write the textual information.
Constructor Description
FileWriter(File file) creates a new file. It gets file name in File object.
Method Description
Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't exist, it
file) throws FileNotFoundException.
It gets filename in file instance. It opens the given file in read mode. If file doesn't
FileReader(File file)
exist, it throws FileNotFoundException.
Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the end of file.