0% found this document useful (0 votes)
6 views206 pages

Java Note(MCA)

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security. It supports various application types including standalone, web, enterprise, and mobile applications, and has four main editions: Java SE, Java EE, Java ME, and Java FX. Key features of Java include simplicity, robustness, platform independence, and a rich set of APIs, making it suitable for a wide range of programming tasks.

Uploaded by

bikashbbsahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views206 pages

Java Note(MCA)

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security. It supports various application types including standalone, web, enterprise, and mobile applications, and has four main editions: Java SE, Java EE, Java ME, and Java FX. Key features of Java include simplicity, robustness, platform independence, and a rich set of APIs, making it suitable for a wide range of programming tasks.

Uploaded by

bikashbbsahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 206

What is Java:

Java is a high level, robust, object-oriented and secure programming language.


It was developed by Sun Microsystems (which is now the subsidiary of Oracle)
in the year 1995. James Gosling is known as the father of Java. Before Java, its
name was Oak. Since Oak was already a registered company, so James Gosling
and his team changed the Oak name to Java.
Platform: Any hardware or software environment in which a program runs, is
known as a platform. Since Java has a runtime environment (JRE) and API, it is
called a platform.

Java Example

class Simple
{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output: Hello Java

Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-


based applications. These are traditional software that we need to install on
every machine. Examples of standalone application are Media player, antivirus,
etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called
a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF,
etc. technologies are used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is


called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile


application. Currently, Android and Java ME are used for creating mobile
applications.

Java Platforms / Editions:


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as


java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core
topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)

It is an enterprise platform which is mainly used to develop web and enterprise


applications. It is built on the top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

Features of Java

The primary objective of Java programming language creation was to make it


portable, simple and secure programming language. The features of Java are
also known as Java buzzwords.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
Its syntax is based on C++.Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator overloading, etc.
Object-oriented

Java is an object-oriented programming language. Everything in Java is an


object. Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
What is an object in Java

An entity that has state and behaviour is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). An object is an instance of a class.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID.

Class in Java

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Method in Java

In Java, a method is like a function which is used to expose the behaviour of an


object.

Advantage of Method
o Code Reusability
o Code Optimization
Inheritance: It is a mechanism in which one object acquires all the properties
and behaviours of a parent object. Moreover, you can add new methods and
fields in your current class also. Inheritance represents IS-A relationship which
is also known as a parent-child relationship.
Use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability
Polymorphism: It is a concept by which we can perform a single action in
different ways. We can perform polymorphism in java by method overloading
and method overriding.
Abstraction in Java: It is a process of hiding the implementation details and
showing only functionality to the user.
Encapsulation in Java: It is a process of wrapping code and data together into
a single unit, for example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members
of the class private. It is a way to achieve data hiding in Java because other
class will not be able to access the data through the private data members.
Platform Independent
Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while Java
is a write once, run anywhere language. A platform is the hardware or software
environment in which a program runs.
Java code can be executed on multiple platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode i.e (.class file). This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e., Write Once
and Run Anywhere (WORA).
Secured

Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because no explicit pointer is present.
Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a Java
application anymore.
o There are exception handling and the type checking mechanism in Java.
All these points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it occupies
4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable

Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance

Java is faster than other traditional interpreted programming languages because


Java bytecode is "close" to native code. It is still a little bit slower than a
compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.
Distributed

Java is distributed because it facilitates users to create distributed applications in


Java. RMI and EJB are used for creating distributed applications.
Multi-threaded

The main advantage of multi-threading is that it doesn't occupy memory for


each thread. It shares a common memory area. Threads are important for multi-
media, Web applications, etc.
Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means


classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

KEY DIFFERENCE:

 C++ uses only compiler, whereas Java uses compiler and interpreter both.
 C++ supports both operator overloading & method overloading whereas
Java only supports method overloading.
 C++ supports manual object management with the help of new and delete
keywords whereas Java has built-in automatic garbage collection.
 C++ supports structures and union whereas Java doesn’t support .

Advantage of OOPs over Procedure-oriented programming


language
1) OOPs makes development and maintenance easier, whereas, in a procedure-
oriented programming language, it is not easy to manage if code grows as
project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming
language, global data can be accessed from anywhere.
What is the difference between an object-oriented programming language
and object-based programming language?
Object-based programming language follows all the features of OOPs except
Inheritance. JavaScript and VBScript are examples of object-based
programming languages.

Java Naming conventions

Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.All the classes,
interfaces, packages, methods and fields of Java programming language are
given according to the Java naming convention. If you fail to follow these
conventions, it may generate confusion or erroneous code.By using standard
Java naming conventions, you make your code easier to read for yourself and
other programmers.

Advantage of naming conventions in java

The following are the key rules that must be followed by every identifier:

o The name must not contain any white spaces.


o The name should not start with special characters like & (ampersand), $
(dollar), _ (underscore).

CamelCase in java naming conventions


Java follows camel-case syntax for naming the class, interface, method, and
variable. If the name is combined with two words, the second word will start
with uppercase letter always such as actionPerformed(), firstName,
ActionEvent, ActionListener, etc.
Creating Hello World Example

class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.

Parameters used in First Java Program

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it
is visible to all.
o static is a keyword. If we declare any method as static, it is known as the
static method. The core advantage of the static method is that there is no
need to create an object to invoke the static method. The main() method is
executed by the JVM, so it doesn't require creating an object to invoke
the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program. Execution of program
always starts from main().
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class,
out is an object of the PrintStream class, println() is a method of the
PrintStream class.
Java Variables

A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.Variable is a name of memory
location.
Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. A
local variable can’t be defined with “static” keyword.
2) Instance Variable

A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static. It is called an instance variable
because its value is instance specific and is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local.


You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.
Scope of a Variable
o We can declare variables anywhere in the program but it has limited
scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and
constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the
main() function

Ex:
public class Demo
{
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[])
{
//local variable
int marks = 72;
}
}
Data Types in Java
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Operators in Java
Operator in Java is a symbol that is used to perform operations. For example:
+, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
OUTPUT
10
12
12
10

Java Unary Operator Example 2: ++ and --

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
OUTPUT:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-
11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}

OUTPUT
-11
9
False
true

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
}}
Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.

EX:

public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

 Logical &&(And) and Bitwise &

The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is
true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is
true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming. It is the only conditional operator which
takes three operands.
Java Ternary Operator Example

public class OperatorExample{


public static void main(String args[]){ int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output
2

Java Assignment Operator Example

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Java Keywords

Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
JavaControl Statements
If-else Statement
The Java if statement is used to test the condition. It
checks boolean condition: true or false. There are various types of if statement
in Java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is
true.

Syntax:

if(condition){
//code to be executed
}
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
System.out.print("Age is greater than 18");
}
}
Output:
Age is greater than 18
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.

Syntax:

if(condition){
//code if condition is true
}else{
//code if condition is false
}
Ex:1

public class IfElseExample {


public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0)
System.out.println("even number");
else
System.out.println("odd number");
}
}
Output:
Odd number
Leap Year Example:A year is leap, if it is divisible by 4 and 400. But, not by
100.

public class LeapYearExample {


public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0))
System.out.println("LEAP YEAR");
else
System.out.println("COMMON YEAR");
}
}
Output:
LEAP YEAR

Java if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A gr
ade and +.

public class IfElseIfExample


{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
System.out.println("fail");
else if(marks>=50 && marks<60){
System.out.println("D grade");
else if(marks>=60 && marks<70)
System.out.println("C grade");
else if(marks>=70 && marks<80)
System.out.println("B grade");
else if(marks>=80 && marks<90)
System.out.println("A grade");
else if(marks>=90 && marks<100)
System.out.println("A+ grade");
else
System.out.println("Invalid!");
}
}
Output:
C grade
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.

Syntax:

if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is
like if-else-if ladder statement.
Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output:20
Loops in Java

In programming languages, loops are used to execute a set of


instructions/functions repeatedly when some conditions become true. There are
three types of loops in Java.

o for loop
o while loop
o do-while loop

Comparison for loop while loop do while loop

Introduction The Java for loop is The Java while loop is The Java do while loop
a control flow a control flow is a control flow
statement that statement that executes statement that executes a
iterates a part of a part of the programs part of the programs at
the programs multipl repeatedly on the basis least once and the further
e times. of given boolean execution depends upon
condition. the given boolean
condition.

