0% found this document useful (0 votes)
27 views

Unit 1 Part 2

Java was developed in 1991 and is a simple, object-oriented programming language that is designed to have few implementation dependencies. It is commonly used for mobile apps, web apps, games, and more. Java features include being platform independent, secure, multi-threaded, and having high performance.

Uploaded by

Dinesh Tripathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Unit 1 Part 2

Java was developed in 1991 and is a simple, object-oriented programming language that is designed to have few implementation dependencies. It is commonly used for mobile apps, web apps, games, and more. Java features include being platform independent, secure, multi-threaded, and having high performance.

Uploaded by

Dinesh Tripathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Introduction to Java

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired
by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few
implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any Java Virtual
Machine.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection

Features of Java
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that played an
important role in moulding out the final form of this outstanding language. Those features are:
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and
ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner
way.

Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily extendedas it
is based on Object Model. Following are some basic concept of OOP's.

i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation

3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error
checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage Collector and
Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine with
Java Runtime Environment can run Java Programs.

5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.

6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.

7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on computer networks. Java
has a special class library for communicating using TCP/IP protocols. Creating network
connections is very much easy in Java as compared to C/C++.
What is a Variable?
When we want to store any information, we store it in an address of the computer. Instead of
remembering the complex address where we have stored our information, we name that
address.The naming of an address is known as variable. Variable is the name of memory
location.

In other words, variable is a name which is used to store a value of any type during program
execution.

To declare the variable in Java, we can use following syntax

datatype variableName;
Here, datatype refers to type of variable which can any like: int, float etc. and variableName
can be any like: empId, amount, price etc.
Java Programming language defines mainly three kind of variables.

1. Instance Variables
2. Static Variables (Class Variables)
3. Local Variables

Instance variables in Java


Instance variables are variables that are declare inside a class but outside any
method,constructor or block. Instance variable are also variable of object commonly
known as field or property.
They are referred as object variable. Each object has its own copy of each variable
and thus, itdoesn't effect the instance variable if one object changes the value of the
variable.
class Student
{
String name;int age;
}
Here name and age are instance variable of Student class.

Static variables in Java


Static are class variables declared with static keyword. Static variables are initialized
only once.Static variables are also used in declaring constant along with final
keyword.
class Student
{
String name;int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share
instituteCodeproperty.
Local variables in Java
Local variables are declared in method, constructor or block. Local variables are
initialized whenmethod, constructor or block start and will be destroyed once its end.
Local variable reside in stack. Access modifiers are not used for local variable.

float getDiscount(int price)


{
float discount;
discount=price*(20/100
); return discount;
}
Here discount is a local variable.

Data Types in Java


Java language has a rich implementation of data types. Data types specify size and
the type ofvalues that can be stored in an identifier.
In java, data types are classified into two catagories :

1. Primitive Data type


2. Non-Primitive Data type

1) Primitive Data type


A primitive data type can be of eight types :

Primitive Data types

char boolean byte short int long float double

Once a primitive data type has been declared its type can never change, although in
most casesits value can change. These eight primitive type can be put into four
groups

Integer
This group includes byte, short, int, long
byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default
value zero.example: byte b=10;
short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767.
Default value zero. example: short s=11;
int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to
2147483647.Default value zero. example: int i=10;
long : It is 8 bytes(64-bits) integer data type. Value range from -
9,223,372,036,854,775,808 to9,223,372,036,854,775,807. Default value zero.
example: long l=100012;

Example:
Lets create an example in which we work with integer type data and we can get idea
how to usedatatype in the java program.

package corejava;

public class Demo{

public static void main(String[] args) {


// byte typebyte b = 20;
System.out.println("b= "+b);
// short typeshort s = 20;
System.out.println("s= "+s);

// int typeint i = 20;


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

// long typelong l = 20;


System.out.println("l= "+l);

}
}

b= 20 s= 20 i= 20 l= 20
Floating-Point Number
This group includes float, double

float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double db=11.123;

Example:
In this example, we used floating point type and declared variables to hold floating values.Floating
type is useful to store decimal point values.

public class Demo{

public static void main(String[] args) {


// float type float f = 20.25f;
System.out.println("f= "+f);

// double type double d = 20.25;


System.out.println("d= "+d);
}
}

