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

java assignment bca

Javascript assignment bca

Uploaded by

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

java assignment bca

Javascript assignment bca

Uploaded by

Prathamesh Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Object Oriented Programming (OOPs) Concept in Java

As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming, they use
objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing
tasks assigned by you. Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.

OOPS Concepts in Java

Let us discuss prerequisites by polishing concepts of method declaration and message passing. Starting off with the method
declaration, it consists of six components:

Access Modifier:

Defines the access type of the method i.e. from where it can be accessed in your application. In Java, there are 4 types of access
specifiers:
public:
Accessible in all classes in your application.
protected:
Accessible within the package in which it is defined and in its subclass(es) (including subclasses declared outside the package).
private:
Accessible only within the class in which it is defined.
default (declared/defined without using any modifier):
Accessible within the same class and package within which its class is defined.

The return type:


The data type of the value returned by the method or void if it does not return a value.

Method Name:
The rules for field names apply to method names as well, but the convention is a little different.

Parameter list:
Comma-separated list of the input parameters that are defined, preceded by their data type, within the enclosed parentheses.
If there are no parameters, you must use empty parentheses ().

Exception list:
The exceptions you expect the method to throw. You can specify these exception(s).
Method body: It is the block of code, enclosed between braces, that you need to execute to perform your intended operations.

Message Passing:
Objects communicate with one another by sending and receiving information to each other. A message for an object is a
request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired
results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.

OOPS concepts are as follows:

Class
Object
Method and method passing

Pillars of OOPs
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Runtime polymorphism

A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods
that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. This includes classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:

Modifiers:
A class can be public or have default access (Refer to this for details).

Class name: The class name should begin with the initial letter capitalized by convention.

Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.

Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements.
A class can implement more than one interface.

Body: The class body is surrounded by braces, { }.


An object is a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. The objects are what perform your code, they are the part of your
code visible to the viewer/user. An object mainly consists of:

State: It is represented by the attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.

Identity: It is a unique name given to an object that enables it to interact with other objects.

Method: A method is a collection of statements that perform some specific task and return the result to the caller. A method
can perform some specific task without returning anything. Methods allow us to reuse the code without retyping it, which is
why they are considered time savers. In Java, every method must be part of some class, which is different from languages like C,
C++, and Python.

class and objects one simple java program :

public class GFG {

static String Employee_name;


static float Employee_salary;

static void set(String n, float p) {


Employee_name = n;
Employee_salary = p;
}

static void get() {


System.out.println("Employee name is: " +Employee_name );
System.out.println("Employee CTC is: " + Employee_salary);
}

public static void main(String args[]) {


GFG.set("Rathod Avinash", 10000.0f);
GFG.get();
}
}

Output
Employee name is: Rathod Avinash
Employee CTC is: 10000.0
Let us now discuss the 4 pillars of OOPs:

Pillar 1: Abstraction

Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or non-
essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object, ignoring the
irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in
classifying/grouping the object.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the car
speed or applying brakes will stop the car, but he does not know how on pressing the accelerator, the speed is actually
increasing. He does not know about the inner mechanism of the car or the implementation of the accelerators, brakes etc. in
the car. This is what abstraction is.

In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

The abstract method contains only method declaration but not implementation.

Demonstration of Abstract class

//abstract class
abstract class GFG{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}

Pillar 2: Encapsulation

It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code and the data it
manipulates. Another way to think about encapsulation is that it is a protective shield that prevents the data from being
accessed by the code outside this shield.

Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be accessed only
through any member function of the class in which they are declared.
In encapsulation, the data in a class is hidden from other classes, which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public methods in the class to set
and get the values of the variables.

Demonstration of Encapsulation:

//Encapsulation using private modifier

//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}

Pillar 3: Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is
allowed to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword.
Inheritance is also known as “is-a” relationship.

Let us discuss some frequently used important terminologies:

Superclass: The class whose features are inherited is known as superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class). The
subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Demonstration of Inheritance :

//base class or parent class or super class


class A{
//parent class methods
void method1(){}
void method2(){}
}

//derived class or child class or base class