Syntax for(init;condition;inc while(condition){ do{


r/decr){ //code to be executed //code to be executed
// code to be } }while(condition);
executed
}

Example //for loop //while loop //do-while loop


for(int int i=1; int i=1;
i=1;i<=10;i++){ while(i<=10){ do{
System.out.println(i) System.out.println(i); System.out.println(i);
; i++; i++;
} } }while(i<=10);
Java Nested For Loop
If we have a for loop inside another loop, it is known as nested for loop. The
inner loop executes completely whenever outer loop executes.

public class PyramidExample {


public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}

Output:

*
**
***
****
*****

Java for-each Loop


The for-each loop is used to traverse array or collection in java. It is easier to
use than simple for loop because we don't need to increment value and use
subscript notation.It works on elements basis not index. It returns element one
by one in the defined variable.

Syntax:

for(Type var:array){

//code to be executed
}

Example:

//Java For-each loop example which prints the


//elements of the array
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr)
System.out.print(i);
}
}
Output:12 23 44 56 78

Java Break Statement

When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following the
loop.

//Java Program to demonstrate the use of break statement


public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
} }
Output:
1
2
Java Continue Statement
The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.

Syntax: continue;

//Java Program to demonstrate the use of continue statement


//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5)
continue;
System.out.print(i);
}
}
}
Output:1 2 3 4 6 7 8 9 10
//Java Program to illustrate the use of continue statement
public class ContinueExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement inside inner loop
continue;
}
System.out.println(i+" "+j);
}
}
}
}
Output:

11
12
13
21
23
31
32
33

Java comment lines

Java comments are the statements that are not executed by the compiler and
interpreter.

Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

//This is single line comment


public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
OUTPUT:10
2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/*
This
is
multi line
comment
*/

Example:

public class CommentExample2 {


public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
} }

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create


documentation API, you need to use javadoc tool.

Syntax:

/**
This
is
documentation
comment
*/
Ways to initialize object
There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference


class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.id=101;
s1.name="TACT";
s2.id=102;
s2.name="TAT";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
System.out.println(s2.id+" "+s2.name);//printing members with a white space
}
}
Ouput: 101 TACT
102 TAT
2) Object and Class Example: Initialization through method

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
3) Object and Class Example: Initialization through a constructor
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea()
{System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
Anonymous object
Anonymous simply means nameless. An object which has no reference is
known as an anonymous object. It can be used at the time of object creation
only.If you have to use an object only once, an anonymous object is a good
approach. For example:

new Calculation();//anonymous object

Calling method through a reference:

Calculation c=new Calculation();


c.fact(5);

Calling method through an anonymous object


new Calculation().fact(5);

Let's see the full example of an anonymous object in Java.

class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}

Output:

Factorial is 120
Constructors in Java
 In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one
constructor is called.
 It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

Default constructor (no-arg constructor):-


A constructor is called "Default Constructor" when it doesn't have any
parameter.

Syntax of default constructor:


<class_name>(){}
Example of default constructor
//Java Program to create and call a default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output: Bike is created

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.

Example of default constructor that displays the default values


class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output: 0 null
0 null
Parameterized constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.The parameterized constructor is used to provide
different values to distinct objects. However, you can provide the same values
also.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output: 111 Karan
222 Aryan
Difference between constructor and method in Java

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose the


state of an object. behaviour of an object.

A constructor must not have a return A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

The constructor name must be same as The method name may or may not be
the class name. same as the class name.

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from
one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They
are:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another
using Java constructor.

class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output: 111 Karan
111 Karan
Copy the values of one object into another by assigning the values of one
object into another:
class copy
{ int x;
copy(int a){x=a;}}
public static void main(String a[]){
copy cp=new copy(10);
copy cp1=new copy(20);
cp=cp1;
System.out.println(cp.x);
System.out.println(cp1.x);}}
22 Aryan 25
Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a
value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can
perform any operation in the constructor as you perform in the method.
Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal
information of a constructor in the class. It is found in the java.lang.reflect
package.
Java static keyword

The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.

1) Java static variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading,if any object changes the value of the static variable, it will
retain its value.
//Java Program to illustrate the use of static variable
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value
of it.

// Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:125
Restrictions for the static method
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.

class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
OUTPUT: COMPILER ERROR
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a
non-static method, JVM creates an object first then call main() method that will
lead the problem of extra memory allocation.
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of class loading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
OUTPUT: static block is invoked
Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6.
Since JDK 1.7, it is not possible to execute a Java class without the main
method.

class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
OUTPUT: static block is invoked

Since JDK 1.7 and above, output would be:

Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Java Arrays
Java array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array. Array in Java is index-based, the
first element of the array is stored at the 0th index, 2nd element is stored on 1st
index and so on.
Advantages
o Code Optimization: It makes the code optimized , we can retrieve or
sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization of Array

Syntax:int a[]={33,3,4,5};//declaration, instantiation and initialization

class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:
33
3
4
5

For-each Loop for Java Array


We can also print the Java array using for-each loop.
Syntax:
for(data_type variable:array){
//body of the loop
}
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:

33
3
4
5

Passing Array to a Method in Java


class Testarray2
{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Output:

3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare
the array while passing an array to the method.
public class TestAnonymousArray{
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to metho
d
}}

Output:

10
22
44
66

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column


//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Output:

123
245
445

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged
array. In other words, it is an array of arrays with different number of columns.
//Java Program to illustrate the jagged array
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//Printing the data of a jagged array
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

Output:

012
3456
78
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}

Output:

268
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is
multiplied by all the columns of the second matrix which can be understood by
the image given below.
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}}

Output:

666
12 12 12
18 18 18
String
When it comes to Java, a string is considered as an object that defines a
sequence of char values. In Java, arrays are unchangeable, likewise strings are
unchangeable(immutable) as well. In any case, if a modification happens in a
string, a completely new string is constructed. Java defines a class called String
in java.lang package. It allows to create and manipulate String objects.
Examples:
String myString = “Joy with Java”;
System.out.println(myString);
System.out.println(“Welcome”);
System.out.println(“Welcome” + “ “+ myString);
String aString = “An example of string is ” + myString;

Program:
import java.lang; // It is by default imported in all programs.
class BasicStringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
String myString = “Joy with Java”;
System.out.println(myString);
System.out.println(“Welcome”);
System.out.println(“Welcome” + “ “ + myString);
}
}
Operations on strings such as

1. Trimming
2. Concatenating
3. Converting
4. Comparing
5. Replacing, etc.

Constructors of String
String() Initializes a newly created String object so that it represents an
empty character sequence.
String(byte[] bytes) Constructs a new String by decoding the specified array
of bytes usingthe platform's default char set.
String(byte[] bytes, Charset charset) Constructs a new String by decoding
the specified array of bytes usingthe specified char set.
String(byte[] ascii, int hibyte) This method does not properly convert bytes
into characters. As ofJDK 1.1, the preferred way to do this is via the String
constructors that take a Charset, charset name, or that use the platform's default
charset.
String(byte[] bytes, int offset, int length) Constructs a new String by
decoding the specified subarray of bytes using the platform's default char set.
String(StringBuffer buffer) Allocates a new string that contains the
sequence of characterscurrently contained in the string buffer argument.
String(byte[] bytes, int offset,int length, Charset charset)Constructs a new
String by decoding the specified subarray of bytes using the specified charset.
Important methods of String class
Example 1 : length() of String

int length() Returns the number of characters in the String.


public class StringLengthDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
int stringLength = text.length();
System.out.print(stringLength);
}
}
Output Code
24
Example 2 : charAt()

char charAt(int i) Returns the character at i-th index.


public class CharAccessDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
char data = text.charAt(3);
System.out.print(data);
}
}
Output Code
A
Example 3 : concat()

String concat(String s) Concatenates specified string to the end of this string.

public class StringMergingDemo{


public static void main(String args[]){
String text1 = "DATA STRUCTURE WITH";
String text2 = " JAVA";
String text3 = text1.concat(text2);
System.out.print(text3);
}
}
Output Code
DATA STRUCTURE WITH JAVA

Example 4 : toLowerCase()

String toLowerCase() Converts all the characters in the String to lower case.

public class StringToLowerCaseDemo{


public static void main(String args[]){
String text = "Data Structure with Java";
String output = text.toLowerCase();
System.out.println(output);
}
}
Output Code
data structure with java
Example 5: toUpperCase()
String toUpperCase() Converts all the characters in the String to
upper case.

public class StringToUpperCaseDemo{


public static void main(String args[]){
String text = "Data Structure with Java";
String output = text.toUpperCase();
System.out.println(output);
}
}
Output Code
DATA STRUCTURE WITH JAVA

Example 6:trim()
String trim() Returns the copy of the String, by removing whitespaces at both
ends. It does not affectwhitespaces in the middle.