f= 20.25 d= 20.25
Characters
This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535.
example: charc='a';
Char Type Example
Char type in Java uses 2 bytes to unicode characters. Since it works with unicode then we can
store alphabet character, currency character or other characters that are comes under the unicode
set.

public class Demo {

public static void main(String[] args) {

char ch = 'S'; System.out.println(ch);

char ch2 = '&';


System.out.println(ch2);

char ch3 = '$'; System.out.println(ch3);

S&$
Boolean
This group represent boolean, which is a special type for representing true/false values. They are
defined constant of the language. example: boolean b=true;
Boolean Type Example
Boolean type in Java works with two values only either true or false. It is mostly use in
conditional expressions to perform conditional based programming.

public class Demo {

public static void main(String[] args) {

boolean t = true; System.out.println(t);

boolean f = false;
System.out.println(f);

true false

2) Non-Primitive(Reference) Data type


A reference data type is used to refer to an object. A reference variable is declare to be of
specific and that type can never be change.
For example: String str, here str is a reference variable of type String. String is a class in Java.
We will talk a lot more about reference data type later in Classes and Object lesson.
Reference type are used to hold reference of an object. Object can be instance of any class or
entity.

In object oriented system, we deal with object that stores properties. To refer those objects we
use reference types.

We will talk a lot more about reference data type later in Classes and Object lesson.

Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are
called Identifier. Identifier must follow some rules. Here are the rules:

● All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an


underscore.
● After the first character, an identifier can have any combination of characters.
● Java keywords cannot be used as an identifier.
● Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

Some valid identifiers are: int a, class Car, float amount etc.

Java Arrays
An array is a collection of similar data types. Array is a container object that hold values of
homogeneous type. It is also known as static data structure because size of an array must be
specified at the time of its declaration.

Array starts from zero index and goes to n-1 where n is length of the array.
In Java, array is treated as an object and stores into heap memory. It allows to store primitive
values or reference values.
Array can be single dimensional or multidimensional in Java.

Features of Array
● It is always indexed. Index begins from 0.
● It is a collection of similar data types.
● It occupies a contiguous memory location.
● It allows to access elements randomly.

Single Dimensional Array


Single dimensional array use single index to store elements. You can get all the elements of array
by just increment its index by one.
Array Declaration
Syntax :
datatype[] arrayName; or
datatype arrayName[];
Java allows to declare array by using both declaration syntax, both are valid.
The arrayName can be any valid array name and datatype can be any like: int, float, byte etc.

Example :
int[ ] arr; char[ ]
arr; short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.

Initialization of Array
Initialization is a process of allocating memory to an array. At the time of initialization, we specify
the size of array to reserve memory area.

Initialization Syntax

arrayName = new datatype[size] newoperator


is used to initialize an array.
The arrayName is the name of array, new is a keyword used to allocate memory and size islength of
array.

We can combine both declaration and initialization in a single statement.


Datatype[] arrayName = new datatype[size]
Example : Create An Array
Lets create a single dimensional array.

class Demo
{
public static void main(String[] args)
{
int[] arr = new int[5];for(int x :
arr)
{
System.out.println(x);
}
}
}

00000

In the above example, we created an array arr of int type and can store 5 elements. We iterate
the array to access its elements and it prints five times zero to the console. It prints zero because
we did not set values to array, so all the elements of the array initialized to 0 by default.
Set Array Elements
We can set array elements either at the time of initialization or by assigning direct to its index.
int[] arr = {10,20,30,40,50};
Here, we are assigning values at the time of array creation. It is useful when we want to store static
data into the array.
or
arr[1] = 105
Here, we are assigning a value to array’s 1 index. It is useful when we want to store dynamic data into
the array.
Array Example
Here, we are assigning values to array by using both the way discussed above.

class Demo
{
public static void main(String[] args)
{
int[] arr = {10,20,30,40,50};
for(int x : arr)
{
System.out.println(x);
}

// assigning a value

arr[1] = 105;
System.out.println("element at first index: " +arr[1]);
}
}

10 20 30 40 50 element at first index: 105

Accessing array element


we can access array elements by its index value. Either by using loop or direct index value. We can
use loop like: for, for-each or while to traverse the array elements.
Example to access elements
class Demo
{
public static void main(String[] args)
{
int[] arr = {10,20,30,40,50};
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}

System.out.println("element at first index: " +arr[1]);


}
}
10 20 30 40 50 element at first index: 20

Here, we are traversing array elements using loop and accessed an element randomly.
Note:-To find the length of an array, we can use length property of array object like:
array_name.length.

Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have multiple
rows and multiple columns unlike single dimensional array, which can have only onerow index.

It represent data into tabular form in which data is stored into row and columns.
Multi-Dimensional Array Declaration
datatype[ ][ ] arrayName;

Initialization of Array
datatype[ ][ ] arrayName = new int[no_of_rows][no_of_columns];
The arrayName is the name of array, new is a keyword used to allocate memory and no_of_rows
and no_of_columns both are used to set size of rows and columns elements.
Like single dimensional array, we can statically initialize multi-dimensional array as well.
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};

Example:

class Demo
{
public static void main(String[] args)
{
int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
for(int i=0;i<3;i++)
{
for (int j = 0; j < 5; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();

// assigning a value
System.out.println("element at first row and second column: "
+arr[0][1]);
}
}
Java Class
In Java everything is encapsulated under classes. Class is the core of Java language. It can be
defined as a template that describe the behaviors and states of a particular entity.
A class defines new data type. Once defined this new type can be used to create object of that
type.

Object is an instance of class. You may also call it as physical existence of a logical template
class.
In Java, to declare a class class keyword is used. A class contain both data and methods that
operate on that data. The data or variables defined within a class are called instance variables
and the code that operates on this data is known as methods.
Thus, the instance variables and methods are known as class members.
Rules for Java Class

● A class can have only public or default(no modifier) access specifier.


● It can be either abstract, final or concrete (normal class).
● It must have the class keyword, and class must be followed by a legal identifier.
● It may optionally extend only one parent class. By default, it extends Object class.
● The variables and methods are declared within a set of curly braces.

A Java class can contains fields, methods, constructors, and blocks. Lets see a general structure
of a class.
Java class Syntax

class class_name {field;


method;
}

A simple class example


Suppose, Student is a class and student's name, roll number, age are its fields and info() is a
method. Then class will look like below.
class Student.
{
String name;int
rollno; int age;
void info(){
// some code
}
}
This is how a class look structurally. It is a blueprint for an object. We can call its fields andmethods
by using the object.

The fields declared inside the class are known as instance variables. It gets memory when anobject
is created at runtime.
Methods in the class are similar to the functions that are used to perform operations andrepresent
behavior of an object.

After learning about the class, now lets understand what is an object.

Java Object
Object is an instance of a class while class is a blueprint of an object. An object represents theclass
and consists of properties and behavior.
Properties refer to the fields declared with in class and behavior represents to the methods available in
the class.
In real world, we can understand object as a cell phone that has its properties like: name, cost, color
etc and behavior like calling, chatting etc.

So we can say that object is a real world entity. Some real world objects are: ball, fan, car etc.There is
a syntax to create an object in the Java.

Java Object Syntax

className variable_name = new className();


Here, className is the name of class that can be anything like: Student that we declared in the
above example.
variable_name is name of reference variable that is used to hold the reference of created object.
The new is a keyword which is used to allocate memory for the object.

Lets see an example to create an object of class Student that we created in the above classsection.
Although there are many other ways by which we can create object of the class. we have covered
this section in details in a separate topics.

Example: Object creation

Student std = new Student();


Here, std is an object that represents the class Student during runtime.
The new keyword creates an actual physical copy of the object and assign it to the std variable.
It will have physical existence and get memory in heap area. The new operator dynamically
allocates memory for an object.
In this image, we can get idea how the an object refer to the memory area.

Methods in Java
Method in Java is similar to a function defined in other programming languages. Method describes
behavior of an object. A method is a collection of statements that are grouped together to perform an
operation.

For example, if we have a class Human, then this class should have methods like eating(), walking(),
talking() etc, which describes the behavior of the object.
Declaring method is similar to function. See the syntax to declare the method in Java.

return-type methodName(parameter-list)
{
//body of method
}
return-type refers to the type of value returned by the method.

methodName is a valid meaningful name that represent name of a method.

parameter-list represents list of parameters accepted by this method.

Method may have an optional return statement that is used to return value to the caller function.
Example of a Method:
Lets understand the method by simple example that takes a parameter and returns a string value.
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}

Modifier : Modifier are access type of method. We will discuss it in detail later.

Return Type : A method may return value. Data type of value return by a method is declare in
method heading.

Method name : Actual name of the method.


Parameter : Value passed to a method.

Method body : collection of statement that defines what method does


Calling a Method
Methods are called to perform the functionality implemented in it. We can call method by its
name and store the returned value into a variable.
String val = GetName(".com")
It will return a value studytonight.com after appending the argument passed during method call.

Inheritance (IS-A relationship) in Java


Inheritance is one of the key features of Object Oriented Programming. Inheritance provided
mechanism that allowed a class to inherit property of another class. When a Class extendsanother
class it inherits all non-private members including fields and methods. Inheritance inJava can be best
understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub
class(child) in Java language.

Inheritance defines is-a relationship between a Super class and its Sub class.

extendsand implementskeywords are used to describe inheritance in Java.


Let us see how extends keyword is used to achieve Inheritance. It shows super class and sub-class
relationship.
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class
}

Purpose of Inheritance
1. It promotes the code reusabilty i.e the same methods and variables which are defined in a
parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.

Disadvantages of Inheritance
1. Main disadvantage of using inheritance is that the two classes (parent and child class)
gets tightly coupled.
2. This means that if we change code of parent class, it will affect to all the child classes
which is inheriting/deriving the parent class, and hence, it cannot be independent of
each other.

Simple example of Inheritance


Before moving ahead let's take a quick example and try to understand the concept of Inheritance
better,
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {

public void c1()


{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child(); cobj.c1(); //method of
Child class cobj.p1(); //method of Parent class
}
}
Types of Inheritance
Java mainly supports only three types of inheritance that are listed below.

1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance

NOTE: Multiple inheritance is not supported in java

We can get a quick view of type of inheritance from the below image.

Single Inheritance
When a class extends to another class then it forms single inheritance. In the below example, we
have two classes in which class A extends to class B that forms single inheritance.

class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}