class B extends A{ //Inherits parent class methods
//child class methods
void method3(){}
void method4(){}
}

Pillar 4: Polymorphism

It refers to the ability of object-oriented programming languages to differentiate between entities with the same name
efficiently. This is done by Java with the help of the signature and declaration of these entities. The ability to appear in many
forms is called polymorphism.

E.g.

sleep(1000) //millis

sleep(1000,2000) //millis,nanos

Note: Polymorphism in Java is mainly of 2 types:

Overloading
Overriding
Example

// Java program to Demonstrate Polymorphism

// This class will contain


// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {

// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output
30
60
31.0

Comparison Index C++ Java

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is
programming. widely used in Windows-based, web-based, enterprise,
and mobile applications.

Design Goal C++ was designed for systems and Java was designed and created as an interpreter for
applications programming. It was an printing systems but later extended as a support
extension of the C programming network computing. It was designed to be easy to use
language. and accessible to a broader audience.

Goto C++ supports the goto statement. Java doesn't support the goto statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance through
inheritance class. It can be achieved by using interfaces in java.

Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading

Pointers C++ supports pointers. You can write a Java supports pointer internally. However, you can't
pointer program in C++. write the pointer program in java. It means java has
restricted pointer support in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter. Java source
Interpreter compiled and run using the compiler code is converted into bytecode at compilation time.
which converts source code into The interpreter executes this bytecode at runtime and
machine code so, C++ is platform produces output. Java is interpreted that is why it is
dependent. platform-independent.

Call by Value and C++ supports both call by value and Java supports call by value only. There is no call by
Call by reference call by reference. reference in java.

Structure and C++ supports structures and unions. Java doesn't support structures and unions.
Union

Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party libraries
for thread support.

Documentation C++ doesn't support documentation Java supports documentation comment (/** ... */) to
comment comments. create documentation for java source code.

Virtual Keyword C++ supports virtual keyword so that Java has no virtual keyword. We can override all non-
we can decide whether or not to static methods by default. In other words, non-static
override a function. methods are virtual by default.

unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that
shift >>> fills zero at the top for the negative numbers. For
positive numbers, it works same like >> operator.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented language. Java is also an object-oriented language. However,


everything (except fundamental types) is an object in
History of Java

Java Version History


The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced technology
for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc.
However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s.
James Gosling - founder of java
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun
engineers called Green Team.
ADVERTISEMENT

2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "Oak"?


Java History from Oak to Java
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?


7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.
ADVERTISEMENT

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name
was chosen by James Gosling while having a cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in
1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to
the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java

Features of Java

The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this language.
The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is
a simple programming language because:

Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing
some rules.

Basic concepts of OOPs are:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Platform Independent
Java is platform independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:

Runtime Environment
API(Application Programming Interface)
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. 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
Java Programs run inside a virtual machine sandbox
Robust
The English mining of Robust is strong. Java is robust because:

It uses strong memory management.

There is a lack of pointers that avoids security problems.

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.
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. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it 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++.
ADVERTISEMENT

Java supports dynamic compilation and automatic memory management (garbage collection).

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:

Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
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.

Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to
declare variable's type and name.

There are 8 types of primitive data types:

boolean data type


byte data type
char data type
short data type
int data type
long data type
float data type
double data type

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track
true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

Boolean one = false


Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a
byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example:

byte a = 10, byte b = -20


Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.

Example:

short s = 10000, short r = -5000


Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value
is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Example:

int a = 100000, int b = -200000


Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.

Example:

long a = 100000L, long b = -200000L


Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use a
float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

Example:

float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is
generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:

double d1 = 12.3
Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.

Example:

char letterA = 'A'

Difference between JDK, JRE, and JVM

We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the brief overview of
JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see the differences
between the JDK, JRE, and JVM.

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
Backward Skip 10sPlay VideoForward Skip 10s

The JVM performs the following main tasks:


Loads code
Verifies code
Executes code
Provides runtime environment
More Details.

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
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:

Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |=


<<= >>= >>>=

Java Unary Operator


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

incrementing/decrementing a value by one


negating an expression
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
}}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:

21
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
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:

40
80
80
240

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.