public class TrimStringDemo{


public static void main(String args[]){
String text = " Data Structure with Java ";
String output = text.trim();
System.out.println(output);
}
}
Output Code
Data Structure with Java
Example 7 : replace()

String replace(char old, char new) Returns new string by replacing all
occurrences of old withnew.

public class StringReplaceDemo{


public static void main(String args[]){
String text = "Data Structure with C++";
String output = text.replace("C++" ,"Java");
System.out.println(output);
}
}
Output Code
Data Structure with Java
Example 8 : equals()

Boolean equals(Object o) Compares this string to the specified object.


public class StringEqualsDemo{
public static void main(String args[]){
String text1 = "DATA STRUCTURE WITH JAVA";
String text2 = "DATA STRUCTURE WITH C++";
String text3 = "DATA STRUCTURE WITH JAVA";
boolean output1 = text1.equals(text2);
boolean output2 = text1.equals(text3);
System.out.println(output1);
System.out.println(output2);
}
}
Output
false
true
Example 9 : equalsIgnoreCase()
Boolean equalsIgnoreCase(String s) Compares string to another string, ignoring
case considerations.
public class StringEqualsCaseDemo{
public static void main(String args[]){
String text1 = "DATA STRUCTURE WITH JAVA";
String text2 = "DATA STRUCTURE WITH C++";
String text3 = "DATA STRUCTURE WITH JAVA";
String text4 = "data structure with c++";
String text5 = "data structure with java";
Boolean output1 = text1.equalsIgnoreCase(text2);
Boolean output2 = text1.equalsIgnoreCase(text3);
Boolean output3 = text1.equalsIgnoreCase(text4);
Boolean output4 = text1.equalsIgnoreCase(text5);
System.out.println(output1);
System.out.println(output2);
System.out.println(output3);
System.out.println(output4);
}
}
Output Code
false
true
false
true
Example 10 : compareTo()
int compareTo(String s) Compares two string lexicographically.

public class StringCompareDemo {


public static void main(String args[]){
String text1 = "DATA STRUCTURE WITH JAVA";
String text2 = "DATA STRUCTURE WITH C++";
String text3 = "DATA STRUCTURE WITH JAVA";
String text4 = "data structure with c++";
String text5 = "data structure with java";
int output1 = text1.compareTo(text2);
int output2 = text1.compareTo(text3);
int output3 = text1.compareTo(text4);
int output4 = text1.compareTo(text5);
System.out.println(output1);
System.out.println(output2);
System.out.println(output3);
System.out.println(output4);
}
}

Output Code
70 -
32
-32
Example 11 : substring()
String substring(int i) Returns the sub string starting from the character with i-th
index.
public class SubstringDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
String data = text.substring(3);
System.out.print(data);
}
}
Output Code
A STRUCTURE WITH JAVA

Example 12 : substring()
String substring(int i, int j) Returns the substring from character with i to j-1
indices.
public class SubstringAnyDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
String data = text.substring(5,14);
System.out.print(data);
}
}
Output Code
STRUCTURE
Example 13 : indexOf() method
int indexOf(String s, int i) Returns the index within the string of the first
occurrence of the specified string,
starting at the specified index.
public class Example{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
int output = text.indexOf("T",4);
System.out.print(output);
}
}
Output Code
6

Example 14 : lastIndexOf()
int lastIndexOf(String s) Returns the index within the string of the last
occurrence of the specified string.
public class Example{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
int output = text.lastIndexOf("T");
System.out.print(output);
}
}
Output Code
17
Example 15 : String to Int,Float
public class StringToIntegerDemo{
public static void main(String args[]){
String number = "95";
int num = Integer.parseInt(number);
int output = num + 5;
System.out.println(output);
String number1= "95.59";
float num1= Float.parseFloat(number1);
System.out.println(num1);
}
}
Output Code
100
95.59

Example 16 : Int to String


public class IntegerToStringDemo{
public static void main(String args[]){
int i=20;
String s=String.valueOf(i);
System.out.println(i+10); // + is binary plus operator
System.out.println(s+20); // + is string concatenation operator
}
}
Output Code
30
2020
Example 17 : Float to String
public class FloatToStringDemo{
public static void main(String args[]){
float f=15.5F;//F is the suffix for float
String s = String.valueOf(f);
System.out.println(s);
}
}
Output Code
15.5

Example 18 : to String
// The following program demonstrates binary, hexadecimal, and octal
conversion:
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " +
Integer.toBinaryString(num));
System.out.println(num + " in octal: " +
Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " +
Integer.toHexString(num));
}
}
Output Code
19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0
StringBuffer
StringBuffer is the equivalent class of the class string. The class StringBuffer
delivers more functionality to the other class strings. We can make changes here
because the StringBuffer is mutable.

String StringBuffer
String is immutable. It is mutable.

It is slow in terms of executing the It is fast in terms of executing the


concatenation task. concatenation task.

Here the length of the string class is Here the length can be modified
static. whenever required, as it is dynamic in
behaviour.

It is less efficient. It is more efficient in nature as


compared to the string class.

String consumes more as compared StringBuffer uses less memory as


to the stringbuffer. compared to the string.

It utilises a string constant pool to It prefers heap memory to store the


store the values. objects.

It overrides both equal() and It cannot override equal() and


hashcode() techniques of object class. hashcode() methods.
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects.
The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity


of 16.

StringBuffer(String str) It creates a String buffer with the specified string.

StringBuffer(int It creates an empty String buffer with the specified


capacity) capacity as length.

Important methods of StringBuffer class


Modifier and Method Description
Type

public append(String s) It is used to append the specified string


synchronized with this string. The append() method is
StringBuffer overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, It is used to insert the specified string with


synchronized String s) this string at the specified position. The
StringBuffer insert() method is overloaded like
insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int,
double) etc.
public replace(int It is used to replace the string from
synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex, String
str)

public delete(int It is used to delete the string from specified


synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least


minimumCapacity) equal to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the string


i.e. total number of characters.

public String substring(int It is used to return the substring from the


beginIndex) specified beginIndex.

public String substring(int It is used to return the substring from the


beginIndex, int specified beginIndex and endIndex.
endIndex)

What is a mutable String?


A String that can be modified or changed is known as mutable String.
StringBuffer and StringBuilder classes are used for creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.

class StringBufferExample{
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
}
}

Output:

Hello Java

2) StringBuffer insert() Method


The insert() method inserts the given String with this string at the given
position.

class StringBufferExample2{
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
}
}

Output:

HJavaello

3) StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex
and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

Output:

HJavalo

4) StringBuffer delete() Method


The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

Output:

Hlo

5) StringBuffer reverse() Method


The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5{

public static void main(String args[]){


StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Output:

olleH

6) StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:

16
16
34

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given
capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+
2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed. A
specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies. JVMs are
available for many hardware and software platforms (i.e. JVM is platform
dependent).

JVM Architecture
JVMcontainsclass loader, memory area, execution engine etc.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever


we run the java program, it is loaded first by the classloader. There are three
built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super
class of Extension classloader. It loads the rt.jar file which contains all
class files of Java Standard Edition like java.lang package classes,
java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and
parent classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the classfiles from classpath. By default,
classpath is set to current directory. You can change the classpath using "-
cp" or "-classpath" switch. It is also known as Application classloader.

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your
own classloader, you need to extend the ClassLoader class.

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 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.
8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to


communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or
interact with OS libraries.
JAVA API Documents
For complete application development, developers need to work with third-
party code. Now, in order to integrate the applications with the third-party code,
programmers need well-written documentation, in other words, API
documentation.

It is a set of predefined rules and specifications that need to be followed by the


programmer to use the services and resources provided by another software
program.

How to create an API Document?


By using the "javadoc" tool we can create a documented API in Java. In the
Java file, we must use the documentation comment /**......*/ to post information
for the class, constructors, field, method, etcetera.

What is javadoc tool?


The javadoc tool converts declarations and doc comments in Java source files
and formats the public and protected API into a set of HTML pages.
In general, it creates a list of classes, a class hierarchy and an index of the entire
API. As we pass arguments to javadoc, javadoc produces HTML pages by
default for that.

How to comment on the Source Code?


Since javadoc automatically creates an HTML web page, we can also add
further documentation inside doc comments, including special formatting with
HTML tags. Javadoc comments begin with (/**) and indicate text (provided by
the programmer) to be included automatically in the generated documentation.

/**
* This is a javadoc comment
**/

Using standard HTML in javadoc

We can also use standard HTML tags within a java-doc comment. However, we
don't use heading tags such as <h1>, <h2> and <h6>, or a horizontal rule <hr>.
An example that shows document API
In this example; we can create a simple class that contains a documentation
comment and shows how to create a documented API.
1. package com.mypack;
2. public Class APIDocEx
3. {
4. public static void square(int x)
5. {
6. System.out.println(x * x);
7. }
8. }
Output
To create the document API, we need to use the javadoc tool as in the
following.
In a command prompt write the following:
javadoc M.java

After generating the documented API. We will now see many HTML files
created. Now we need to open the index.html file to get the information about
the classes. The figure below shows the following.
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviours of a parent object. Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.
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 the parent class. Moreover, you can add new
methods and fields in your current class also.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is


the superclass. The relationship between the 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
Bonus of Programmer is:1000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical. In java programming, multiple and hybrid
inheritance is supported through interface only.

Note: Multiple inheritance is not supported in Java through class.


Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.
Ex:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As
you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...
Interface in Java:

An interface in Java is a blueprint of a class. It has static constants and abstract


methods. The interface in Java is a mechanism to achieve abstraction.It is used
to achieve abstraction and multiple inheritance in Java. Java Interface
also represents the IS-A relationship. Since Java 8, we can have default and
static methods in an interface. Since Java 9, we can have private methods in
an interface. Interface fields are public, static and final by default, and the
methods are public and abstract.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.

How to declare an interface?

An interface is declared by using the interface keyword.


Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces:
Java Interface Example
interface printable{
void print();
}
class A implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A obj = new A();
obj.print();
}}