public class B extends A{


public static void main(String[] args) {B b = new B();
b.show();

}
}

Multilevel Inheritance
When a class extends to another class that also extends some other class forms a multilevel
inheritance. For example a class C extends to class B that also extends to class A and all the data
members an methods of class A and B are now accessible in class C.
Example:

class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}

class B extends A{int b =


10; void showB() {
System.out.println("b = "+b);
}
}

public class C extends B{

public static void main(String[] args) {C c = new C();


c.show();
c.showB();
}
}

Hierarchical Inheritance
When a class is extended by two or more classes, it forms hierarchical inheritance. For example,class
B extends to class A and class C also extends to class A in that case both B and C share properties of
class A.

class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}

class B extends A{int b =


10; void showB() {
System.out.println("b = "+b);
}
}

public class C extends A{


public static void main(String[] args) {C c = new C();
c.show();
B b = new B();
b.show();
}
}

Java Package
Package is a collection of related classes. Java uses package to group related classes, interfaces and
sub-packages.
We can assume package as a folder or a directory that is used to store similar files.

In Java, packages are used to avoid name conflicts and to control access of class, interface and
enumeration etc. Using package it becomes easier to locate the related classes and it also provides a
good structure for projects with hundreds of classes and other files.

Lets understand it by a simple example, Suppose, we have some math related classes andinterfaces
then to collect them into a simple place, we have to create a package.
Types Of Package
Package can be built-in and user-defined, Java provides rich set of built-in packages in form of
API that stores related classes and sub-packages.