Java Right Shift Operator Example


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
}}
Output:

2
5
2

Java Shift Operator Example:


>> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && 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
}}
Output:

false
False

Java AND Operator Example: Logical && vs Bitwise &


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);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Output:

false
10
false
11

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
//|| vs |
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
}}
Output:

true
true
true
10
true
11

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
Another Example:

public class OperatorExample{


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

Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its
left.

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);
}}
Output:

14
16

Java Assignment Operator Example

public class OperatorExample{


public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:

13
9
18
9

Java Assignment Operator Example:


Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:

Compile time error


After type cast:

public class OperatorExample{


public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20

Java Keywords (short note)

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.

List of Java Keywords


A list of Java keywords or reserved words are given below:

abstract:
Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It
can have abstract and non-abstract methods.

boolean:
Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.

break:
Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified
conditions.

byte:
Java byte keyword is used to declare a variable that can hold 8-bit data values.

case:
Java case keyword is used with the switch statements to mark blocks of text.

catch:
Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.

char:
Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters

class:
Java class keyword is used to declare a class.

continue:
Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code
at the specified condition.

default:
Java default keyword is used to specify the default block of code in a switch statement.

do:
Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.

double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.

else: Java else keyword is used to indicate the alternative branches in an if statement.

enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.

extends: Java extends keyword is used to indicate that a class is derived from another class or interface.

final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a

variable. It is used to restrict the user from updating the value of the variable.
finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.

float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.

for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.

if: Java if keyword tests the condition. It executes the if block if the condition is true.

implements: Java implements keyword is used to implement an interface.

import: Java import keyword makes classes and interfaces available and accessible to the current source code.

instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an
interface.

int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.

interface: Java interface keyword is used to declare an interface. It can have only abstract methods.

long: Java long keyword is used to declare a variable that can hold a 64-bit integer.

native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).

new: Java new keyword is used to create new objects.


null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.

package: Java package keyword is used to declare a Java package that includes the classes.

private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the
class in which it is declared.

protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but
through inheritance only. It can't be applied with the class.

public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest
scope among all other modifiers.

return: Java return keyword is used to return from a method when its execution is complete.

short: Java short keyword is used to declare a variable that can hold a 16-bit integer.

static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly
used for memory management.

strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.

super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the
immediate parent class method.

switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement
tests the equality of a variable against multiple values.

synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
this: Java this keyword can be used to refer the current object in a method or constructor.

throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly
used to throw custom exceptions. It is followed by an instance.

throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.

transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either
catch or finally block.

void: Java void keyword is used to specify that a method does not have a return value.

volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of
iteration is not fixed, it is recommended to use the while loop.

Java Control Statements | Control Flow in Java

Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which
they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called
control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

Decision Making statements


if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements
evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are
two types of decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific
condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-
statements given below.

Backward Skip 10s

Play Video

Forward Skip 10s

Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let's understand the if-statements one by one.

1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the
program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.

Student.java

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20

2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is
executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is
the chain of if-else statements that create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output:

Delhi

4) Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:

Delhi

5) Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead
of if-else-if statements. It also enhances the readability of the program.

Points to be noted about switch statement:

The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of expression. It is optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it
will also be a constant value.
The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.

Student.java

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:

While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it
will also be a constant value. The switch permits only int, string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However,
loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition
checking time.

for loop
while loop
do-while loop
Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to
execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}
The flow chart for the for-loop is given below.

Control Flow in Java


Consider the following example to understand the proper functioning of the for loop in java.

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need
to update the loop variable. The syntax to use the for-each loop in java is given below.

for(data_type var : array_name/collection_name){


//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop

The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of
iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement
doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then
the loop body will be executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.

Control Flow in Java


Consider the following example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of
iteration is not known and we have to execute the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is
given below.

do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.

Control Flow in Java


Consider the following example to understand the functioning of the do-while loop in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements
transfer the execution control to the other part of the program. There are two types of jump statements in Java, i.e., break and
continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch
statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop


Calculation.java

public class Calculation {

public static void main(String[] args) {


// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}

}
}

}
Output:

0
1
2
3
4
5

Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and
jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in Java.

public class ContinueExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:

0
1
2
3
5
1
2
3
5
2
3
5

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.

The static can be:

Variable (also known as a class variable)


Method (also known as a class method)
Block
Nested class
Static in Java
1) Java static variable

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

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.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Backward Skip 10s

Play Video

Forward Skip 10s

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is
created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to
the common property of all objects. If we make it static, this field will get the memory only once.

Java static property is shared to all objects.


Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

Output:

111 Karan ITS


222 Aryan ITS

Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance
variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is
incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:
1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static
variable, it will retain its value.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
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[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Test it Now
Output:

1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

Another example of a static method that performs a normal calculation


//Java 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

There are two main restrictions for the static method. They are:

The static method can not use non static data member or call non-static method directly.
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);
}
}
Test it Now
Output:Compile Time 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


Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
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

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

variable
Method
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. We will have detailed learning of these. Let's first learn the basics of final keyword.

final keyword in java

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:
Compile Time Error

2) Java final method

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

Example of final method


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

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the
access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

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.

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.

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.
1) Private
2)
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are
accessing these private members from outside the class, so there is a compile-time error.

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
}
}
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:

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
}
}
Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot
be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and
public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A
class is not public, so it cannot be accessed from outside the package.

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

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed
from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.

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

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an
important part of OOPs (Object Oriented programming system).

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

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


For Code Reusability.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child
class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a
parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is
to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
Java Inheritance Example

Inheritance in Java

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);
}
}

Programmer salary is:40000.0


Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

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. We will learn about interfaces later.

Types of inheritance in Java

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

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Multiple inheritance in Java

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.

File: TestInheritance.java

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.

File: TestInheritance2.java

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.

File: TestInheritance3.java

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…

Multithreading in Java

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to
achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be
achieved in two ways:

Process-based Multitasking (Multiprocessing)


Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


Each process has an address in memory. In other words, each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

Threads share the same address space.


A thread is lightweight.
Cost of communication between the thread is low.
Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated

Explanation of Different Thread States

New:
Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet
and thus has not begun its execution.

Active:
When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states
within it: one is runnable, and the other is running.

Runnable:
A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be
ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for
a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so
that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to
run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change
in the state of a thread is from runnable to running and again back to runnable.

Blocked or Waiting:
Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the
waiting state.

For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the
other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use
the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus
never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread
then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which
thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.

Timed Waiting:
Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is
not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific
span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution
from when it has left earlier.

Terminated:
A thread reaches the termination state because of the following reasons:

When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one
can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States

In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java
provides the constants ENUM to represent the state of a thread. These constants are:

public static final Thread.State NEW


It represents the first state of a thread that is the NEW state.

public static final Thread.State RUNNABLE


It represents the runnable state.It means a thread is waiting in the queue to run.

public static final Thread.State BLOCKED


It represents the blocked state. In this state, the thread is waiting to acquire a lock.

public static final Thread.State WAITING


It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or Thread.join() method
with no timeout. A thread in the waiting state is waiting for another thread to complete its task.

public static final Thread.State TIMED_WAITING


It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint. Waiting
has no time constraint, whereas timed waiting has the time constraint. A thread invoking the following method reaches the
timed waiting state.

sleep
join with timeout
wait with timeout
parkUntil
parkNanos
public static final Thread.State TERMINATED
It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its execution.

Java Program for Demonstrating Thread States

The following Java program shows some of the states of a thread defined above.

FileName: ThreadState.java
// ABC class implements the interface Runnable
class ABC implements Runnable
{
public void run()
{

// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}

System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ ThreadState.t1.getState());

// try-catch block
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}

// ThreadState class implements the interface Runnable


public class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;

// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();
t1 = new Thread(obj);

// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());

// invoking the start() method on


// the thread t1
t1.start();

// thread t1 is moved to the Runnable state


System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
}
public void run()
{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);

// thread t2 is created and is currently in the NEW state.


System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
t2.start();

// thread t2 is moved to the runnable state


System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());

// try-catch block for the smooth flow of the program


try
{
// moving the thread t1 to the state timed waiting
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}

System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );

// try-catch block for the smooth flow of the program


try
{
// waiting for thread t2 to complete its execution
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());
}

}
Output:

The state of thread t1 after spawning it - NEW


The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED
Explanation: Whenever we spawn a new thread, that thread attains the new state. When the method start() is invoked on a
thread, the thread scheduler moves that thread to the runnable state. Whenever the join() method is invoked on any thread
instance, the current thread executing that statement has to wait for this thread to finish its execution, i.e., move that thread to
the terminated state. Therefore, before the final print statement is printed on the console, the program invokes the method
join() on thread t2, making the thread t1 wait while the thread t2 finishes its execution and thus, the thread t2 get to the
terminated or dead state. Thread t1 goes to the waiting state because it is waiting for thread t2 to finish it's execution as it has
invoked the method join() on thread t2.
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.

Here, we will have the detailed learning of creating and using user-defined packages.

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.

package in java

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case
of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current
folder.

How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;
import package.classname;
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

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.
sequence of package

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String,
Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.


Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple

Output:
Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For example:

how to put class file in another package


//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:
e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.

e:\sources> set classpath=c:\classes;.;


e:\sources> java mypack.Simple

Output:
Welcome to package

Ways to load the class files or jar files

There are two ways to load the class files temporary and permanent.

Temporary
By setting the classpath in the command prompt
By -classpath switch

Permanent
By setting the classpath in the environment variables
By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the
application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.


In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as 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 need to handle exceptions. Let's consider 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 a Java program and an exception occurs at statement 5; the rest of the code will not be
executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the
statements 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 inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions namely:

Checked Exception
Unchecked Exception
Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

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 necessary 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 specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

JavaExceptionExample.java

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...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

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.

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.

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

3) A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a
string variable that has characters; converting this variable into digit will cause NumberFormatException.

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

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

User-defined Exception in Java

An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the
program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own
Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize
the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.

For example, MyException in the below code extends the Exception class.

Why use custom exceptions?


Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes
need to create custom exceptions.

Following are a few of the reasons to use custom exceptions:

To catch and provide specific treatment to a subset of existing Java exceptions.


Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users
or the developers to understand the exact problem.
In order to create a custom exception, we need to extend the Exception class that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()”
function on the object created.

// A Class that represents use-defined exception

class MyException extends Exception {


public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}

Output

Caught
GeeksGeeks

In the above code, the constructor of MyException requires a string as its argument. The string is passed to the parent class
Exception’s constructor using super(). The constructor of the Exception class can also be called without a parameter and the call
to super is not mandatory.

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT
is heavy weight i.e. its components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.

Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like
TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different
platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each
component as shown in above diagram. In order to place every component in a particular position on a screen, we need to add
them to a container.

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that
extends Container class are known as container such as Frame, Dialog and Panel.

It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the
layout of components.

Note: A container itself is a component (see the above diagram), therefore we can add a container inside container.
Types of containers:

There are four types of containers in Java AWT:

Window
Panel
Frame
Dialog

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.

Useful Methods of Component Class


Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager Defines the layout manager for the component.
m)

public void setVisible(boolean status) Changes the visibility of the component, by default
false.

Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.

By extending Frame class (inheritance)


By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.

AWTExample1.java

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets the position of the awt
button.

Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating a TextField, Label and
Button component on the Frame.

AWTExample2.java

// importing Java AWT class


import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
// adding components into frame
f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

Output:

JLabel (short note)

The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The
text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.

public class JLabel extends JComponent implements SwingConstants, Accessible

Java JButton

The JButton class is used to create a labeled button that has platform independent implementation. The application result in
some action when the button is pushed. It inherits AbstractButton class.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible

Java String

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.
For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:

String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes
implement it. It means, we can create strings in Java by using these three classes.

CharSequence in Java
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For
mutable strings, you can use StringBuffer and StringBuilder classes.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The
java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:

By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:

String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a
reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in
the pool. For example:

String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool,
it will not create a new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in
the string constant pool. The variable s will refer to the object in a heap (non-pool).

Java String Example

StringExample.java

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:

java
strings
Example

The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using
println() method.

You might also like