Output:

Hello

Multiple inheritance in Java by interface:


If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A1 obj = new A1();
obj.print();
obj.show();
}}

Output:
Hello
Welcome

Interface inheritance:
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}}

Output:

Hello
Welcome

Java 8 Default Method in Interface:


Since Java 8, we can have method body in interface. But we need to make it
default method. Let's see an example:
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

Output:

drawing rectangle
default method

Java 8 Static Method in Interface:

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:

drawing rectangle
27
Member access rules in Java

The access modifiers in Java specifies the accessibility or scope of a field,


method, constructor, or class.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.

There are many non-access modifiers, such as static, abstract, synchronized,


native, volatile, transient, etc. Here, we are going to learn the access modifiers
only.
Understanding Java Access Modifiers

Access within class within outside outside


Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Private Constructor

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
//save by A.java
package pack;
class A{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the
package but through inheritance only.
It provides more accessibility than the default modifier.
Example of protected access modifier

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
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
this keyword in Java
1) this: to refer current class instance variable

this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and formal parameters, this keyword
resolves the problem of ambiguity.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

111 ankit 5000.0


112 sumit 6000.0

2) this: to invoke current class method

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.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
OUTPUT: hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It
is used to reuse the constructor. In other words, it is used for constructor
chaining.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}

Output:

hello a
10
4) this: to pass as an argument in the method

this keyword can also be passed as an argument in the method. It is mainly


used in the event handling.

class Test
{
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}

// Method that receives 'this' keyword as parameter


void display(Test obj)
{
System.out.println("a = " +obj.a + " b = " + obj.b);
}

// Method that returns current class instance


void get()
{
display(this);
}

public static void main(String[] args)


{
Test object = new Test();
object.get();
}
-Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is referred by super reference
variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
OUTPUT: black
white
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark(); }}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

Java final keyword:


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).

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
} }
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run(); }}
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running

Q)What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as


blank final variable .We can initialize a blank final variable in constructor
only.
class Bike{
final int speedlimit;//blank final variable

Bike(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike(); }}
output: 70

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

class Bik{
int cube(final int n){
n=n+2;//can't be changed as n is final
}
public static void main(String args[]){
Bike b=new Bike();
b.cube(5);
}}
Output:Compile Time Error

Q) Can we declare a constructor final?

No, because constructor is never inherited.


Polymorphism in Java

Polymorphism allows us to perform a single action in different ways. In other


words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms,
so it means many forms.
Real life example of polymorphism: A person at the same time can have
different characteristic. Like a man at the same time is a father, a husband, an
employee. So, the same person possesses different behaviour in different
situations. This is called polymorphism.
In Java polymorphism is mainly divided into two types:

 Compile time Polymorphism


 Runtime Polymorphism

1. Compile-time polymorphism: It is also known as static


polymorphism. This type of polymorphism is achieved by Method overloading
or Operator overloading. But Java doesn’t support the Operator Overloading.

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it
is known as MethodOverloading.Method overloading increases the readability
of the program.
Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type
Ex-1

import java.util.*;
class overload
{
Scanner sc=new Scanner(System.in);
void Add()
{
System.out.println("Eneter a number");
int x=sc.nextInt();
System.out.println("Eneter a number");
int y=sc.nextInt();
System.out.println("Result="+(x+y));
}
int Add(int x,inty,int z)
{return(x+y+z);}
}
class OverloadDemo
{
public static void main(String args[])
{
overload ob1=new overload();
ob1.Add();
System.out.println("Additionof three
integers="+ob1.Add(10,20,30));
}
}
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that each
constructor performs a different task. They are differentiated by the compiler by
the number of parameters in the list and their types.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output: 111 Karan 0
222 Aryan 25
Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a
class by method overloading. But JVM calls main() method which receives
string array as arguments only. Let's see the simple example:
class TestOverloading{
public static void main(String[] args){System.out.println("HELLO JAVA");}
public static void main(String args){System.out.println("HII");}
public static void main(){System.out.println("HELLO WORLD");}
}

Output: HELLO JAVA

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method
overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


The method must have the same name as in the parent class

The method must have the same parameter as in the parent class.

There must be an IS-A relationship (inheritance).


class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}}

Output:

Bike is running safely

Why can we not override static method?

It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to
the heap area.
Can we override java main method?

No, because the main is a static method.


Difference between method Overloading and Method Overriding

Method Overloading Method Overriding

Method overloading is used to Method overriding is used to provide


increase the readability of the the specific implementation of the
program. method that is already provided by its
super class.

Method overloading is Method overriding occurs in two


performed within class. classes that have IS-A (inheritance)
relationship.

In case of method In case of method


overloading, parameter must be overriding, parameter must be same.
different.

Method overloading is the example Method overriding is the example


of compile time polymorphism. of run time polymorphism.

In java, method overloading can't be Return type must be same or


performed by changing return type covariant in method overriding.
of the method only. Return type can
be same or different in method
overloading. But you must have to
change the parameter.
Run time Polymorphism in Java(Dynamic method
dispatch):

Runtime polymorphism or Dynamic Method Dispatch is a process in which


a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is based
on the object being referred to by the reference variable.
Example of Java Runtime Polymorphism

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
} }
Output:

drawing rectangle...
drawing circle...
drawing triangle.

Java instanceof operator:

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

class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println (s instanceof Simple1);//true
}
}

Output:true
Abstract class in Java:

o A class which is declared with the abstract keyword is known as an


abstract class in Java. It can have abstract and non-abstract methods
(method with the body).It needs to be extended and its method
implemented. It cannot be instantiated. It can have constructors and static
methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
o Abstraction is a process of hiding the implementation details and
showing only functionality to the user. Another way, it shows only
essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract


Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}}
Output : running safely

Another example:
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest of SBI
is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest of PNB
is: "+b.getRateOfInterest()+" %");
}}

Output: Rate of Interest of SBI is: 7 %


Rate of Interest of PNB is: 8 %

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
} }

Output: bike is created

running safely

gear changed
Difference between abstract class and interface
Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have Members of a Java interface are public by
class members like private, protected, default.
etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
Java Package

A java package is a group of similar types of classes, interfaces and sub-


packages. Package in java can be categorized in two form, built-in package and
user-defined package. There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages. 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

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Reading and Writing at Console in Java
Input from Console
There are several ways to read data given by the user at the console. They are:

 Scanner class
 BufferedReader class
 Console class

Scanner Class
This is the most common and preferred method to take input. It is used to read
input from the console. However, it was initially brought up for the purpose of
parsing strings and primitive data types.
import java.util.Scanner;
publicclass ReadWriteConsole {
publicstaticvoid main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter some string: ");
String myString = in.nextLine();
System.out.println("Please enter some integer: ");
int myInt = in.nextInt(); //This parses to integer
System.out.println("Please enter some float: ");
float myFloat = in.nextFloat(); //This parses to float
System.out.println("*******Validation Part*******");
System.out.println("Your input string: "+myString);
System.out.println("Your input int: "+myInt);
System.out.println("Your input float: "+myFloat);
}

}
Output:
Please enter some string:
trident
Please enter some integer:
89
Please enter some float:
80.8
*******Validation Part*******
Your input string: trident
Your input int: 89
Your input float: 80.8