● Built-in Package: math, util, lang, i/o etc are the example of built-in packages.
● User-defined-package: Java package created by user to categorize their project's classes and interface
are known as user-defined packages.
How to Create 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
{
String empId;
String name;
}
The above statement will create a package woth name mypack in the project directory.

Java uses file system directories to store packages. For example the .javafile for any class you define to
be part of mypack package must be stored in a directory called mypack.
Example of Java packages
Now lets understand package creation by an example, here we created a leanjava package that stores
the FirstProgram class file.
//save as FirstProgram.javapackage
learnjava;
public class FirstProgram{
public static void main(String args[]) { System.out.println("Welcome to package example");
}
}

Accessing package without import keyword


If you use fully qualified name to import any class into your program, then only that particular class
of the package will be accessible in your program, other classes in the same package will not be
accessible. For this approach, there is no need to use the import statement. But you will have to use the
fully qualified name every time you are accessing the class or the interface. Thisis generally used
when two packages have classes with same names. For example: java.util and java.sqlpackages contain
Date class.

Example
In this example, we are creating a class A in package pack and in another class B, we are accessing it
while creating object of class A.
//save by A.java
package pack; public
class A {
public void msg() { System.out.println("Hello");
}
}

//save by B.javapackage
mypack; class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified nameobj.msg();
}
}
Java Interfaces
Interface is a concept which is used to achieve abstraction in Java. This is the only way by which we
can achieve full abstraction. Interfaces are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body. It can have When you
create an interface it defines what a class can do without saying anything about how the class will do
it.