BufferedReader Class
This is the classical way to take input, which was part of JDK's first release.
Here, we instantiate the BufferedReader class by wrapping
an InputStreamReader which wraps the standard console input stream. It
buffers the input for efficient reading. It is accompanied by static methods of
Wrapper classes to read corresponding data types.
import java.io.*;
publicclass ReadWriteConsole
{
publicstaticvoid main(String args[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter some string: ");
String myString = in.readLine();
System.out.println("Please enter some integer: ");
int myInt = Integer.parseInt(in.readLine());
System.out.println("Please enter some float: ");
float myFloat = Float.parseFloat(in.readLine());
System.out.println("*******Validation Part*******");
System.out.println("Your input string: "+myString);
System.out.println("Your input int: "+myInt);
System.out.println("Your input float: "+myFloat);
}
}
Output
Please enter some string:
trident
Please enter some integer:
88
Please enter some float:
8.9
*******Validation Part*******
Your input string: trident
Your input int: 88
Your input float: 8.9

 Console Class
The Java Console class is be used to get input from console. It provides
methods to read texts and passwords.If you read password using Console class,
it will not be displayed to the user.
import java.io.*;
public class Main
{
public static void main(String[] args) {
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
System.out.println("Enter your age: ");
int n1=Integer.parseInt(c.readLine());
System.out.println(n1);

}
}
Using Command line argument :
The java command-line argument is an argument i.e. passed at the time of
running the java program. The arguments passed from the console can be
received in the java program and it can be used as an input. So, it provides a
convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.

// Program to check for command line arguments


class CommandLineExample {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if (args.length> 0) {
System.out.println("The command line arguments are:");
for(String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}

1. compile by > javac CommandLineExample.java


2. run by > java CommandLineExample sonoo how are you
output: sonoo how are you
Output to Console
There are two ways to write at the console. Both the ways belong to
class PrintStream( Character-based class ).

 print andprintln methods: Here, the methods are defined by


class Printstream and is referenced by System.out. These methods are
widely used.
 write method: It is also defined by PrintStream class. It
is not recommended for use.

import java.io.*;
publicclass ReadWriteConsole
{
publicstaticvoid main(String args[]) throws IOException
{
for(int i=1;i<=5;i++)
System.out.print(i);
for(inti=1;i<=5;i++)
System.out.println(i);
for(int x=65;x<=70;x++){
System.out.write(x);
System.out.write('\n');
}
}
}
File Handling in Java

In Java, with the help of File Class, we can work with files. This File Class is
inside the java.io package. The File class can be used by creating an object of
the class and then specifying the name of the file.
Why File Handling is Required?
 File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
 In simple words, file handling means reading and writing data to a
file.

File Operations
We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
import java.io.File;
import java.io.IOException;
publicclass IOClass
{
publicstaticvoid main(String[] args)
{
try
{
File f0 = new File("D:Myfile.txt");
if (f0.createNewFile())
System.out.println("File " + f0.getName() + " is created successfully.");
else
{
System.out.println("File is already exist in the directory.");
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
System.out.println("Is file writeable?: " + f0.canWrite());
System.out.println("Is file readable " + f0.canRead());
System.out.println("The size of the file in bytes is: " + f0.length());
}
}
catch (IOException exception)
{
System.out.println("An unexpected error is occurred.");

}
}

}
What is a Stream in Java?
Stream in Java Programming Language is the sequence of the objects that are
pipelined to get desired results.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
The Stream is not a data structure instead it just takes input from collections of
I/O. Stream doesn’t change the original methods or data structure it just
pipelines it and provides our result.
There are two brands of Stream in Java Programming Language:

1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source.
The Input Stream provides the set of Objects and pipelines together to provide
us the functionality of Input the collection in I/O File.
2. Output Stream:
The Output Stream provides the functionality of writing the data to the
Destination. The Output Stream provides the set of Objects and pipelines
together to provide us the functionality of Output to the collection in I/O File.

Fig: Flow of data in standard Input-Output streams and file stream.


Character Stream in Java
Java provides Byte Stream to perform the input and output of 8-bit bytes data.
Java also provides the functionality of taking input and output in the form of
character i.e. in 16-bit Unicode.
Unlike Byte Stream, Character Stream takes two bytes at a time and processes
it. Character is more efficient as compared to Byte Stream but the Character
Stream usually uses the Byte Stream class to implement it.

Some important Character 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

OutputStreamReader Output stream that translate character to byte.

Output Stream that


PrintWriter
contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


Reading/Writing in a file using Character Stream classes
import java.io.*;
publicclass CharacterStream {

publicstaticvoid main(String[] args) throws IOException


{
//Reading data from keyboard
String text;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter some data");
text = br.readLine();
FileWriter fw=new FileWriter("D:MyDoc.txt");
fw.write(text);;
fw.close();
int i;
//String str;
FileReader fr= new FileReader("D:MyDoc.txt");
/*Display through BufferedReader
BufferedReader br2 = new BufferedReader(fr);
while ((str=br2.readLine())!=null)
System.out.println(str);*/
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}

}
Filecopy program(Using Character stream classes)
import java.io.*;
publicclass IOClassReadWrite {

publicstaticvoid main(String[] args) throws IOException


{

FileReader source = null;


FileWriter dest = null;
try {
source = new FileReader("D:Myfile.txt");
dest = new FileWriter("D:dest.txt");
int temp;
while ((temp = source.read()) != -1)
dest.write(temp);
System.out.println("Successfully copied");
}
finally
{
if (source != null)
source.close();
if (dest != null)
dest.close();
}
}
}
Program based on BufferedReader & Bufferedwriter
import java.io.*;
publicclass ReadWriteFileReaderWriter
{

publicstaticvoid main(String[] args) throws IOException


{

FileWriter writer = new FileWriter("D:\\testout.txt");


BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to java");
buffer.close();
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();

}
Byte Stream
Byte Stream is mainly consolidated with byte data. The byte data is nothing but
an 8-bits data. Java Byte Stream is used to perform the input and output in the
form of an 8-bits byte.This stream takes the input and computes it in the form of
byte data. There are many classes in Java that provide the byte stream but we
recommend using FileInputStream and FileOutputStream.
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
Reading/Writing in a file using Byte Stream classes

import java.io.*;
publicclass Bytestream
{
publicstaticvoid main(String[] args) throws IOException
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}
}
 Filecopy program(Using Byte stream classes)
import java.io.*;
publicclass IOClassWrite
{
publicstaticvoid main(String[] args) throws IOException
{
FileInputStream source = null;
FileOutputStream dest = null;
try {
source = new FileInputStream("D:Myfile.txt");
dest = new FileOutputStream("D:destination.txt");
int temp;
while ((temp = source.read()) != -1)
dest.write(temp);
System.out.println("Successfully copied");
}
finally
{
if (source != null)
source.close();
if (dest != null)
dest.close();

}
}
Reading/Writing Primitive types of data
import java.io.*;
publicclass MultipleData
{

publicstaticvoid main(String[] args) throws IOException


{
//Write primitive data type into file
File file = new File("file.txt");
FileOutputStream ft = new FileOutputStream(file);
DataOutputStream dt = new DataOutputStream(ft);
dt.writeInt(50);
dt.writeDouble(400.25);
dt.writeChar('A');
dt.flush();
ft.close();
dt.close();
//Read primitive data type from file
FileInputStream ft1 = new FileInputStream(file);
DataInputStream dt1 = new DataInputStream(ft1);
System.out.println(dt1.readInt());
System.out.println(dt1.readDouble());
System.out.println(dt1.readChar());
ft1.close();
dt1.close();
}
}
Exception Handling in Java

In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime. The Exception Handling in Java is
one of the powerful mechanisms to handle the runtime errors so that normal
flow of the application can be maintained ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of


the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception
at statement 5, the rest of the code will not be executed i.e. statement 6 to 10
will not be executed. If we perform exception handling, the rest of the statement
will be executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy
which is inherited by two subclasses: Exception and Error. A hierarchy of Java
Exception classes are given below:

Types of Java Exceptions

There are two types of exceptions: checked exception and unchecked exception.
The main difference between checked and unchecked exception is that the
checked exceptions are checked at compile-time while unchecked exceptions
are checked at runtime.
1.Checked Exception

2.Unchecked Exception

3.Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException


and Error are known as checked exceptions e.g.IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception:

Unchecked exceptions are not checked at compile time. Most of the times this
exception occurs due to the bad data provided by user during the user-program
interaction. It is up to the programmer to judge the conditions in advance, that
can cause such exceptions and handle them appropriately. All Unchecked
exceptions are direct sub classes of RuntimeException class.
The classes which inherit RuntimeException are known as unchecked
exceptionse.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBou
ndsException etc.
3) Error

Error is irrecoverable e.g.OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Java Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should


place exception code. The try block must be followed by either
catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an exception
in the method. It is always used with method signature.
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They
are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException.


Suppose I have a string variable that has characters, converting this variable into
digit will occur NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method. If an exception occurs at the particular statement of
try block, the rest of the block code will not execute. So, it is recommended not
to keeping the code in try block that will not throw an exception. Java try block
must be followed by either catch or finally block.
Syntax of Java try-catch

try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

 Java catch block


Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.The catch block must be
used after the try block only. You can use multiple catch block with a single try
block.
Problem without exception handling
public class TryCatchExample1 {
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
} }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).

Solution by exception handling


public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }

Output:

java.lang.ArithmeticException: / by zero
rest of the code
Example :Here, we handle the exception using the parent class exception.

public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //throw exception to the catch block
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }

Output:

java.lang.ArithmeticException: / by zero
rest of the code

Example :Print a custom message on exception.

public class TryCatchExample5 {


public static void main(String[] args) {
try
{ int data=50/0; }//throw exception to the catch block
catch(Exception e){
System.out.println("Can't divided by zero"); // displaying the custom msg
}}

Output:

Can't divided by zero


Example: In this example, along with try block, exception may arise in a
catch block.
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0;
}
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Here, we can see that the catch block didn't contain the exception code. So,
enclose exception code within a try block and use catch block only to handle the
exceptions.
Example:

public class TryCatchExample9 {


public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

Try block having multi-catch block:


A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform different
tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{ System.out.println("Parent Exception occurs");}
}
}

Output:

Arithmetic Exception occurs


rest of the code
Example 2

In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is invoked.
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
} }

Output:

Arithmetic Exception occurs


rest of the code
Example 3

In this example, we generate NullPointerException, but didn't provide the


corresponding exception type. In such case, the catch block containing the
parent exception class Exception will invoked.

public class MultipleCatchBlock3 {


public static void main(String[] args) {

try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs"
);
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}}

Output:

Parent Exception occurs


rest of the code
Example 4

Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).
class MultipleCatchBlock4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 co
mpleted");}
System.out.println("rest of the code...");
}}

Output:

Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement”);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}}
Output:
going to divide

java.lang.ArithmeticException: / by zero

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for


length 5

other statement

normal flow..
Java finally block

Java finally block is a block that is used to execute important code such as
closing connection, stream etc. Java finally block is always executed whether
exception is handled or not. Java finally block follows try or catch block.

Ex:
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output:5

finally block is always executed

rest of the code...


Java throw keyword
The Java throw keyword is used to explicitly throw an exception. We can throw
either checked or unchecked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception.

The syntax of java throw keyword is given below.

throw exception;

java throw keyword example


In this example, we have created the validate method that takes integer value as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:not valid


How can we create a custom exception in Java?

Sometimes it is required to develop meaningful exceptions based on the


application requirements. We can create our own exceptions by extending
Exception class in Java. User-defined exceptions in Java are also known as
Custom Exceptions.
Steps to create a Custom Exception with an Example
 CustomException class is the custom exception class this class is
extending Exception class.
 Create one local variable message to store the exception message
locally in the class object.
 We are passing a string argument to the constructor of the custom
exception object. The constructor set the argument string to the
private string message.
 toString() method is used to print out the exception message.
classCustomExceptionextendsException{
String message;
CustomException(String str){
message = str;
}
publicString toString(){
return("Custom Exception Occurred : "+ message);
}
}
publicclassMainException{
publicstaticvoid main(String args[]){
try{
thrownewCustomException("This is a custom message");
}catch(CustomException e){
System.out.println(e);
}
}
}

Output

Custom Exception Occurred : This is a custom message


Java throws keyword:

The throws keyword indicates what exception type may be thrown by a method.
publicvoidmyMethod() throwsArithmeticException, NullPointerException
{
// Statements that might throw an exception
}

Example of throws Keyword:


In this example the method myMethod() is throwing two checked
exceptions so we have declared these exceptions in the method
signature using throws Keyword. If we do not declare these exceptions then the
program will throw a compilation error.
importjava.io.*;
classThrowExample {
voidmyMethod(intnum)throwsIOException, ClassNotFoundException{
if(num==1)
thrownewIOException("IOException Occurred");
else
thrownewClassNotFoundException("ClassNotFoundException");
}
}

publicclassExample1{
publicstaticvoidmain(Stringargs[]){
try{
ThrowExampleobj=newThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:

java.io.IOException: IOExceptionOccurred
Differences between throw and throws.
Sr. Key throw throws
No.

Definition Throw is a keyword which Throws is a keyword used in


is used to throw an the method signature used to
exception explicitly in the declare an exception which
1
program inside a function might get thrown by the
or inside a block of code. function while executing the
code.

Internal Internally throw is On other hand we can declare


implementation implemented as it is multiple exceptions with
allowed to throw only throws keyword that could
2 single exception at a time get thrown by the function
i.e we cannot throw where throws keyword is
multiple exception with used.
throw keyword.

Type of With throw keyword we On other hand with throws


exception can propagate only keyword both checked and
unchecked exception i.e unchecked exceptions can be
checked exception cannot declared and for the
3 be propagated using throw. propagation checked
exception must use throws
keyword followed by
specific exception class
name.

Syntax Syntax wise throw keyword On other hand syntax wise


4 is followed by the instance throws keyword is followed
variable. by exception class names.

Declaration In order to use throw On other hand throws


keyword we should know keyword is used with the
5
that throw keyword is used method signature.
within the method.
Difference between final, finally and finalize
final: It is a keyword that is used to apply restrictions on a class, method, or
variable.

 The class with this keyword cannot be inherited.


 The method with this keyword cannot be overridden.
 The variable with this keyword cannot be changed.
Ex:
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}

finally: In Java, finally is a block used to place important code that will be
executed whether or not an exception is handled.

Ex:
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}

finalize: finalize() is used to perform clean-up processing just before the


object is collected by the garbage collector. finalize is deprecated in Java 9.

class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc(); }}
Multithreading
Thread is an execution unit that is part of a process. A process can have
multiple threads, all executing at the same time. It is a unit of execution in
concurrent programming. A thread is a flow of execution through the process
code, with its own program counter that keeps track of which instruction to
execute next, system registers which hold its current working variables, and a
stack which contains the execution history. Threads provide a way to improve
application performance through parallelism.

Advantages of Thread

 Threads minimize the context switching time.


 Use of threads provides concurrency within a process.
 Efficient communication.
 It is more economical to create and context switch threads.
 Threads allow utilization of multiprocessor architectures to a greater scale
and efficiency.
Life cycle of a thread in Java

A thread goes through various stages in its lifecycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete
life cycle of a thread.

Following are the stages of the life cycle −


New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. Thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
How to create a thread in Java
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Th
class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()

method on the thread.

3. public void sleep(long miliseconds): Causes the currently executing thread to


(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified

miliseconds.

6. public int getPriority(): returns the priority of the thread.


7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to temporarily

pause and allow other threads to execute.

15.public void suspend(): is used to suspend the thread(depricated).


16.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or user thread.
20.public boolean isInterrupted(): tests if the thread has been interrupted.
21.public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended t
executed by a thread. Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

1) Java Thread Example by extending Thread class

FileName: Multi.java

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:

thread is running...
2)Java Thread Example by implementing Runnable interface
FileName: Multi3.java

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:

thread is running...

3) Using the Thread Class: Thread(String Name)


FileName: MyThread1.java

public class MyThread1


{
public static void main(String argvs[])
{
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}

Output:

My first thread
4) Using the Thread Class: Thread(Runnable r, String name)
FileName: MyThread2.java

public class MyThread2 implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}

Output:

My new thread
Now the thread is running ...
Java Synchronization
Synchronization is a process of handling resource accessibility by multiple
thread requests. The main purpose of synchronization is to avoid thread
interference. At times when more than one thread try to access a shared
resource, we need to ensure that resource will be used by only one thread at a
time. The process by which this is achieved is called synchronization. The
synchronization keyword in java creates a block of code referred to as critical
section.
class First
{
synchronizedpublicvoid display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
publicvoid run()
{
fobj.display(msg);
}
}
publicclass JavaSynchronize {

publicstaticvoid main(String[] args)


{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second(fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}

Output
[welcome]
[programmer]
[new]
Difference between synchronized keyword and
synchronized block
When we use synchronized keyword with a method, it acquires a lock in the
object for the whole method. It means that no other thread can use any
synchronized method until the current thread, which has invoked it's
synchronized method, has finished its execution.
synchronized block acquires a lock in the object only between parentheses after
the synchronized keyword. This means that no other thread can acquire a lock
on the locked object until the synchronized block exits. But other threads can
access the rest of the code of the method.

Ex:Synchronized block
class First
{
publicvoid display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println( e);
}
System.out.println ("]");
}
}
class Second extends Thread
{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
publicvoid run()
{
synchronized(fobj)
{
fobj.display(msg);
}
}
}
publicclass JavaSynchronize {
publicstaticvoid main(String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second(fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}

Output
[welcome]
[programmer]
[new]
Interthread Communication: Itis all about allowing

synchronized threads to communicate with each other. Cooperation (Inter-


thread communication) is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods
of Object class:
 wait()
 notify()
 notifyAll()
wait() The wait() method causes current thread to release the lock and wait
until either another thread invokes the notify() method or the notifyAll() method
for this object, or a specified amount of time has elapsed.The current thread
must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
notify() The notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them is chosen
to be awakened.
notifyAll() wakes up all the thread that called wait() on same object.

Difference between wait() and sleep()


wait() sleep()
called from synchronised block no such requirement
monitor is released monitor is not released
gets awake when notify() or does not get awake when notify() or
notifyAll() method is called. notifyAll() method is called
not a static method static method
sleep() method is simply used to put your
wait() is generaly used on condition
thread on sleep.
Program based on Inter thread communication

class Customer extends Thread


{
int amount=10000;
synchronizedvoid withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronizedvoid deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Interthread
{
publicstaticvoid main(String args[]){
Customer c=new Customer();
new Thread(){
publicvoid run(){c.withdraw(15000);}
}.start();
new Thread(){
publicvoid run(){c.deposit(10000);}
}.start();
}
}

Output
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
Java join() method
The join() method in Java is provided by the java.lang.Thread class that permits
one thread to wait until the other thread to finish its execution. Suppose th be
the object the class Thread whose thread is doing its execution currently, then
the th.join(); statement ensures that th is finished before the program does the
execution of the next statement.

Ex:
class CustomThread implements Runnable {
publicvoid run() {
System.out.println(Thread.currentThread().getName() + " started.");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println(Thread.currentThread().getName() + " exited.");
}
}
publicclass ThreadJoin {
publicstaticvoid main(String[] args) throws InterruptedException {
CustomThread th=new CustomThread();
Thread t1 = new Thread( th, "Thread-1");
t1.start();
t1.join();
Thread t2 = new Thread( new CustomThread(), "Thread-2");
t2.start();
t2.join();
Thread t3 = new Thread( new CustomThread(), "Thread-3");
t3.start();
}
}
Output

Thread-1 started.
Thread-1 exited.
Thread-2 started.
Thread-2 exited.
Thread-3 started.
Thread-3 exited.

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and
10. In most cases, the thread scheduler 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. Note that not
only JVM a Java programmer can also assign the priorities of a thread explicitly
in a Java program.

Setter & Getter Method of Thread Priority


public final int getPriority(): The java.lang.Thread.getPriority() method
returns the priority of the given thread.
public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign the priority of the thread
to newPriority. The method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " +
Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().g
etPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
}
}
Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Local inner class

A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block.
public class Main
{
private int data=30;//instance variable
void display()
{
class Local
{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[])
{
Main obj=new Main();
obj.display();
}
}
Java Member Inner Class
In this example, we are creating a msg() method in the member inner class that
is accessing the private data member of the outer class.

public class Main


{
private int data=30;
class Inner{
void msg()
{System.out.println("data is "+data);}
}
public static void main(String args[])
{
Main obj=new Main();
Main.Inner in=obj.new Inner();
in.msg();
}
}
Java Anonymous inner class
Java anonymous inner class is an inner class without a name and for which only a single object is
created. In simple words, a class that has no name is known as an anonymous inner class in Java.
It should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways.

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


TestAnonymousInner.java

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Output:

nice fruits
Java anonymous inner class example using interface
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}

Output:

nice fruits
Java Abstract Window Toolkit(AWT)
AWT stands for Abstract Window Toolkit, developed by Sun Microsystems in
1995 and is a platform-dependent API used to develop Graphical User Interface
or window-based applications in Java. 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 an improved GUI API
that extends the AWT.

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. 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.

Window:The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.

Panel:The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components.

Frame:The Frame is the container that contain title bar and border and can
have menu bars. It can have other components like button, text field, scrollbar
etc. Frame is most widely used container while developing an AWT application.

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.*;
publicclass AWTFrame
{
AWTFrame()
{
Frame f=new Frame();
f.setSize(400, 500); //setting size.
f.setTitle("Welcome to AWT"); //setting title.
f.setLayout(null); //set default layout for frame.
f.setVisible(true);
f. setBackground(Color.yellow);
}
publicstaticvoid main(String args[])
{
AWTFrame af = new AWTFrame();
}
}
Creating Frame window by extending Frame class
import java.awt.*;
publicclassAWTFrameextends Frame
{
AWTFrame()
{
setSize(400, 500); //setting size.
setTitle("Welcome to AWT"); //setting title.
setLayout(null); //set default layout for frame.
setVisible(true);
setBackground(Color.yellow);
}
publicstaticvoid main(String args[])
{
AWTFrame af = new AWTFrame();
}
}

NOTE:

1. While creating a frame following two attributes are must for visibility of
the frame:

o setSize(int width, int height);

o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then
you need to add it to the frame by using the method - add(Component's
Object);

3. You can add the following method also for resizing the frame -
setResizable(true);
Delegation Event Model in Java

The Delegation Event model is defined to handle events in GUI programming


languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system. whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an
event that is mapped to a code to respond to functionality to the user. This is
known as event handling.
The Event model is based on two things, i.e., Event Source and Event Listeners.
 Event Source means any object which creates the message or event.
 Event Listeners are the object which receives the message or event.

Delegation Event Model in Java, the Delegation event model is based upon
Event Source, Event Listeners, and Event Objects.
 Event Source is the class used to broadcast the events.
 Event Listeners are the classes that receive notifications of events.
 Event Object is the class object which describes the event.
In the Delegation model, a source generates an event and forwards it to one or
more listeners, where the listener waits until they receive an event. Once the
listener gets the event, it is processed by the listener, and then they return it. The
UI elements can delegate an event's processing to a separate function.

The essential advantage of the Delegation Event Model is that the application
logic is completely separated from the interface logic.
Registering the Source With Listener in Delegation Event Model
The different Classes provide different registration methods.
Syntax:

addTypeListener()
where Type represents the Type of event.

For Example: For KeyEvent we use addKeyListener() to register, For


ActionEvent we use addActionListener() to register.

Handling Mouse Events

MouseListener and MouseMotionListener is an interface in java.awt.event


package .
Mouse events are of two types. MouseListener handles the events when the
mouse is not in motion. While MouseMotionListener handles the events when
mouse is in motion.There are five types of events that MouseListener can
generate. There are five abstract functions that represent these five events.
The abstract functions are :
1. void mouseReleased(MouseEvent e) : Mouse key is released
2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate. There
are two abstract functions that represent these five events.
The abstract functions are :
1. void mouseDragged(MouseEvent e) : Invoked when a mouse
button is pressed in the component and dragged. Events are passed
until the user releases the mouse button.
2. void mouseMoved(MouseEvent e) : invoked when the mouse cursor
is moved from one point to another within the component, without
pressing any mouse buttons.

 MouseListener program:
import java.awt.*;
import java.awt.event.*;
public class AWTMouseEvent extends Frame implements MouseListener
{
Label l;
AWTMouseEvent()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}

public static void main(String[] args)


{
new AWTMouseEvent();
}
}
MouseMotionListener program

import java.awt.*;

import java.awt.event.*;

public class MouseMotionEvent extends Frame implements


MouseMotionListener

MouseMotionEvent()

addMouseMotionListener(this);

setSize(300,300);

setLayout(null);

setVisible(true);

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent e)

dispose();

});

public void mouseDragged(MouseEvent e) {

Graphics g=getGraphics();

g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);