It can have only abstract methods and static fields. However, from Java 8, interface can have
default and static methods and from Java 9, it can have private methods as well.
When an interface inherits another interface extends keyword is used whereas class use
implements keyword to inherit an interface.
Advantages of Interface

● It Support multiple inheritance


● It helps to achieve abstraction
● It can be used to achieve loose coupling.

Syntax:
interface interface_name {
// fields
// abstract/private/default methods
}

Interface Key Points

● Methods inside interface must not be static, final, native or strictfp.


● All variables declared inside interface are implicitly public, static and final.
● All methods declared inside interfaces are implicitly public and abstract, even if you don't use
public or abstract keyword.
● Interface can extend one or more other interface.
● Interface cannot implement a class.
● Interface can be nested inside another interface.

Time for an Example!


Let's take a simple code example and understand what interfaces are:
interface Moveable
{
int AVERAGE-SPEED = 40;
void move();
}

Example of Interface implementation


In this example, we created an interface and implemented using a class. lets see how toimplement the
interface.
interface Moveable
{
int AVG-SPEED = 40;
void move();
}
class Vehicle implements Moveable
{
public void move()
{
System .out. print in ("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle(); vc.move();
}
}

Java Exception Handling


Exception Handling is a mechanism to handle exception at runtime. Exception is a condition that
occurs during program execution and lead to program termination abnormally. There can be several
reasons that can lead to exceptions, including programmer error, hardware failures, files that need to
be opened cannot be found, resource exhaustion etc.

Suppose we run a program to read data from a file and if the file is not available then the program
will stop execution and terminate the program by reporting the exception message.
The problem with the exception is, it terminates the program and skip rest of the execution that means
if a program have 100 lines of code and at line 10 an exception occur then program will terminate
immediately by skipping execution of rest 90 lines of code.

To handle this problem, we use exception handling that avoid program termination and continue the
execution by skipping exception code.
Java exception handling provides a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
Uncaught Exceptions
Lets understand exception with an example. When we don't handle the exceptions, it leads to
unexpected program termination. In this program, an ArithmeticException will be throw due todivide
by zero.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an exception
and then throw it. As we don't have any mechanism for handling exception in the above program,
hence the default handler (JVM) will handle the exception and will print the details of the exception
on the terminal.
Java Exception
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsiblefor
doing something about the exception is called an exception handler
How to Handle Exception
Java provides controls to handle exception in the program. These controls are listed below.

● Try : It is used to enclose the suspected code.


● Catch: It acts as exception handler.
● Finally: It is used to execute necessary code.
● Throw: It throws the exception explicitly.
● Throws: It informs for the possible exception.

We will discuss about all these in our next tutorials.


Types of Exceptions
In Java, exceptions broadly can be categories into checked exception, unchecked exception and
error based on the nature of exception.

● Checked Exception

The exception that can be predicted by the JVM at the compile time for example : File that
need to be opened is not found, SQLException etc. These type of exceptions must bechecked
at compile time.

● Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException class. Unchecked
exception are ignored at compile time and checked at runtime. For example :
ArithmeticException, NullPointerException, Array Index out of Bound exception.
Unchecked exceptions are checked at runtime.

● Error
Errors are typically ignored in code because you can rarely do anything about an error. For
example, if stack overflow occurs, an error will arise. This type of error cannot be handled in
the code.
Java Exception class Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.

● Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
● RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
● Exceptions of type Error are used by the Java run-time system to indicate errors having
to do with the run-time environment, itself. Stack overflow is an example of such an
error.

Example: Handling Exception


Now lets understand the try and catch by a simple example in which we are dividing a number by
zero. The code is enclosed into try block and a catch handler is provided to handle the exception.
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a = 0;
b = 10;
c = b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}