public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {

new MouseMotionEvent();

Keyboard Events
Java KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is
notified against KeyEvent. The KeyListener interface is found in java.awt.event
package, and it has three methods.

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

Sr. Method name Description


no.

1. public abstract void keyPressed It is invoked when a key has been


(KeyEvent e); pressed.

2. public abstract void keyReleased It is invoked when a key has been


(KeyEvent e); released.

3. public abstract void keyTyped It is invoked when a key has been


(KeyEvent e); type
//Keyboard Events Program
import java.awt.*;
import java.awt.event.*;
publicclassKeyboardEventextends Frame implements KeyListener
{
Label l;
TextArea txtarea;
KeyboardEvent()
{
l = new Label();
l.setBounds (20, 50, 100, 20);
txtarea = new TextArea();
txtarea.setBounds (20, 80, 300, 300);
txtarea.addKeyListener(this);
add(l);
add(txtarea);
setSize (400, 400);
setLayout (null);
setVisible (true);
addWindowListener(new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
dispose();
}
});
}
publicvoid keyPressed (KeyEvent e)
{
l.setText ("Key Pressed");
}
publicvoid keyReleased (KeyEvent e)
{
l.setText ("Key Released");
}
publicvoid keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
publicstaticvoid main(String[] args) {
new KeyboardEvent();
}
}
AWT program
import java.awt.*;
import java.awt.event.*;

classAWTextends Frame implements ActionListener


{
Label lsname, lsrollno, lsclass, lgander, lsbg, lsmob, lsadrs;
CheckboxGroup gander;
Checkbox male, female, trainpass;
Choice csclass;
TextField tfsname, tfsrollno, tfsmob;
TextArea tasadrs;
Button submit;
TextArea display_details;
AWT()
{
lsname = new Label("Name : ");
lsrollno = new Label("Roll No : ");
lsclass = new Label("Class : ");
lgander = new Label("Gander : ");
lsbg = new Label("Blood Group : ");
lsmob = new Label("Mobile : ");
lsadrs = new Label("Address : ");
gander = new CheckboxGroup();
male = new Checkbox("Male", gander, false);
female = new Checkbox("Female", gander, false);
trainpass = new Checkbox("Apply For Train Concession");
csclass = new Choice();
csclass.add("BSc IT");
csclass.add("BSc CS");
csclass.add("BCA");
csclass.add("MSc IT");
csclass.add("MSc CS");
csclass.add("MCA");
tfsname = new TextField();
tfsrollno = new TextField();
tfsmob = new TextField();
tasadrs = new TextArea("", 2 , 100 ,
TextArea.SCROLLBARS_NONE);
submit = new Button("Submit");
display_details = new TextArea("", 2 , 100 ,
TextArea.SCROLLBARS_NONE);
display_details.setEditable(false);
lsname.setBounds(10, 30, 50, 20);
tfsname.setBounds(70, 30, 150, 20);
lsrollno.setBounds(240, 30, 50, 20);
tfsrollno.setBounds(300, 30, 150, 20);
lsclass.setBounds(10, 60, 50, 20);
csclass.setBounds(70, 60, 150, 20);
lgander.setBounds(240, 60, 50, 20);
male.setBounds(300, 60, 50, 20);
female.setBounds(360, 60, 50, 20);
lsmob.setBounds(10, 90, 50, 20);
tfsmob.setBounds(70, 90, 150, 20);
trainpass.setBounds(240, 90, 150, 20);
lsadrs.setBounds(10, 120, 50, 20);
tasadrs.setBounds(70, 120, 380, 70);
submit.setBounds(10, 200, 440, 30);
display_details.setBounds(10, 240, 440, 130);
add(lsname);
add(lsrollno);
add(lsclass);
add(lgander);
add(lsbg);
add(lsadrs);
add(lsmob);
add(male);
add(female);
add(csclass);
add(tfsname);
add(tfsrollno);
add(tasadrs);
add(tfsmob);
add(trainpass);
add(submit);
add(display_details);
submit.addActionListener(this);
setTitle("Students Details");
setSize(460,390);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
dispose();
}
});
}

publicvoid actionPerformed(ActionEvent e)
{
if(e.getSource()==submit)
{
String tp = trainpass.getState() ? "Applied for Train
Concession" : "Not Applied for Train Concession";

String sdetails = " ***** Students Details *****n Name : "


+ tfsname.getText() + "n Roll No. :" + tfsrollno.getText() + "n Class : " +
csclass.getSelectedItem() + "n Gander : " +
gander.getSelectedCheckbox().getLabel() + "n Mobile : " + tfsmob.getText() +
"n Train Pass : " + tp + "n Address : " + tasadrs.getText();

display_details.setText(sdetails);
}
}

publicstaticvoid main(String[] args)


{
newAWT();
}
}

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If

you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.
java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener
Program on Adapter class:
import java.awt.*;
import java.awt.event.*;
publicclass MouseAdClass extends MouseAdapter
{
Label l;
Frame f;
MouseAdClass()
{
f=new Frame();
f.addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
f.add(l);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
f.dispose();
}
});
}
publicvoid mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
publicvoid mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}

}
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight


components.

The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components Java swing components are platform-


are platform-dependent. independent.

2) AWT components Swing components are lightweight.


are heavyweight.

3) AWT doesn't support Swing supports pluggable look and feel.


pluggable look and feel.

4) AWT provides less Swing provides more powerful


components than Swing. components such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
Hierarchy of Java Swing classes

Swing Program
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class SwingProgram extends JFrame
{
JFrame f;
JLabel lsname;
JTextField tfsname;
JCheckBox jcb1,jcb2,jcb3;
JTextArea txadrs;
JRadioButton r1,r2,r3;
JButton sub;
JToggleButton button;
JPanel panel;
JComboBox cou;
JScrollPane spane;
JDialog d;
SwingProgram()
{
//Label creation
lsname= new JLabel("Name : ");
lsname.setBounds(50,100,100, 40 );
//Textbox creation
tfsname= new JTextField();
tfsname.setBounds(130,100,150, 40);
//Checkbox creation
jcb1 = new JCheckBox("Singing");
jcb2 = new JCheckBox("Dancing");
jcb3 = new JCheckBox("Reading");
jcb1.setBounds(60,150,150, 40);
jcb2.setBounds(60,170,150, 60);
jcb3.setBounds(60,190,150, 100);
//Radiobutton creation
r1=new JRadioButton("Male");
r2=new JRadioButton("Female");
r1.setBounds(60,220,100,30);
r2.setBounds(60,250,100,30);
//TextArea creation
txadrs=new JTextArea();
txadrs.setBounds(60,300,150, 100);
//ToggleButton creation
button=new JToggleButton();
button.setBounds(10,50,100, 50);
//Listbox creation
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
JList<String> list = new JList<>(l1);
list.setBounds(200,200, 75,75);
//Combobox creation
String dept[]={"BBA","BCA","MBA","MCA"};
cou=new JComboBox(dept);
cou.setBounds(250,400,100,30);
//Panel creation & place button
panel=new JPanel();
panel.setBounds(400,80,200,200);
sub=new JButton("Submit");
sub.setBounds(420,100, 100,100);
panel.add(sub);
panel.setBackground(Color.yellow);
//Dialog box creation
d=new JDialog(f,"Dialog example",true);
JButton b=new JButton("OK");
d.add(b);
d.setSize(400,400);
d.setVisible(true);
add(cou);
add(list);
add(txadrs);
add(r1);
add(r2);
add(jcb1);
add(jcb2);
add(jcb3);
add(lsname);
add(tfsname);
add(button);
add(panel);
setTitle("Students Details");
setSize(700,650);
setLayout(null);
setVisible(true);
}

public static void main(String[] args)


{
new SwingProgram();
}
}
Java Application Vs. Java Applet

Parameters Java Application Java Applet

Meaning A Java Application also known as The Java applet works on the client
application program is a type of side, and runs on the browser and
program that independently makes use of another application
executes on the computer. program so that we can execute it.

Requirement of Its execution starts with the It does not require the use of any
main( ) method main( ) method only. The use of main() method. Java applet
the main( ) is mandatory. initializes through init( ) method.

Execution It cannot run independently, but It cannot start independently but


requires JRE to run. requires APIs for use (Example. APIs
like Web API).

Installation We need to install the Java Java applet does not need to be
application first and obviously on pre-installed.
the local computer.

Connectivity It is possible to establish It cannot establish connection to


with server connections with other servers. other servers.

Operation It performs read and write tasks It cannot run the applications on
on a variety of files located on a any local computer.
local computer.

File access It can easily access a file or data It cannot access the file or data
available on a computer system found on any local system or
or device. computer.

Security Java applications are pretty Java applets are less reliable. So,
trusted, and thus, come with no they need to be safe.
security concerns.
Java Applet
Applet is a special type of java 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:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.

Hierarchy of Applet
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

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.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).
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{
public void paint(Graphics g){
g.drawString("welcome",150,150);
} }
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java.
Now Html file is not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
} }
/*
<applet code="First.class" width="300" height="300">
</applet> */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

You might also like