Multiple catch blocks


A try block can be followed by multiple catch blocks. It means we can have any number of catch
blocks after a single try block. If an exception occurs in the guarded code(try block) the exception is
passed to the first catch block in the list. If the exception type matches with the first catch block it
gets caught, if not the exception is passed down to the next catch block. This continue until the
exception is caught or falls through all catches.
Multiple Catch Syntax
To declare the multiple catch handler, we can use the following syntax.

try
{
// suspected code
}
catch(Exception1 e)
{
// handler code
}
catch(Exception2 e)
{
// handler code
}

Now lets see an example to implement the multiple catch block that are used to catch
possibleexception.

The multiple catch blocks are useful when we are not sure about the type of exception during
program execution.
Examples for Multiple Catch blocks
In this example, we are trying to fetch integer value of an Integer object. But due to bad input,
itthrows number format exception.

class Demo{
public static void main(String[] args) {
try
{
Integer in = new Integer("abc");in.intValue();

}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}

Introduction to Multithreading in Java


Multithreading is a concept of running multiple threads simultaneously. Thread is a light weight unit
of a process that executes in multithreading environment.
A program can be divided into a number of small processes. Each small process can be addressed as
a single thread (a lightweight process). You can think of a lightweight process as a virtual CPU that
executes code or system calls. You usually do not need to concern yourself withlightweight
processes to program with threads. Multithreaded programs contain two or more threads that can run
concurrently and each thread defines a separate path of execution. This means that a single program
can perform two or more tasks simultaneously. For example, one thread is writing content on a file
at the same time another thread is performing spelling check.
In Java, the word thread means two different things.
● An instance of Thread class.
● or, A thread of execution.

An instance of Thread class is just an object, like any other object in java. But a thread of execution
means an individual "lightweight" process that has its own call stack. In java eachthread has its own
call stack.

Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory and perform context switching
aswell that helps to share the memory and reduce time of switching between threads.
Multitasking
Multitasking is a process of performing multiple tasks simultaneously. We can understand it by
computer system that perform multiple tasks like: writing data to a file, playing music, downloading
file from remote server at the same time.

Multitasking can be achieved either by using multiprocessing or multithreading. Multitasking by


using multiprocessing involves multiple processes to execute multiple tasks simultaneously whereas
Multithreading involves multiple threads to executes multiple tasks.
Why Multithreading ?
Thread has many advantages over the process to perform multitasking. Process is heavy weight,
takes more memory and occupy CPU for longer time that may lead to performance issue with the
system. To overcome these issue process is broken into small unit of independent sub-process.
These sub-process are called threads that can perform independent task efficiently. So nowadays
computer systems prefer to use thread over the process and use multithreading to perform
multitasking.
How to Create Thread ?
To create a thread, Java provides a class Thread and an interface Runnable both are located
intojava.lang package.

We can create thread either by extending Thread class or implementing Runnable interface.
Bothincludes a run method that must be override to provide thread implementation.
It is recommended to use Runnable interface if you just want to create a thread but can
useThread class for implementation of other thread functionalities as well.
We will discuss it in details in our next topics.
The mainthread
When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main
method.This thread is called as main thread. Although the main thread is automatically created,
you can control it by obtaining a reference to it by calling currentThread() method.

Two important things to know about main thread are,

● It is the thread from which other threads will be produced.


● It must be always the last thread to finish execution.

class MainThread
{
public static void main(String[] args)
{
Thread t = Thread.currentThread(); t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}

Life cycle of a Thread


Like process, thread have its life cycle that includes various phases like: new,
running,terminated etc. we have described it using the below image.

1. New : A thread begins its life cycle in the new state. It remains in this state until the start()
method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this
stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.

Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
tomake 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
codeunderstand 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.

Java Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStreamand OutputStream.

These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.

Some important Byte stream classes.


Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.


DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print()and println()method

These classes define several key methods. Two most important are

1. read(): reads byte of data.


2. write(): Writes byte of data.

Java Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.

These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes


Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.


FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReade Output stream that translate character to byte.


r
PrintWriter Output Stream that contain print()and println()method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read()method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));char c = (char)br.read();
//Reading character
}
}

Reading Strings in Java


To read string we have to use readLine()function with BufferedReader class's object.
String readLine() throws IOException

Program to take String input from Keyboard in Java

import java.io.*;class
MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new
BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Program to read from a file using BufferedReader class


import java. Io *;class
ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}

Program to write to a File using FileWriter class


import java. Io *;class
WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt"); String str="Write this string
to my file";FileWriter fw = new FileWriter(fl) ; fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser. This is the first
Java program that can run over the network using the browser. Applet is typically embedded
inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed on an
Internet server, transported over Internet, and can be automatically installed and run as apart of a
web document.

After a user receives an applet, the applet can produce a graphical user interface. It has limited
access to resources so that it can run complex computations without introducing the risk of
viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.

JVM creates an instance of the applet class and invokes init()method to initialize an Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.
Lifecycle of Java Applet
Following are the stages in Applet

1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
A Simple Applet
import java.awt.*; import
java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awtand java.applet.

java.awt.*imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. java.applet.* imports the applet package, which contains the class Applet.
Every applet that you create must be a subclass of Applet class.

The class in the program must be declared as public, because it will be accessed by code that is
outside the program.Every Applet application must declare a paint() method. This method is
defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about applet
application is that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main()method.
Advantages of Applets

1. It takes very less response time as it works on the client side.


2. It can be run on any browser which has JVM running in it.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.

An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

● init() : init() is the first method to be called. This is where variable are initialized. This method
iscalled only once during the runtime of applet.
● start() : start() method is called after init(). This method is called to restart an applet after it has
been stopped.
● stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
● destroy() : destroy() method is called when your applet needs to be removed completely from
memory.

Note: The stop() method is always called before destroy() method.


Example of an Applet Skeleton
import java.awt.*; import
java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Introduction to Java String Handling


String is an object that represents sequence of characters. In Java, String is represented by String
class which is located into java.langpackage
It is probably the most commonly used class in java library. In java, every string that we create is
actually an object of type String. One important thing to notice about string object is that string
objects are immutable that means once a string object is created it cannot be changed.
The Java String class implements Serializable, Comparable and CharSequence interface that we
have represented using the below image.
In Java, CharSequence Interface is used for representing a sequence of characters.
CharSequence interface is implemented by String, StringBuffer and StringBuilder classes. This
three classes can be used for creating strings in java.

What is an Immutable object?


An object whose state cannot be changed after it is created is known as an Immutable object.
String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.
Creating a String object
String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String
object.
public class Demo{
public static void main(String[] args) {String s1 = "Hello
Java"; System.out.println(s1);
}
}

2) Using new Keyword


We can create a new string object by using new operator that allocates memory for the object.
public class Demo{
public static void main(String[] args) {String s1 = new
String("Hello Java");System.out.println(s1);
}
}

1) Using concat() method


Concat()method is used to add two or more string into a single string object. It is string class method
and returns a string object.
public class Demo{

public static void main(String[] args) {String s = "Hello";


String str = "Java";
String str1 = s.concat(str);
System.out.println(str1);
}
}
HelloJava
2) Using + operator
Java uses "+"operator to concatenate two string objects into single one. It can also concatenate
numeric value with string object. See the below example.
public class Demo{
public static void main(String[] args) {String s = "Hello";
String str = "Java"; String str1 = s+str;
String str2 = "Java"+11;
System.out.println(str1);
System.out.println(str2);
}
}
HelloJava Java11
String Comparison
To compare string objects, Java provides methods and operators both. So we can compare string
in following three ways.

1. Using equals()method
2. Using ==operator
3. By CompareTo()method

Using equals() method


equals()method compares two strings for equality. Its general syntax is,

boolean equals (Object str)

Example
It compares the content of the strings. It will return true if string matches, else returns false.
public class Demo{
public static void main(String[] args) {String s = "Hell";
String s1 = "Hello";String s2
= "Hello";
boolean b = s1.equals(s2); //true
System.out.println(b);
b= s.equals(s1) ; //false
System.out.println(b);
}
}
true false

Event Handling

Components of Event Handling


Event handling has three main components,

● Events : An event is a change in state of an object.


● Events Source : Event source is an object that generates an event.
● Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occurs.

How Events are handled?


A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by
a number of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface

Event Classes Descriptio Listener Interface


n
generated when button is pressed, menu-item is selected,
ActionEvent ActionListener
list-item is double clicked

generated when mouse is dragged, moved,clicked,pressed


MouseEvent MouseListener
or released and also when it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

generated when window is activated, deactivated,


WindowEvent WindowListener
deiconified, iconified, opened or closed

generated when component is hidden, moved, resized or


ComponentEvent ComponentEventListener
set visible

generated when component is added or removed from


ContainerEvent ContainerListener
container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses keyboard focus FocusListener


Example of Event Handling
import java.awt.*; import
java.awt.event.*;
import java.applet.*;
import java.applet.*; import
java.awt.event.*;import java.awt.*;

public class Test extends Applet implements KeyListener


{
String msg=""; public void
init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}

Java Abstract Window Toolkit(AWT)


Java AWT is an API that contains large number of classes and methods to create and manage
graphical user interface ( GUI ) applications. The AWT was designed to provide a common set of
tools for GUI design that could work on a variety of platforms. The tools provided by the AWT are
implemented using each platform's native GUI toolkit, hence preserving the look andfeel of each
platform. This is an advantage of using AWT. But the disadvantage of such an approach is that GUI
designed on one platform may look different when displayed on another platform that means AWT
component are platform dependent.

AWT is the foundation upon which Swing is made i.e Swing is a improved GUI API that extendsthe
AWT. But now a days AWT is merely used because most GUI Java programs are implemented using
Swing because of its rich implementation of GUI controls and light-weightednature.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below, all the classes are available in java.awt
package.
Component class
Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the
attributes of visual component. A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field, tables etc.
Container is a subclass of component class. Container class keeps track of components that are
added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or border.
It is container that is used for holding components.
Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT applications
are created using Frame window. Frame class has two different constructors,
Frame() throws HeadlessException Frame(String title) throws
HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,

1. By Instantiating Frame class


2. By extending Frame class
Creating Frame Window by Instantiating Frame class
import java.awt.*; public
class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size. fm.setVisible(true);
//set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible
Example:
Lets take an example to create a button and it to the frame by providing coordinates.

import java.awt.*; public class


ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");Button b1=new
Button("Press Here"); b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}

AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is
allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
import java.awt.*;class
LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo"); Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}

AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e
true or false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it
returns true else returns false.

import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");Checkbox ckbox1 = new
Checkbox("Yes", true); ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1); checkB_f.add(ckbox2);
checkB_f.setSize(400,400); checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}

AWT Layouts:

Introduction
Layout means the arrangement of components within the container. In other way we can say that
placing the components at a particular position within the container. The task of layouting the
controls is done automatically by the Layout Manager.

Layout Manager
The layout manager automatically positions all the components within the container. If we do not
use layout manager then also the components are positioned by the default layout manager. It is
possible to layout the controls by hand but it becomes very difficult because of the following two
reasons.

● It is very tedious to handle a large number of controls within the container.


● Oftenly the width and height information of a component is not given when we need to
arrange them.

Java provide us with various layout manager to position the controls. The properties like size,shape
and arrangement varies from one layout manager to other layout manager. When the size of the applet
or the application window changes the size, shape and arrangement of the components also changes
in response i.e. the layout managers adapt to the dimensions of appletviewer or the application
window.
The layout manager is associated with every Container object. Each layout manager is an object of the
class that implements the LayoutManager interface.

Following are the interfaces defining functionalities of Layout Managers.

Sr.
Interface & Description
No.
LayoutManager

1 The LayoutManager interface declares those methods which need to be implemented by the
class whose object will act as a layout manager.

LayoutManager2

2 The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those


classes that know how to layout containers based on layout constraint object.

AWT Layout Manager Classes:


Following is the list of commonly used controls while designed GUI using AWT.
Sr.
Layout Manager & Description
No.
BorderLayout

1 The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.

CardLayout

2 The CardLayout object treats each component in the container as a card. Only one card is visible
at a time.

FlowLayout
3
The FlowLayout is the default layout.It layouts the components in a directional flow.

GridLayout
4
The GridLayout manages the components in form of a rectangular grid.

GridBagLayout

5 This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of
same size.

You might also like