II-i-oops-lecture Notes Java (3)
II-i-oops-lecture Notes Java (3)
Introduction: Introduction to Object Oriented Programming, The History and Evolution of Java,
Introduction to Classes, Objects, Methods, Constructors, this keyword, Garbage Collection, Data Types,
Variables, Type Conversion and Casting, Arrays, Operators, Control Statements, Method Overloading,
Constructor Overloading, Parameter Passing, Recursion, String Class and String handling methods.
History of Java:-
Java is a popular object-oriented programming language, developed by sun micro systems of USA in
1991(which has since been acquired by oracle). Originally it was called as oak. The developers of java
are James Gosling and his team (Patrick naughton, Chris warth, ed frank, and mike Sheridan).
This language was renamed as “java” in 1995. Java was publicly announced in 1995 and now more than
3 billion devices run java
The primary motivation of java was need for a platform independent language which can be used to
create software to be embedded in different consumer electronic devices like remote controls,
microwave ovens etc.
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.
Principles
There were five primary goals in the creation of the Java language:
Editions:
Java Standard Edition: - Java Standard Edition, also known as J2SE / JSE is the
java platform (Any hardware or software environment in which a program runs is known as a
platform.) for developing client-side application which runs on desktop, and applets which run on
web browser.
Core Java + JDBC is the part of Java Standard Edition (J2SE / JSE).
Java Enterprise Edition : - Java Enterprise Edition, also known as J2EE / JEE is the java platform
built on the top of Java SE , which is used to develop enterprise- oriented server applications.(Server
side applications include servlets, which are java programs that are similar to applets but run on a
server rather than a client.)
Servlets + JSPs are the part of Java Enterprise Edition.
Java Micro Edition: - Java Micro Edition, also known as J2ME / JME is the java platform
which is also built on Java SE. It is mainly used to develop mobile applications.
Java FX: - Java FX, also known as Java Flex is used to develop rich internet applications. It
uses light-weight user interface API.
Characteristics of OOP:
Emphasis on data.
Programs are divided into what are known as methods.
Data structures are designed such that they characterize the objects.
Methods that operate on the data of an object are tied together.
Data is hidden.
Objects can communicate with each other through methods.
Reusability.
Follows bottom-up approach in program design
OOP concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object:
Class:
A class can also be defined as a blueprint from which we can create an individual object. Class doesn't
consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism:
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the
ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows us
to define one interface or method and have multiple implementations.
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest may differ
according to banks. For example, SBI, ICICI and AXIS are the child classes that provide different rates of
interest.
Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction means simple things like objects, classes, and variables represent more complex underlying
code and data. It avoids repeating the same work multiple times. In java, we use abstract class and interface
to achieve abstraction.
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it cannot be
instantiated. So we cannot create an object of an abstract class. Also, an abstract class can contain abstract
as well as concrete methods. To use an abstract class, we have to inherit it from another class where we
have to provide implementations for the abstract methods there itself, else it will also become an abstract
class.
Interface:
Interface in Java is a collection of abstract methods and static constants. In an interface, each method is
public and abstract but it does not contain any constructor. Along with abstraction, interface also helps to
achieve multiple inheritances in Java. So an interface is a group of related methods with empty bodies.
Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe
from outside interference and misuse.
In Java, the basis of encapsulation is the class. There are mechanisms for hiding the complexity of
the implementation inside the class.
Each method or variable in a class may be marked private or public.
The public interface of a class represents everything that external users of the class need to know, or
may know.
The private methods and data can only be accessed by code that is a member of the class.
Therefore, any other code that is not a member of the class cannot access a private method or
variable.
Since the private members of a class may only be accessed by other parts of program through the
class’ public methods, we can ensure that no improper actions take place.
Features of java:
The features of Java are also known as Java buzzwords. A list of most important features of java language
is given below
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple:
Its coding style is very clean and easy to
understand.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Portable:
Java is portable because it facilitates us to carry the Java byte code to any platform. It doesn't require any
implementation. Moreover, any changes and updates made in Operating Systems, Processors and System
resources will not enforce any changes in Java programs.
Platform Independent
Being platform-independent means a program compiled on one machine can be executed on any machine in
the world without any change. Java achieves platform independence by using the concept of the BYTE
code.
There are two types of platforms software-based and hardware based. Java provides a software
based platform.
Java has two components:
1. Runtime environment
2. API(Application programming language)
Java code can run on multiple platforms, for example Windows, Linux, Solaris, Mac Os, etc. Java
converts the source code into an intermediate code called the bytecode. This byte code is further translated
to machine-dependent code by another layer of software called JVM (Java Virtual Machine).
Java is a “Write Once, run anywhere” (WORA) which means that we can develop applications on one
environment (OS) and run on any other environment without doing any modification in the code.
Below diagram explains the platform independence feature of Java-Portable
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.
Class loader: Class loader in java is part of Java Runtime Environment (JRE) which is used to load
java classes into Java Virtual Machine dynamically. It adds security by separating the package for the
classes of local file system from those that are imported from network sources.
Byte code Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
Security Manager: It determines what resources a class can access such as reading and writing to the
local disk.
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.
Interpreted:
Java is both compiled and interpreted language since java programs are compiled first using java
compiler (javac) then at runtime the compiled code (bytecode) is interpreted by java interpreter in order to
execute the program.
Java is a highly interpreted language. At runtime java bytecode is interpreted(converted) into
machine code using java interpreter(part of JVM) in order to run the program. Java has the feature of just-
in-time(JIT) compilation (happens at runtime) which reduces the interpretation time.
The diagram below shows the above process:
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.
Java provides high performance with the use of “JIT – Just In Time compiler”, in which the
compiler compiles the code on-demand basis, that is, it compiles only that method which is being called.
This saves time and makes it more efficient.
Multithreaded:
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 code of java is divided into smaller parts and Java executes them in a sequential and timely manner.
The main advantage of multithreading is that the maximum utilization of resources is possible.
It doesn’t occupy memory for each thread. It shares a common memory area.
There is no need to wait for the application to finish one task before beginning another one.
There is a decreased cost of maintenance. Also, It is time-saving. It improves the performance of
complex applications.
Distributed:
Java is distributed because it encourages users to create distributed applications.
RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans) 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.
It also enables multiple programmers at many locations to work together on a single project.
Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to
classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and
even modify them.
Java even supports functions written in other languages such as C and C++ to be written in Java programs.
These functions are called “native methods”. These methods are dynamically linked at runtime.
A java program may contain many classes, of which only one class should contains main() method.
Documentation section Suggested
Package statements Optional
Import statements Optional
Interface statements Optional
Class Definations Optional
Main Method Class
{ Essential
Main Method Definations
}
Documentation section:
Package statement:
This is the first statement in java file. This statement declares a package name and informs the compiler
that the class defined here belongs to this package.
Ex: - package student
Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import java.lang.String
The above statement instructs the interpreter to load the String class from the lang package. Note:
• Import statement should be before the class definitions.
• A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method declarations.
Note: Methods in interfaces are not defined just declared.
Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A program can have
multiple class definitions.
To create a simple Java program, we need to create a class that contains the main method. Let's understand
the requirement first.
Requirements:
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
class Simple{
public static void main(String args[])
{ System.out.println("Hello Java");
}
}
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte
code.
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't require creating an object to
invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
Java Comments:
The java comments are statements that are not executed by the compiler and interpreter. The comments
can be used to provide information or explanation about the variable, method, class or any statement. It can
also be used to hide program code for specific time. Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
Syntax:
//This is single line comment
Example:
public class CommentExample1
{
public static void main(String[] args)
{
int i=10;//Here, i is a variable System.out.println(i);
}}
Output: 10
Data type:
Java is a statically typed and also a strongly typed language. In Java, each type of data (such as integer,
character, hexadecimal, etc. ) is predefined as part of the programming language and all constants or
variables defined within a given program must be described with one of the data types.
Data types represent the different values to be stored in the variable. In java, there are two categories of
data types:
Primitive data types
Non-primitive data types
Variable:
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.
Types of Variable
There are three types of variables in java:
Local variable
Instance variable
Static variable
Local variable:
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
Local variables are declared inside the methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered.
Local variable will be destroyed once it exits the method, constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial value
should be assigned before the first use.
Instance variable:
A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any block.
A slot for each instance variable value is created when a space is allocated for an object in the
heap.
Instance variables are created when an object is created with the use of the keyword ‘new’ and
destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object’s state that must be present throughout the class.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can be given
for these variables with the use of access modifiers.
Instance variables have default values.
numbers, the default value is 0,
Booleans it is false,
Object references it is null.
Values can be assigned during the declaration or within the constructor.
Instance variables cannot be declared as static.
Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using
the fully qualified name: ObjectReference.VariableName.
Static Variable:
Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
Only one copy of each class variable per class is created, regardless of how many objects are
created from it.
Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final, and static. Constant variables never change from their initial
value
Static variables are stored in the static memory. It is rare to use static variables other than declared
final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is same as instance variables. However, most static variables are declared public since
they must be available for users of the class.
Default values are same as instance variables.
Values can be assigned during the declaration or within the constructor. Additionally, values can be
assigned in special static initialize blocks.
Static variables cannot be local.
Static variables can be accessed by calling with the class name like ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as instance
and local variables.
Example:
class VaribleDemo
{
int a=10; //instance variable
static int b=20; //static variable or class variable
VaribleDemo()
{
int c =30; //Local
variables
System.out.println("c="+c);
}
void setData()
{
int d=40; //Local varibles
System.out.println("d="+d);
}
public static void main(String args[])
{
VaribleDemo v=new VaribleDemo();
System.out.println("a="+v.a);
System.out.println("b="+b);
v.setData();
}
}
Output:
ELEMENTS OR TOKENS IN JAVA PROGRAM:
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as
follows:
Keywords
Identifiers
Constants
Special Symbols
Operators
Keyword:
Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword which
is not allowed. Java language supports following keywords:
abstract assert boolean break byte
case catch char class const
continue default do double else
enum exports extends final finally
float for goto if implements
import instanceof int interface long
module native new open opens
package private protected provides public
requires return short static strictfp
super switch synchronized this throw
throws to transient transitive try
uses void volatile while with
Identifiers:
Identifiers used for naming classes, methods, variables, objects, labels and interfaces in a program.
Java identifiers follow the following rules:
1. Identifier must start with a letter, a currency character ($), or a connecting character such as
underscore (_).
2. Identifier cannot start with a number.
3. Uppercase and lowercase letters are distinct.
4. Total, TOTAL and total are different.
5. They can be of any length.
6. It should not be a keyword.
7. Spaces are not allowed.
Examples of legal and illegal identifiers follow,
Constants in Java:
A constant is a variable which cannot have its value changed after declaration. It uses the 'final' keyword.
Syntax:
Modifier final dataType variableName = value; //variable constant
Modifier static final dataType variableName = value; //constant variable
Special Symbols:
The following special symbols are used in Java having some special meaning and thus, cannot be used for
some other purpose.
[] () {}, ; * =
1. Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
2. Parentheses(): These special symbols are used to indicate function calls and function parameters.
3. Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
4. Comma (, ): It is used to separate more than one statements like for separating parameters in
function calls.
5. Semicolon: It is an operator that essentially invokes something called an initialization list.
6. Assignment operator: It is used to assign values
Operators:
Operator in java is a symbol that is used to perform operations. Java provides a rich set of operators to
manipulate variables. For example: +, -, *, / etc. All the Java operators can be divided into the following
groups
• Arithmetic Operators:
Multiplicative : * / %
Additive : + -
• Relational Operators
Comparison : < > <= >=
instanceof
Equality : == !=
• Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
Shift operator: << >> >>>
• Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
• Assignment Operators: =
• Ternary operator: ? :
• Unary operator
Postfix : expr++ exp--
Prefix : ++expr --expr +expr -expr
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, We need to convert explicitly using the cast operator “( )”
explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be
compatible with each other.
Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
Java Enum:
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
Simple example of java enum
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, RAINY };
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}
Output:
WINTER
SPRING
SUMMER
RAINY
Control flow Statements:
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a part of the
program again and again. To solve this problem, java provides control statements.
if statement
if-else statement
if-else if statement
nested if statement
switch
statement Example:
import java.util.Scanner;
public class IfElseDemo
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 2) == 0) {
System.out.println("Given number is EVEN number!!");
}
else {
while statement
do-while statement
for statement
for-each statement
Example:
break
continue
return
break:
Continue:
Introduction of classes:
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
VariableDeclaration-n;
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class. In
most classes, the instance variables are acted upon and accessed by the methods defined for that class.
Thus, it is the methods that determine how a class’ data can be used.
Example:
class Demo
{
int x=5;
void display()
{
System.out.println(“x value is: ”+x);
}}
Creating Objects:
An object in Java is essentially a block of memory that contains space to store all the instance variables.
Creating an object also known as instantiating an object. Objects in Java are created using the new
operator. The new operator creates an object of the specified class and returns a reference to that object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable
class Demo
{
int x;
int display()
{
System.out.println("X value is: "+x);
return 0;
}
public static void main(String args[])
{
Demo D1=new Demo();
D1.x=10;
D1.display();
}
}
Output:
X value is: 10
s1 Name: null
Student Objects
s2 Idno: 0
class Student
{
String name;
int idno;
public static void main(String args[])
{
Student s1=new Student();//create and initialize object
System.out.println("Name: "+s2.name);
System.out.println("Idno: "+s2.idno);
}
}
Output:
Name: null
Idno: 0
Methods in java:
A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is executed
only when we call or invoke it.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header, as we have shown in the
following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background that is already
stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Example:
In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output:
Enter the number: 45
num is odd
Constructor:
A class contains constructors that are invoked to create objects from the class blueprint. Constructor
declarations look like method declarations—except that they use the name of the class and have no return
type. A constructor initializes an object immediately upon creation.
Rules with Constructors
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Constructors should be public.
Constructors cannot be inherited.
They can be overloaded. Many constructors with the same name can be defined.
Types of Constructors:
o Default constructor: is the type of constructor with out any argument.
o Parameterized Constructor: is a constructor with one or more argument.
Default Constructor:
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
classname(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
Class Bike1
{
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}}
Output:Bike is created
Parameterized constructor:
A parameterized constructor is a constructor that accepts some parameters. Any number of parameters can
be specified. Parameterized constructors are mostly used to initialize the instance fields of a class.
Example:
class Demo
{
int num;
String name;
Demo()
{
System.out.print("default constructor");
}
Demo(int n,String name1)
{
num=n;
name=name1;
}
void display()
{
System.out.println(" "+num+" "+name);
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Demo d=new Demo ();
Demo d1=new Demo(1001,"shyam");
d.display();
d1.display();
}
}
Output:
default constructor
0 null
1001 shyam
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:
o Variable (also known as a class variable)
o Method (also known as a class method)
o Block
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).
Output:
101 Shyam SVREC
102 vinod SVREC
Program of the counter without static variable and with static variable:
//Java Program to demonstrate the use of an insta//Java Program to illustrate the use of static variab
nce variable which get memory each time when le which is shared with all objects.
we create an object of the class. class Counter{
class Counter{ static int count=0;//will get memory only once an
int count=0;//will get memory each time when the d retain its value
instance is created
Counter(){ count+ Counter(){
+;//incrementing value count++;//incrementing the value of static variable
System.out.println(count);
} System.out.println(count);
}
public static void main(String args[]){ public static void main(String args[]){
//Creating objects //creating objects
Counter c1=new Counter(); Counter c1=new Counter();
Counter c2=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); Counter c3=new Counter();
} }
} }
Output: Output:
1 1
1 2
1 3
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.
static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
this Keyword
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the
current object.
Usage of Java this keyword: Here is given the 6 usage of java this keyword.
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0
Note:If local variables (formal arguments) and instance variables are different, there is no need to use this
keyword.
2. this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[])
{ A a=new A();
a.n();
}}
Output:
hello n
hello m
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This
approach is better if you have many constructors in the class and want to reuse that constructor.
class Student{
int id;
String name;
String city;
Student(int id,String name)
{ this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student e1=new Student(111,"karan");
Student e2 =new Student(222,"Aryan","delhi");
e1.display();
e2.display();
}}
Output:
111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
Arrays:
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, the elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, and 2nd element is
stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java There
are two types of array.
o Single Dimensional Array
o Multidimensional Array
Instantiation of an Array in
Java arrayRefVar=new
datatype[size];
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of
the program
In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.
class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args)
{ Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(11,11,11));
}}
Output:
22
33
In this example, we have created two methods that differ in data type .The first add method receives two
integer arguments and second add method receives two double arguments.
class Adder{
int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args)
{ Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(12.3,12.6));
}}
Output:
22
24.9
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example:
class Box
{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
Output:
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.
Parameter passing:
CallByValue(int x, int y) {
a = x;
b = y;
}
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
}
public static void main(String args[]) {
Reference(int x, int y) {
a = x;
b = y;
}
Garbage Collection
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM.
When Java programs run on the JVM, objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds
these unused objects and deletes them to free up memory.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be used to
perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you
have created any object without new, you can use finalize method to perform cleanup processing
(destroying remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in
System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
Simple Example of garbage collection in java
public class
TestGarbage1{ int a,b;
TestGarbage1()
{ a=10;
b=20;
}
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[])
{ TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=s1;
new TestGarbage1();
System.gc();
} }
Output:
object is garbage collected
object is garbage collected
object is garbage collected
guaranteed. Recursion:
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself
is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname()
{
//code to be executed methodname();//calling same method
}
Example:
class Factorial
{
// this is a recursive function
int fact(int n)
{ int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
String class:
String is a sequence of characters. But in Java, a string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.
String is final class in java.
public final class String extends Object implements Serializable, Comparable<String>, CharSequence.
Inheritance: Basics, Using Super, Creating Multilevel hierarchy, Method overriding, Dynamic Method
Dispatch, Using Abstract classes, Using final with inheritance, Object class
Packages: Basics, Finding packages and CLASSPATH, Access Protection, Importing packages.
Interfaces: Definition, Implementing Interfaces, Extending Interfaces, Nested Interfaces, Applying Interfaces,
Variables in Interfaces.
Inheritance
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 we can create new classes that are built upon existing classes. When
we inherit from an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new
methods and fields in your current class also.
Extends keyword in JavaThe extended keyword extends a class and is an indicator that a class is being
inherited by another class. When we say class B extends a class A, it means that class B is inheriting the
properties(methods, attributes) from class A. Here, class A is the superclass or parent class and class B is the
subclass or child class.
Types of inheritance:
Single Inheritance:
When a class inherits another class, it is known as a single inheritance. It means that the properties of the base
class are acquired by the derived class.
Example:
class A
{
int a, b;
void display()
{
System.out.println(“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;
void show()
{
System.out.println(“Inside Class B values=”+a+” “+b+” “+c);
}
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10; Output:
obj.b=20; Inside class A values =10 20
obj.c=30; Inside Class B values=10 20 30
obj.display();
obj.show();
}
}
Note:
Even though a subclass includes all of the members of its super class, it cannot access those members who are
declared as Private in super class.
Super Keyword:
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever we create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.
d.printColor();
}}
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use super
keyword.
void display() {
// print maxSpeed of base class (vehicle)
System.out.println("vehicle class display");
}
Output:
}
vehicle class display
// sub class Car extending vehicle
car class display
class Car extends Vehicle {
Maximum Speed: 120
int maxSpeed = 180;
void display() {
// print maxSpeed of base class (vehicle)
super.display();
System.out.println("car class display");
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args) {
Car small = new Car();
small.display();
}
}
The super keyword can also be used to invoke the parent class constructor.
class A
{
int a;
A(int a)
{
this.a=a;
System.out.println("a="+a);
}
}
class B extends A
{
int b;
B(int a,int b)
{
super(a);
System.out.println("b="+b);
}
}
class TestSuper
{
public static void main(String args[])
{
B obj=new B(4,5);
}
}
Output:
a=4
b=5
Multilevel Inheritance:
In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel
inheritance a subclass is derived from a derived class. One class inherits only single class. Therefore, in
multilevel inheritance, every time ladder increases by one. The lower most class will have the properties of all
the super classes’
It is common that a class is derived from another derived class. The class student serves as a base class for the
derived class marks, which in turn serves as a base class for the derived class percentage. The class marks is
known as intermediates base class since it provides a link for the inheritance between student and percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the
features found in all of its super classes. In this case, percentage inherits all aspects of marks and student.
Example:
class student {
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas() {
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student {
int total;
class A {
public void methodA() {
System.out.println("method of Class A");
}
}
class B extends A {
public void methodB() {
System.out.println("method of Class B");
}
}
class C extends A {
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");
}
}
class JavaExample {
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
System.out.println("B class object");
obj1.methodA();
obj1.methodB();
System.out.println("C class object");
obj2.methodA();
obj2.methodC();
System.out.println("D class object");
obj3.methodA();
obj3.methodD();
System.out.println("A class object");
A obj4 = new A();
obj4.methodA();
}
}
Multiple Inheritance:
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance”
is that the derived class will have to manage the dependency on two base classes.
Note:
*To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
*Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call the method
of A or B class.
*Since compile-time errors are better than runtime errors, Java renders compile-time error if we inherit 2 classes.
So whether we have same method or different, there will be compile time error.
Hybrid inheritance
A hybrid inheritance is a combination of more than one types of inheritance. For example when class A and B
extends class C & another class D extends class A then this is a hybrid inheritance, because it is a combination of
single and hierarchical inheritance.
Polymorphism:
Note:
Overloading is not possible by changing the return type only. It gives compile time error due to ambiguity.
Type promotion:
Smaller data type is promoted to bigger once if no matching data type is found
Eg: add(int a,long b)
Call>add(4,5) the 5 is promoted to long data type.
Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within its subclass, it will always refer to the version of
that method defined by the subclass. The version of the method defined by the superclass will be
hidden.
Method overriding is used for runtime polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)
example:
class Animal{}
class Dog extends Animal{}
Animal a=new
Dog();//upcasting
In the above example, we've created two classes, named
Animal(superclass) & Dog(subclass).
While creating the object 'a', we've taken the reference variable of the parent class(Animal), and the object
created is of child class(Dog).
class Phone {
public void showTime() {
System.out.println("Time is 8 am");
}
public void on() {
System.out.println("Turning on Phone...");
}
}
obj.showTime();
obj.on();
// obj.music(); Not
Allowed obj = new
Phone(); obj.on();
}
}
Output:
Time is 8 am
Turning on SmartPhone...
Turning on Phone...
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where we type the text and send the message. We don't know the internal processing about the message delivery.
Concrete class:
A concrete class is one which contains fully defined methods. Defined methods are also known as
implemented or concrete methods. With respect to concrete class, we can create an object of that
class directly.
Abstract class:
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods (methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods.
An abstract class is one which contains some defined methods and some undefined methods. Undefined
methods are also known as unimplemented or abstract methods. Abstract method is one which does not
contain any definition. To make the method as abstract we have to use a keyword called “abstract” before
the function declaration.
In java, the following some important observations about abstract classes are as follows:
An instance (object) of an abstract class cannot be created.
Constructors are allowed.
We can have an abstract class without any abstract method.
There can be a final method in abstract class but any abstract method in class(abstract class) cannot be
declared as final or in simpler terms final method cannot be abstract itself as it will yield an error:
“Illegal combination of modifiers: abstract and final”
We can define static methods in an abstract class
We can use the abstract keyword for declaring top-level classes (Outer class) as well as inner
classes as abstract
If a class contains at least one abstract method then compulsory should declare a class as abstract
If the Child class is unable to provide implementation to all abstract methods of the Parent class then
we should declare that Child class as abstract so that the next level Child class should provide
implementation to the remaining abstract method.
Example 1:
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{ Output:
B's implementation of callme.
void callme()
This is a concrete method.
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
A b = new B();
b.callme();
b.callmetoo();
}}
Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract
class.
One other point: class A implements a concrete method called callmetoo()
Example 2:
abstract class Bike
{
static int speed=70;
Bike() //constructor
{
System.out.println("Bike is created");
}
abstract void run(); //abstrct method
static void runSpeed() //static method
{
System.out.println("Speed:"+speed);
}
final void changGear() //final method
{
System.out.println("Gear changed");
}
}
class Honda extends Bike{
void run()
{
System.out.println("Running safely");
}
}
abstract class Abstract{
Output:
public static void main(String[] args) {
Bike is created
Bike b=new Honda(); Running safely
b.run(); Speed:70
Bike.runSpeed(); Gear changed
b.changGear();
}
}
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final
can be:
1. variable
2. method
3. class
final Variable – Once a variable is declared as final, it can be initialized during declaration or in the constructor.
And can never be changed during the course of the program. Hence static final variables are also called
constants.
If we make any variable as final, we cannot change the value of final variable(It will be constant).
Example:
final Method – Once a method is declared as final, it can never be overridden by any sub class that is inheriting
the method’s class.
Example:
Example:
Object class:
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if
extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java
classes. Hence Object class acts as a root of the inheritance hierarchy in any Java Program.
Method Description
public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
1. toString() method
The toString() provides a String representation of an object and is used to convert an object to a String.
The default toString() method for class Object returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code
of the object. In other words, it is defined as:
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
It is always recommended to override the toString() method to get our own String representation of Object.
Note: Whenever we try to print any Object reference, then internally toString() method is called.
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
Output:
Student@64
// Overriding hashCode() Student@64
public int hashCode() { return roll_no; }
// Driver code
public static void main(String args[])
{
Student s = new Student();
3. equals():
This method compares two objects and returns whether they are equal or not. It is used to compare the value of
the object on which the method is called and the object value which is passed as the parameter.
4. getClass():
It is used to return the class object of this object. Also, it fetches the actual runtime class of the object on
which the method is called. This is also a native method. It can be used to get the metadata of the this class.
Metadata of a class includes the class name, fields name, methods, constructor, etc.
Example:
public class MainClass {
public static void main(String[] args) {
Object s = new String("Hi");
Output:
Object i = new Integer(19); Class of Object s is : java.lang.String
Class c = s.getClass(); Class of Object i is : java.lang.Integer
Class d = i.getClass();
// for the String
System.out.println("Class of Object s is : " + c.getName());
// for the integer
System.out.println("Class of Object i is : " + d.getName());
}
}
5. clone():
The clone() method is used to create an exact copy of this object. It creates a new object and copies all the
data of the this object to the new object.
Example:
import java.util.*;
// declare variables
String name;
int age;
// print variable
System.out.print(obj1.name); // xyz
System.out.println(" " + obj1.age); // 19
try {
Output:
xyz 19
// create clone of obj1
xyz 19
MainClass obj2 = (MainClass) obj1.clone();
}
}
JAVA - PACKAGES
What is package:
Packages are used in Java, in-order to avoid name conflicts and to control access of class, interface
and enumeration etc. A package can be defined as a group of similartypes of classes, interface,
enumeration or sub-package.
Using package it becomes easier to locate the related classes and it also provides a good structure for
projects with hundreds of classes and other files.
*Packages are those classes which contains methods without the main method in them.
*Packages are mainly used to reuse the classes which are already created/used in other program.
*We can define many numbers of classes in the same package.
Benefits of using package in java:
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
This package can be providing reusability of code.
We can create our own package or extend already available package.
Built-in Package: Existing Java package forexample java.lang, java.util, java.io etc.
User-defined-package: Java package created by user to categorize their project's classes and
interface.
Built Packages are provided for the programme in-order to reduce the burden.Some of the frequently used
built in packages are:
1. java.lang: language supports classes. These are classes that java compiler itself uses and therefore
automatically imported. They include classes for primitive types, strings, math, threads and exceptions.
2. java.util: language utility classes such as vectors, hash tables, random numbers, date etc.
3. java.io: input/output support classes. They provide the facility for input/output of data.
4. java.awt: set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists
5. java.net: Classes for networking. They include classes for communicating with local computers as well
as with internal servers.
Access Protection:
Classes and packages are both means of encapsulating and containing the name space and scope of variables and
methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data
and code. The class is Java‘s smallest unit of abstraction.
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.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
Private
Default
Protected
Public
How to Create a package:
Creating a package in java is quite easy. Simply include a package command followed by name of the
package as the first statement in java source file.
Example:
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the projectdirectory.
Java uses file system directories to store packages. For example the .java file for any class you define to be
part of mypackage package must be stored in a directory called mypackage. Additional points about
package:
A package is always defined as a separate folder having the same name as the package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package mustbe declared public.
All classes within the package must have the package statement as its firstline.
All classes of the package must be compiled before use (So that they areerror free)
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).
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.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Example of package that import the packagename.*:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello java");
}
}
//save by B.java
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new
A(); obj.msg();
}
}
Output: Hello java
2) Using packagename.classname:
If you import package.classname then only declared class of this package will beaccessible.
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
Output: Hello
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.
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, we need to import the subpackage as well.
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.
package com.javatpoint.core;
class Simple{
For example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}}
To Compile:
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;.;
The -d switch specifies the destination where to put the generated class file. We can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If we want to keep
the package within the same directory, we can use . (dot).
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to
look for class file. For example:
Introduction
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and abstract.
As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.
Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods defined by the
interface. The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{ // class-body }
If a class implements more than one interface, the interfaces are separated with a comma.
interface printable{
void print();
}
class A6 implements printable{ Output:
public void print(){System.out.println("Hello");} Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
} Output:
class A7 implements Printable,Showable{ Hello
public void print(){System.out.println("Hello");} Welcome
public void show(){System.out.println("Welcome");}
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an
example:
File: TestInterfaceDefault.java
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
Output:
}
drawing rectangle
class Rectangle implements Drawable{
default method
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Nested Interfaces:
An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces
are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred
by the outer interface or class. It can't be accessed directly. There are given some points that should be
remembered by the java programmer.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
Nested interfaces are declared static implicitly.
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Output:
Hello nested interface
As we can see in the above example, we are acessing the Message interface by its outer interface Showable
because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah
directly because we must enter the room first.
Output:
Hello nested interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Class can contain concrete(with implementation) The interface cannot contain concrete(with
methods implementation) methods
The access specifiers used with classes are In Interface only one specifier is used- Public.
private, protected, and public.
UNIT - III Exception handling, Stream based I/O (java.io)
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and
catch, multiple catch clauses, nested try statements, throw, throws and finally, built-in
exceptions, creating own exception subclasses.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and Writing Files, Random
access file operations, The Console class, Serialization, Enumerations, Autoboxing, Generics.
Exception handling:
An exception is an unexpected event that occurs during program execution. It affects the flow
of the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
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:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5; //exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.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:
Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle
errors.
Exceptions
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.
RuntimeException
A runtime exception happens due to a programming error. They are also known
as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
Improper use of an API - IllegalArgumentException
Null pointer access (missing the initialization of a variable) - NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
We can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if we had checked whether the variable
was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if we tested the array index
against the array bounds.
IOException
An IOException is also known as a checked exception. They are checked by the compiler
at the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
Trying to open a file that doesn’t exist results in FileNotFoundException
Trying to read past the end of a file
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:
1. Checked Exception
2. Unchecked Exception
3. Error
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.
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.
catch blocks:
E:\>java JavaExceptionExample
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaExceptionExample.main(JavaExceptionExample.java:5)
2. toString() – This method prints exception information in the format of Name of the
exception: description of the exception.
Example:
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
Output:
java.lang.ArithmeticException: / by zero
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
Output:
/ by zero
Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
JavaExceptionExample.java
Output:
E:\>javac JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){ E:\>java JavaExceptionExample
try{ java.lang.ArithmeticException: / by zero
//code that may raise exception rest of the code...
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Multiple catch clauses:
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if we have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
System.out.println("other statement");
}
// catch block of outer try block
catch (Exception e) {
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
E:\>javac NestedTryBlock.java
E:\>java NestedTryBlock
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..
Throw statement:
program:
//user defined exception
class Eligible extends Exception {
String str;
Eligible(String s) {
str = s;
}
public String toString() {
return ("user defined Exception is " + str);
}
public static void main(String[] args)throws Eligible {
int age = 15;
try {
if (age < 18) {
throw new Eligible("not eligible for vote");
} else {
System.out.println("eligible for vote");
}
} catch (Eligible e) {
Output:
System.out.println(e); E:\>javac Eligible.java E:\
} >java Eligible
finally user defined Exception is not eligible for
{ vote
System.out.println("Finally block"); Finally block
}
System.out.println("rest of code");
}
}
throws is a keyword in Java which is used in the signature of method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
Syntax:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 …
{
// code
}
exception_list is a comma separated list of all the
exceptions which a method might throw.
Example:
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
Finally block:
Java finally block is a block used to execute important code such as closing the connection,
etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.
Example:
public class TestFinallyBlock1{
public static void main(String args[]){
try {
E:\>javac TestFinallyBlock.java
E:\>java TestFinallyBlock
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock.main(TestFinallyBlock.java:9)
List of checked exceptions in Java
The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be
instantiated because it is an interface or is an abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.
1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
S.
No. Exception Class with Description
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type
of object into an array of objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to
another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
or inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without
owning the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to
modify the state of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as
an array , vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
S.
No. Exception Class with Description
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.
The Stream:
A stream is a sequence of data. Streams facilitate translating data from one place to another.
Different streams are needed to send and receive data through different sources, such as to
receive data from keyboard, we need a stream and to send data to a file, we need another
stream. Without streams it is not possible to move data in java.
Standard Input: Accessed through in which is used to read input from the keyboard.
Standard Output: Accessed through out which is used to write output to the display
(console).
Standard Error: Accessed through err which is used to write error output to the
display (console).
There are two brands of Stream in Java Programming Language:
1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source. The Input
Stream provides the set of Objects and pipelines together to provide us the functionality of
Input the collection in I/O File.
2. Output Stream:
The Output Stream provides the functionality of writing the data to the Destination. The
Output Stream provides the set of Objects and pipelines together to provide us the
functionality of Output to the collection in I/O File.
Fig: Flow of data in standard Input-Output streams and file streams
The Java Input/Output (I/O) is a part of java.io package. This package contains a relatively
large number of classes that support input and output operations. These classes may be
categorized into groups based on the data type on which they operate.
1. Byte Stream Classes that provide support for handling I/O operations on bytes.
2. Character Stream Classes that provide support for managing I/O operations
on characters.
These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions. Byte stream and Character stream classes
contain specialized input and output stream classes to deal with input and output operations
independently on various types of streams.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown
below:
Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses.
Here are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream
OutputStream Classes
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when we create it. We can explicitly close an output stream with
the close() method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses.
Here are some of the methods:
write() - writes the specified byte to the output stream
write(byte[] array) - writes the bytes from the specified array to the output stream
flush() - forces to write all data present in output stream to the destination
close() - closes the output stream
abstract void close() It closes the stream and releases any system resources
associated with it.
Boolean markSupported() It tells whether this stream supports the mark() operation.
int read() It reads a single character.
abstract int read(char[] cbuf, int off, int It reads characters into a portion of an array.
len)
int read(CharBuffer target) It attempts to read characters into the specified character
buffer.
Writer append(CharSequence csq, int start, It appends a subsequence of the specified character
int end) sequence to this writer.
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.
void write(String str, int off, int len) It writes a portion of a string.
Java provides different ways to take input and provide output on the console.
We use the object of Bufferedredaer class to take input from the keyboard
To use these classes, we need to use the java.io package. Let’s see an example to understand
this method of reading input from the console.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import
java.io.InputStreamReader; public
class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
//Taking the input data using the BufferedReader class
BufferedReader br= new BufferedReader(input);
The other use of Scanner class is to parse the strings and primitive types with the help of java
regular expressions.
The Scanner class is present in the java.util package. This class obtains the input from
System.in (standard input stream).
Advantages
The Scanner class provides useful methods like nextInt(), nextDouble(), nextFloat(), etc,
for parsing primitive data types.
The Scanner class uses regular expressions and we can use these regular expressions to
find tokens.
Drawback
The methods of Scanner class for reading values are not synchronized
Methods:
To read the values of various data types, the Scanner class provides several methods. The
following table shows these methods:
Method Description
Example:
import java.util.Scanner;
public class ScannerClassDemo
{
// Java program to understand the use of Scanner in Java
public static void main(String args[]) Output:
{ E:\pgms>javac
// Using Scanner for Getting Input from User ScannerClassDemo.java E:\pgms>java
Scanner sc = new Scanner(System.in); ScannerClassDemo Enter a string
ram
System.out.println("Enter a string"); You entered string: ram
Enter a number
String string = sc.nextLine(); 1001
System.out.println("You entered string: " +string); You entered integer: 1001
Enter a float number
System.out.println("Enter a number"); 78.9076
int num = sc.nextInt(); You entered float: 78.9076
System.out.println("You entered integer: " +num);
we use the Console class, the JVM associated system console isn't available if we run the code
within an IDE such as Eclipse or IntelliJ IDEA.
There are several methods in Console class that help in reading input texts and passwords
from the console, without displaying it on the screen.
String readLine() This method reads a single line of text from the console.
char[] readPassword() It is used to read a password that is visible on the console screen.
Advantages
Reading password without displaying the characters of the password on the console.
Reading methods of the console class are synchronized.
We can also use the format string syntax with the Console
class Drawback
It does not work in a non-interactive environment (such as in an
IDE). Example:
import java.io.*;
Output:
E:\pgms>javac ConsoleDemo.java
public class ConsoleDemo { E:\pgms>java ConsoleDemo
public static void main(String[] args) Enter username : satya
{ Username : satya
// Create the console object Enter password :
Password : [C@3b9a45b3
Console cnsl= System.console();
if (cnsl == null) {
System.out.println("No console available");
return;
}
// Read line
String str = cnsl.readLine("Enter username : ");
// Print username
System.out.println("Username : " + str);
// Print password
System.out.println("Password : " + ch);
}
}
Writing console output in java
In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.
File class:
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory. The File class
has various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.
import java.io.File;
FileWriter Class:
Java FileWriter class of java.io package is used to write data in character form to file.
Java FileWriter class is used to write character-oriented data to a file. This class
extends OutputStreamWriter. This class provides methods to write strings directly so we don't
need to convert string to a byte array.
o FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
o FileWriter creates the output file if it is not present already.
Constructor Description
FileWriter(String
This constructor creates a new file. It gets the file name in a string.
file)
This constructor creates a new file. It gets the file name in the File
FileWriter(File file)
object.
Method Description
void write(String text) This method is used to write the string into FileWriter.
void write(char c) This method is used to write the char into FileWriter.
void write(char[] c) Thi method is used to write char array into FileWriter.
try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");
FileReader class:
The FileReader class of the java.io package can be used to read data (in characters) from files.
It extends the InputSreamReader class.
Create a FileReader
In order to create a file reader, we must import the java.io.FileReader package first. Once we
import the package, here is how we can create the file reader.
1. Using the name of the file
FileReader input = new FileReader(String name);
Here, we have created a file reader that will be linked to the file specified by the name.
2. Using an object of the file
FileReader input = new FileReader(File fileObj);
Here, we have created a file reader that will be linked to the file specified by the object of the
file.
Methods of FileReader
The the FileReader
class provides implementations for different methods present in
Reader
class.
read() Method
read() - reads a single character from the reader
read(char[] array) - reads the characters from the reader and stores in the specified array
read(char[] array, int start, int length) - reads the number of characters equal to length from
the reader and stores in the specified array starting from the position start
For example:
we have a file named input.txt with the following content.
This is a line of text inside the file.
Let's try to read the file using FileReader.
import java.io.FileReader;
class Main {
public static void main(String[] args) {
try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array); Output
Data in the file:
This is a line of text inside the file.
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have created a file reader named input. The file reader is linked with
the file input.txt.
FileInputStream input = new FileInputStream("input.txt");
To read data from the file, we have used the read() method.
Note: The file input.txt should be present in the current working directory.
RandomAccessFile:
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number
of byte has been read than EOFException is thrown. It is a type of IOException.
Constructor Description
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
Method:
void seek(long It sets the file-pointer offset, measured from the beginning of this
pos) file, at which the next read or write occurs.
void write(int b) It writes the specified byte to this file.
Example:
import java.io.RandomAccessFile;
import java.io.*;
class RaFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile rf=null;
try{
rf=new RandomAccessFile("output.txt","rw");
rf.seek(34);
Output:
rf.writeUTF("Hyderabad"); E:\>javac RaFile.java
rf.seek(10); E:\>java RaFile
int b; file to display capital
while((b=rf.read())!= -1) Hyderabad,,amaravathi
{
System.out.print((char)b);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(rf != null)
{
rf.close();
}
}
}
}
Java Enum:
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, we should always represent
them in UPPERCASE letters.
You can use an Enum type when we need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.
default:
System.out.println(" WORNG WEEK NAME");
break;
}
}
}
}
Serialization:
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform
can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
// Default constructor
public Student(int a, String b)
{
this.a = a;
this.b = b;
}
}
class Test
{
public static void main(String[] args)
{
Student object = new Student(1001, "ram");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of
object out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Student object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.close();
file.close();
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.
Example:
class BoxingExample1{
public static void main(String args[])
{ int a=50;
Output:
Integer a2=new Integer(a);//Boxing
Integer a3=5; //Boxing 50 5
System.out.println(a2+" "+a3);
}
}
The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing. Let's see the example of unboxing:
class UnboxingExample1{
public static void main(String args[])
{ Integer i=new Integer(50);
int a=i;
System.out.println(a); 50
}}
Generics in Java:
Generics means parameterized types. The idea is to allow type (Integer, String, … etc.,
and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types.
Note: Generics does not work with primitive types (int, float, char, etc).
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to
store other objects.
E:\>java GenericsDemo
Generic Class returns: 5
Generic Class returns: Java Programming
Java StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
Example:
class StringBufferExample{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hellojava
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
StringBuilder class:
StringBuilder class has been added in JDK1.5 which has same features like StringBuffer class.
StringBuilder class objects are also mutable as the stringBuffer Objects.
Difference:
StringBuffer is class is synchronized and StringBuilder is not.
Multithreading, The Collections Framework (java.util)
Multithreading: The Java thread model, Creating threads, Thread priorities, Synchronizing
threads, Interthread communication.
The Collections Framework (java.util): Collections overview, Collection Interfaces, The
Collectionclasses- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque.
Hashtable, Properties, Stack, Vector, String Tokenizer, Bit Set, Date, Calendar, Random,
Formatter, Scanner.
Multitasking:
Thread:
The java programming language allows us to create a program that contains one or more parts that
can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java.
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is shown
in the following figure.
Let's look at each phase in detailed.
New
When a thread object is created using new, then the thread is said to be in the New state. This state
is also known as Born state.
Example
Thread t1 = new Thread();
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This state is
also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep( )
method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like
sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( )
method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution completed
or the stop( ) method called. The dead state is also known as the terminated state.
Creating threads in java:
In java, a thread is a lightweight process. Every java program executes by a thread called the main
thread. When a java program gets executed, the main thread created automatically. All other
threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.
Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above
step. Example:
Example:
class SampleThread implements
Runnable{ public void run() {
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class MyThreadTest {
public static void main(String[] args) {
SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}
Thread class:
The Thread class has the following consructors.
Thread( )
Thread( String threadName )
Thread( Runnable objectName )
Thread( Runnable objectName, String threadName )
Method Description
void run( ) Defines actual task of the thread.
void start( ) It moves thre thread from Ready state to Running state by calling run(
) method.
void setName(String) Assigns a name to the thread.
String getName( ) Returns the name of the thread.
void setPriority(int) Assigns priority to the thread.
int getPriority( ) Returns the priority of the thread.
long getId( ) Returns the ID of the thread.
int activeCount() Returns total number of thread under active.
currentThread( ) Returns the reference of the thread that currently in running
state. void sleep( long ) moves the thread to blocked state till the specified number of
milliseconds.
boolean isAlive( ) Tests if the thread is alive.
void yield( ) Tells to the scheduler that the current thread is willing to yield its
current use of a processor.
void join( ) Waits for the thread to end.
Note:
The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and resume( ).
But they are deprecated.
Thread priorities:
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10 is
considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they are
listed below.
MAX_PRIORITY - It has the value 10 and indicates highest priority.
NORM_PRIORITY - It has the value 5 and indicates normal priority.
MIN_PRIORITY - It has the value 1 and indicates lowest priority
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not takes
anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example
String threadName = threadObject.getPriority();
Example:
Note: The synchronization is the process of allowing only one thread to access a shared resource
at a time.
Mutual Exclusion
Inter thread communication
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while they
accessing the shared resource. In java, mutual exclusion is achieved using the following concepts.
Synchronized method
Synchronized block
Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at a
time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that is trying to call the same method must wait, until the lock is released. Once
the lock is released on the shared resource, one of the threads among the waiting threads will be
allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method). When
thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example:
class Printer {
synchronized void printobject(String s) {
System.out.println("\n---start---");
for (int i = 0; i < s.length(); i++)
System.out.print(s.charAt(i));
System.out.print("\n---end---");
} E:\pgms>javac SyncDemo.java
E:\pgms>java SyncDemo
}
---start---
11111111111111111111111
class Cabin extends Thread { ---end---
Printer pnr; ---start---
String str; aaaaaaaaaaa
---end---
---start---
Cabin(Printer pnr, String str) { xxxxxxxxxxxx
this.pnr = pnr; ---end---
this.str = str;
}
class SyncDemo {
public static void main(String args[])throws InterruptedException {
Printer p = new Printer();
Cabin c1 = new Cabin(p, "11111111111111111111111");
Cabin c2 = new Cabin(p, "aaaaaaaaaaa");
Cabin c3 = new Cabin(p, "xxxxxxxxxxxx");
c1.start();
c2.start();
c3.start();
}
}
Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines in
a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.
Syntax
synchronized(object){
...
block code
...
}
Example
class TicketCounter {
int availableSeats = 2;
void bookTicket(String name, int numberOfSeats) {
if((availableSeats >= numberOfSeats) && (numberOfSeats > 0)) {
System.out.println(name+" : "+ numberOfSeats + " Seats Booking Success");
availableSeats -= numberOfSeats;
} else {
System.out.println(name +" : Seats Not Available");
}
}
}
class TicketBookingThread extends Thread {
TicketCounter tc;
String name;
int seats;
TicketBookingThread(TicketCounter tc, String name, int seats) {
this.tc = tc;
this.name = name;
this.seats = seats;
}
public void run() { E:\pgms>javac SynchronizedBlockTest.java
synchronized(tc) { // synchronized block
tc.bookTicket(name, seats); E:\pgms>java SynchronizedBlockTest
Adithya : 2 Seats Booking Success
} Jai : Seats Not Available
}
}
public class SynchronizedBlockTest {
public static void main(String[] args) {
TicketCounter tc = new TicketCounter();
TicketBookingThread t1 = new TicketBookingThread(tc, "Adithya", 2);
TicketBookingThread t2 = new TicketBookingThread(tc, "Jai", 2);
t1.start();
t2.start();
}
}
Note: The complete code of a method may be written inside the synchronized block, where it
works similarly to the synchronized method.
wait( )
notify( )
notifyAll( )
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
Let's look at an example problem of producer and consumer. The producer produces the item and
the consumer consumes the same. But here, the consumer cannot consume until the producer
produces the item, and producer cannot produce until the consumer consumes the item that
already been produced. So here, the consumer has to wait until the producer produces the item,
and the producer also needs to wait until the consumer consumes the same. Here we use the inter-
thread communication to implement the producer and consumer problem.
Example:
class Holder
{
String data;
synchronized void putFruit(String s)
{
if(data!=null)
{
try{ w
ait();
}catch(Exception e){}
}
data=s;
System.out.println(data+" placed");
notify();
}
synchronized String getFruit()
{
String str;
if(data==null)
{
try{
wait();
}catch(Exception e){}
}
str=data;
data=null;
System.out.println(str+" received");
notify();
return str;
}
}
class Producer extends Thread
{
String fruits[]={"apple","banana","grapes","mango","cherry"};
Holder h;
public void run()
{
for(int i=0;i<fruits.length;i++)
{
h.putFruit(fruits[i]);
try{
sleep(1000);
}catch(Exception e){}
}
}
}
class Consumer extends Thread{
Holder h;
public void run()
{
for(int i=0;i<5;i++)
{ Output:
h.getFruit(); E:\pgms>javac ConsProdThread.java
} E:\pgms>java ConsProdThread
} apple placed
} apple received
class ConsProdThread banana placed
{ banana received
public static void main(String args[]) grapes placed
{ grapes received
Holder h=new Holder(); mango placed
Producer p=new Producer(); mango received
Consumer c=new Consumer(); cherry placed
p.h=h; cherry received
c.h=h;
p.start();
c.start();
}
}
Note:All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized
methods only.
Java Collection Framework
Java Collections Framework all classes are divided into following 3 different types of
classes.
Classes
1. Container Objects classes
2. Cursor Objects classes
3. Utility Objects classes
1. Container Objects classes: Following 4 Interfaces are called container objects
List <T> HashSet <T>, LinkedHashSet<T>
Set <T> Stack <T>, LinkedList<T>, ArrayList<T>,Vector<T>
Map <K,V> HashMap <K,V>, Hashtable<K,V>
Queue <T> LinkedList <T>
<T> Represents generic type parameter, i.e which type of elements are being stored.
2. Cursor objects are retrieving objects
Enumeration
Iterator
ListIterator
3. Utility Objects: it is nothing but a class that is given to perform different operations
on container objects are called utility objects i.e two classes
Collections class
Arrays
The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
searching,
sorting,
insertion,
manipulation,
deletion etc.
4. Java collection framework provide many Interfaces and classes
Iterable is the root interface of the Java collection classes. The Collection interface extends
Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface
stands to represent data-structures whose value can be traversed one by one. This is an important
property.
Sets:
A set represents a group of elements arranged just like an array. The set will grow dynamically
when the elements are stored into it. A set will not allow duplicate elements. If we try to pass
for same element that is already available in the set, then it is not stored into the set.
List:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be stored.
Queues:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that
an element that is stored as a first element into the queue will be removed first from the
queue.
Maps:
Maps store elements in the form of key and value pairs. If the key is provided then it’s correspond
value can be obtained. Of course, the keys should have unique values.
Remember, in all the cases the 'elements' refer to 'objects' only. This means we cannot store
primitive data types in the collection objects. We can store only objects since the main aim of
collections is to handle objects only, not the primitive data types.
3. ListIterator Interface:
ListIterator is an interface that contains methods to retrieve the elements from a collection object,
both in forward and reverse directions. It can retrieve the elements in forward and backward
direction. It has the following important methods:
Methods of ListIterator
The ListIterator interface provides methods that can be used to perform various operations on the
elements of a list.
hasNext() - returns true if there exists an element in the list
next() - returns the next element of the list
nextIndex() returns the index of the element that the next() method will return
previous() - returns the previous element of the list
previousIndex() - returns the index of the element that the previous() method will return
remove() - removes the element returned by either next() or previous()
set() - replaces the element returned by either next() or previous() with the specified element
4. Enumeration Interface:
This interface is useful to retrieve elements one by one like Iterator.
It has 2 methods.
hasMoreElements(): It returns true if more elements are left to iterate otherwise returns
false.
Syntax: public boolean hasMoreElements()
nextElement(): It returns the next object of the enumeration.
HashSet Class:
HashSet represents a set of elements (objects). It does not guarantee the order of elements. Also it
does not allow the duplicate elements to be stored.
Example:
import java.util.HashSet; import
java.util.Iterator; public class
HashSetDemo {
public static void main(String[] args) {
//create a HashSet to store Strings
HashSet <String> hs = new HashSet<String> ();
//Store some String elements
hs.add ("Anil");
hs.add ("Akshara");
hs.add ("Babji");
hs.add ("Charan");
hs.add ("Raman");
System.out.println ("HashSet = " + hs);
//add an Iterator to hs HashSet = [Akshara, Raman, Babji, Anil, Charan]
Iterator<String> it = hs.iterator (); Elements Using Iterator:
//display element by element using Iterator Akshara
System.out.println ("Elements Using Iterator: "); Raman
while (it.hasNext() ) Babji
{ Anil
String s = (String) it.next (); Charan
System.out.println(s);
}
}}
Stack Class:
A stack represents a group of elements stored in LIFO (Last In First Out) order.
This means that the element which is stored as a last element into the stack will be the first
element to be removed from the stack. Inserting the elements (Objects) into the stack is called
push operation and removing the elements from stack is called pop operation.
Searching for an element in stack is called peep operation. Insertion and deletion of elements take
place only from one side of the stack, called top of the stack.
push(E item) E The method pushes (insert) an element onto the top of the
stack.
pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object o) int The method searches the specified object and returns the
position of the object.
Example:
import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{ Output: stack: []
//creating an object of Stack class push -> 20
Stack <Integer> stk = new Stack<>(); stack: [20]
System.out.println("stack: " + stk); push -> 13
//pushing elements into the stack
stack: [20, 13]
pushelmnt(stk, 20);
pushelmnt(stk, 13); push -> 89
pushelmnt(stk, 89); stack: [20, 13, 89]
pushelmnt(stk, 90); push -> 90
pushelmnt(stk, 11); stack: [20, 13, 89, 90]
pushelmnt(stk, 45); push -> 11
pushelmnt(stk, 18);
stack: [20, 13, 89, 90, 11]
//popping elements from the stack
popelmnt(stk); push -> 45
popelmnt(stk); stack: [20, 13, 89, 90, 11, 45]
//throws exception if the stack is empty push -> 18
try stack: [20, 13, 89, 90, 11, 45, 18]
{ pop -> 18
popelmnt(stk); stack: [20, 13, 89, 90, 11, 45]
}
pop -> 45
catch (EmptyStackException e)
{ stack: [20, 13, 89, 90, 11]
System.out.println("empty stack"); pop -> 11
} stack: [20, 13, 89, 90]
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
ArrayList Class:
Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class
and implements List interface.
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized. This means that when more than one thread acts
simultaneously on the ArrayList object, the results may be incorrect in some cases.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.
Methods of ArrayList
Method Description
void add(int index, E It is used to insert the specified element at the specified position in a
element) list.
boolean add(E e) It is used to append the specified element at the end of a list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of the list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list
in the correct order.
Boolean contains(Object o) It returns true if the list contains the specified element.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in
the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.
int size() It is used to return the number of elements present in the list.
Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only
specified type of objects in it. If we try to add another type of object, it gives compile time error.
Vector:
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
1) ArrayList is not synchronized. 1) Vector is synchronized.
2) ArrayList increments 50% of current array 2) Vector increments 100% means doubles
size if number of element exceeds from its the array size if total number of element
capacity. exceeds than its capacity.
3) ArrayList is not a legacy class, it is 3) Vector is a legacy class
introduced in JDK 1.2.
4) ArrayList is fast because it is non- 4) Vector is slow because it is synchronized
synchronized. i.e. in multithreading environment, it will
hold the other threads in runnable or non-
runnable state until current thread releases the
lock of object.
5) ArrayLis tuses Iterator interface to traverse 5) Vector uses Enumeration interface to
the elements. traverse the elements. But it can use Iterator
also
Example of Java Vector:
import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection Umesh
v.addElement("irfan");//method of Vector Irfan
v.addElement("kumar"); kumar
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements())
{ System.out.println(e.nextElement());
}}}
Linked list:
A linked list contains a group of elements in the form of nodes. Each node will have three fields-
the data field contatins data and the link fields contain references to previous and next nodes.
import java.util.*;
list_2.add(10);
list_2.add(20);
list_2.addFirst(5);
list_2.addLast(25);
list_2.offer(2);
list_2.offerFirst(1);
list_2.offerLast(10);
list_2.push(40);
list_1.addAll(list_2);
System.out.println("List_1: " + list_1);
System.out.println("List_2: " + list_2);
}
}
E:\pgms>javac LinkedListExample.java
Note: LinkedListExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
E:\pgms>java LinkedListExample
List_1: [40, 1, 5, 10, 20, 25, 2, 10]
List_2: [40, 1, 5, 10, 20, 25, 2, 10]
TreeSet class:
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements the NavigableSet interface. The objects of the TreeSet class are stored in
ascending order.
TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-
Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time.
The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height
never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient
data structures in order to keep the large data that is sorted and also to do operations on it.
TreeSet class:
TreeSet( ) - Creates an empty TreeSet in which elements will get stored in default natural
sorting order.
TreeSet(Collection c) - Creates a TreeSet with given collection of elements.
TreeSet(Comparator c) - Creates an empty TreeSet with the specified sorting order.
TreeSet(SortedSet s) - This constructor is used to convert SortedSet to TreeSet.
Methods of TreeSet:
Method Description
boolean add(E element) Appends given element to the TreeSet.
boolean addAll(Collection c) Appends given collection of elements to the TreeSet.
E First( ) Returns the first (smallest) element from the invoking
TreeSet.
Method Description
E last( ) Returns the last (largest) element from the invoking TreeSet.
E higher(E obj) Returns the largest element e such that e>obj. If it does not
found returns null.
E lower(E obj) Returns the largest element e such that e<obj. If it does not
found returns null.
E ceiling(E obj) Returns the smallest element e such that e>=obj. If it does not
found returns null.
E floor(E obj) Returns the largest element e such that e<=obj. If it does not
found returns null.
SortedSet subSet(E fromElement, Returns a set of elements that lie between the given range
E toElement) which includes fromElement and excludes toElement.
boolean remove(Object element) Removes the first occurence of the given element from the
invoking TreeSet.
boolean removeAll(Collection c) Removes all the elements those are in the specified collection
from the invoking TreeSet.
void clear( ) Removes all the elements from the TreeSet.
int size( ) Returns the total number of elements in the invoking TreeSet.
boolean isEmpty( ) Returns true if the TreeSet is empty otherwise returns false.
boolean equals( ) Compares the specified object with invoking TreeSet
collection for equality.
boolean contains(Object element) Returns true if the HashSet contains given element otherwise
returns false.
Example:
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
HashtTable:
In java, the package java.util contains a class called Hashtable which works like a HashMap but
it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with a
value. Any non-null object can be used as a key or as a value. We can use the key to retrieve the
value back when needed.
The Hashtable class is no longer in use, it is obsolete. The alternate class is HashMap.
The Hashtable class is a concrete class of Dictionary.
The Hashtable class is synchronized.
The Hashtable does no allow null key or value.
The Hashtable has the initial default capacity 11.
The Hash table data structure stores elements in key-value pairs where
Key- unique integer that is used for indexing the values
Value - data that are associated with keys.
S. No. Methods with Description
1. V put(K key, V value) It inserts the specified key and value into the hash table.
2. void putAll(Map m)) It inserts all the elements of Map m into the invoking
Hashtable.
3. V get(Object key) It returns the value associated with the given key.
4. V remove(Object key) It returns the value associated with given key and
removes the same
5. boolean remove(Object key, It removes the specified values with the associated
Object value) specified keys from the hashtable.
6. boolean contains(Object value) It returns true if the specified value found within the hash
table, else return false.
7. V replace(K key, V value) It replaces the specified value for a specified key
8. void clear() It is used to remove all the lements of a Hashtable.
9. int size( ) It returns the total number of elements in the Hashtable.
10. boolean equals(Object o) It is used to compare the specified Object with the
Hashtable.
11. boolean isEmpty( ) It returns true if Hashtable has no elements; otherwise
returns false.
import java.util.*;
class HashTable { Output:
public static void main(String args[])
{ {15=5643, 3=321, 123=432}
Hashtable<Integer, Integer>
ht = new Hashtable<Integer, Integer>();
ht.put(123, 432);
ht.put(12, 2345);
ht.put(15, 5643);
ht.put(3, 321);
ht.remove(12);
System.out.println(ht);
}}
Properties class:
Properties class is used to maintain the data in the key-value form. It takes both key and value as a
string. Properties class is a subclass of Hashtable. It provides the methods to store properties in a
properties file and to get the properties from the properties file. System.getProperties() returns the
all system properties.
Method Description
public void load(Reader r) It will load data from the Reader object.
public void load(InputStream is) It will load data from the InputStream object
It will load all of the properties represented
public void loadFromXML(InputStream in) by the XML document on the specified input
stream into this properties table.
public String getProperty(String key) It will return value based on the key.
public String getProperty(String key, String It will search for the property with the
defaultValue) specified key and return the value.
public void setProperty(String key, String value) It will call the put method of Hashtable.
public void store(OutputStream os, String It will write the properties in the
comment) OutputStream object.
public void storeToXML(OutputStream os, It will write the properties in the writer object
String comment) for generating XML documents.
Example:
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
public class PropetiesTest {
public static void main(String[] args) {
}
}
Output:
Prpperty: password, Property Value: oracle
Prpperty: database, Property Value: oracle10g
Prpperty: username, Property Value: system
Priority Queue:
Methods of PriorityQueue:
add() - Inserts the specified element to the queue. If the queue is full, it throws
an exception.
offer() - Inserts the specified element to the queue. If the queue is full, it returns false.
remove() - removes the specified element from the queue
poll() - returns and removes the head of the queue
peek() - returns the head of the queue.
toArray() - Converts a priority queue to an array and returns it.
size() - Returns the length of the priority queue
contains(element) - Searches the priority queue for the specified element. If the element
is found, it returns true, if not it returns false.
Example:
import java.util.PriorityQueue;
class Main {
public static void main(String[] args) {
Accessed Element: 1
ArrayDeque:
ArrayDeque class to implement queue and deque data structures using arrays.
Creation of ArrayDeque
Methods of ArrayDeque:
add() - inserts the specified element at the end of the array deque
addFirst() - inserts the specified element at the beginning of the array deque
addLast() - inserts the specified at the end of the array deque (equivalent to add())
offer() - inserts the specified element at the end of the array deque
offerFirst() - inserts the specified element at the beginning of the array deque
offerLast() - inserts the specified element at the end of the array deque
getFirst() - returns the first element of the array deque
getLast() - returns the last element of the array deque
peek() - returns the first element of the array deque
peekFirst() - returns the first element of the array deque (equivalent to peek())
peekLast() - returns the last element of the array deque
poll() - returns and removes the first element of the array deque
pollFirst() - returns and removes the first element of the array deque (equivalent to poll())
pollLast() - returns and removes the last element of the array deque
remove() - returns and removes an element from the first element of the array deque
remove(element) - returns and removes the specified element from the head of the array deque
removeFirst() - returns and removes the first element from the array deque (equivalent
to remove())
removeLast() - returns and removes the last element from the array deque
Example:
class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();
// Using add()
animals.add("Dog");
animals.add("elephant"); ArrayDeque: [Cat, Dog, elephant, chitha, rabbit, Horse]
animals.add("chitha");
animals.add("rabbit"); ArrayDeque: [Dog, elephant, rabbit, Horse]
// Using addFirst()
animals.addFirst("Cat");
// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
animals.remove("chitha");
animals.poll();
System.out.println("ArrayDeque: " + animals);
}
}
StringTokenizer:
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.
Constructors of StringTokenizer:
Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified string.
StringTokenizer(String str, It creates StringTokenizer with specified string and delimiter.
String delim)
StringTokenizer(String str, It creates StringTokenizer with specified string, delimiter and
String delim, boolean returnValue. If return value is true, delimiter characters are
returnValue) considered to be tokens. If it is false, delimiter characters serve
to separate tokens.
Methods of the StringTokenizer Class:
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
int countTokens() It returns the total number of tokens.
Example
import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer
class"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
Demonstrating
methods
from
StringTokenizer
class
BitSet:
The Java BitSet class implements a vector of bits. The BitSet grows automatically as more bits
are needed. The BitSet class comes under java.util package. The BitSet class extends the Object
class and provides the implementation of Serializable and Cloneable interfaces.
Each component of bit set contains at least one Boolean value. The contents of one BitSet may be
changed by other BitSet using logical AND, logical OR and logical exclusive OR operations. The
index of bits of BitSet class is represented by positive integers.
Each element of bits contains either true or false value. Initially, all bits of a set have the false
value.
import java.util.BitSet;
public class BitSetDemo {
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output:
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Date:
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated.
Important Methods
boolean after(Date date) : Tests if current date is after the given date.
boolean before(Date date) : Tests if current date is before the given date.
int compareTo(Date date) : Compares current date with given date. Returns 0 if the
argument Date is equal to the Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after the Date argument.
long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00
GMT represented by this Date object.
void setTime(long time) : Changes the current date and time to given time.
Example:
import java.util.Date;
public class DateDemo {
}
}
Output:
Tue Jan 01 05:31:30 IST 2023
change date:Thu Jan 01 11:09:05 IST 1970
Calendar class:
Calendar class is an abstract class in Java that provides methods for multiple operations such as
displaying the year, month, day, hour, etc. It inherits the Object class and implements the
Comparable, Serializable, and Cloneable interfaces.
Calendar’s getInstance method returns a Calendar object whose calendar fields have been
initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();
Example:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args)
{ Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
Output:
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019
Example
int day = calendar.get(Calendar.DATE);
Formatter:
The Formatter is a built-in class in java used for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output in java programming.
The Formatter class is defined as final class inside the java.util package.
The Formatter class implements Cloneable and Flushable interface.
Java Date Format
There are two classes for formatting dates in Java: DateFormat and SimpleDateFormat.
The java.text.DateFormat class provides various methods to format and parse date and time in
java in language-independent manner. The DateFormat class is an abstract class. java.text. The
Format is the parent class and java.text.SimpleDateFormat is the subclass of java.text.DateFormat
class.
In Java, converting the date into the string is called formatting and vice-versa parsing. In other
words, formatting means date to string, and parsing means string to date.
final String format(Date date) converts given Date object into string.
static final DateFormat getInstance() returns date/time formatter with short formatting style for
date and time.
Example:
import java.util.*;
import java.text.*;
class FormatDemo {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
String y = dateFormat.format(cal.getTime());
System.out.println(y);
}
}
Output:
06:30
Applet: Basics, Architecture, Applet Skeleton, requesting repainting, using the status window, passing
parameters to applets
GUI Programming with Swings – The origin and design philosophy of swing, components and containers,
layout managers, event handling, using a push button, jtextfield, jlabel and image icon, the swing buttons, jtext
field, jscrollpane, jlist, jcombobox, trees, jtable, An overview of jmenubar, jmenu and jmenuitem, creating a
main menu, showmessagedialog, showconfirmdialog, showinputdialog, showoptiondialog, jdialog, create a
modeless dialog.
Accessing Databases with JDBC: Types of Drivers, JDBC Architecture, JDBC classes and Interfaces, Basic
steps in developing JDBC applications, Creating a new database and table with JDBC.
Applet:
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Applet Architecture:
1) An applet is a window-based program.
2) Applets are event driven
An applet waits until an event occurs. The run-time system notifies the applet about an
event by calling an event handler that has been provided by the applet. Once this happens, the
applet must take appropriate action and then quickly return.
3) The user initiates interaction with an applet—not the other way around.
The user interacts with the applet as he or she wants, when he or she wants. These
interactions are sent to the applet as events to which the applet must respond.
Examples:
when the user clicks the mouse inside the applet’s window, a mouse-clicked event is
generated.
If the user presses a key while the applet’s window has input focus, a keypress event is
generated.
applets can contain various controls, such as push buttons and check boxes. When the
user interacts with one of these controls, an event is generated.
Types of applets
A web page can contain two types of applets:
1. Local applet
2. Remote applet
Local applets
Local applets are developed and stored locally, and therefore do not require an Internet
connection to be located because the directory is located on the local system.
<applet
codebase = " MyAppPath "
code = "FaceApplet.class"
width = 120
height = 120>
</applet>
Remote applets
Remote applets are stored in a remote computer and an Internet connection is needed to access
them. The remote applet is designed and developed by other developers. To find and load a
remote applet, you need to know the address of the network applet, i.e., the Uniform Resource
Locator (URL).
<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>
Local Applet is available on our computer. Remote Applet is not available on our computer.
In order to use it or access it, we don't In order to use it or access it on our computer, we
need Internet Connection. need an Internet Connection.
Whenever an applet class is created, an instance of it gets created thereby allowing us to use all
the methods of the class. In applet, there is no need of calling a method explicitly, these are
automatically invoked by the browser.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
Application
They are similar to Java programs.
They can be executed independently without using web browser.
It requires a ’main’ function for it to be executed.
Java applications have full access to local file system and network.
They can access all kinds of resources that are available to the system.
They can execute the programs with the help of the local system.
An application program is required when a task needs to be directly performed for the user.
Applets
They are small Java programs.
They have been designed to be included with HTML documents.
They need Java enabled web browser to be executed.
It doesn’t need a main function to get executed.
It doesn’t have local disk and network access.
It can access the browser specific services only.
They can’t access the local system.
They can’t execute programs from local machines.
It is required to perform small tasks or it can be used as a part of a task.
Example:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Java AWT:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java. Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components are using
the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extend Container class are known as container such as
Frame, Dialog and Panel.
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.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
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 m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
Introduction to swings
Swing Features:
Light Weight − Swing components are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
Highly Customizable − Swing controls can be customized in a very easy way as visual
apperance is independent of internal representation.
Pluggable look-and-feel − SWING based GUI Application look and feel can be changed
at run-time, based on available values.
Container Class
Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.
Does not support pluggable look and feel Supports pluggable look and feel
Heavyweight Lightweight
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
Model represents component's data.
View represents visual representation of the component's data.
Controller takes the input from the user on the view and reflects the changes in
Component's data.
Swing component has Model as a seperate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.
Layout Managers
A layout manager arranges the child components of a container. It positions and sets the size of
components within the container’s display area according to a particular layout scheme. The
layout manager’s job is to fit the components into the available area while maintaining the
proper spatial relationships among the components. Swing comes with a few standard layout
managers that will collectively handle most situations; you can make your own layout
managers if you have special requirements.
FlowLayout
The FlowLayout manager is the default Layout Manager for Applets and Panels. It is the most
basic of the layout managers. It places components, left to right, within the container. If it runs
out of room on one "line," it wraps around to the next line.
BorderLayout
The BorderLayout manager is the default Layout Manager for Frames. It places one component
in the center of the Frame and four components at the top, bottom, left, and right margins.
GridLayout
The GridLayout manager tiles the enclosing container. It organizes components in a two-
dimensional grid, specified in the constructor. Components are added, beginning with the top
left corner, left to right, from top row to bottom row.
GridBagLayout
It is a strong layout that organizes all the components into a grid of cells and keeps the object's
aspect ratio even when the container is modified. The size of the cells in this arrangement may
vary. It allocates components with a constant horizontal and vertical spacing. Using this
feature, we can set a default alignment for elements inside the columns or rows.
Event handling:
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events. Let's have a brief
introduction to this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provides classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event and then
returns.
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
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.
Constructor Description
JButton() It creates a button with no text and icon.
Output:
JCheckBox:
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration
Constructor Description
JCheckBox(String text, boolean Creates a check box with text and specifies whether or
selected) not it is initially selected.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
JRadioButton:
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
import javax.swing.*;
public class RadioButtonExample
{ JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
JLabel:
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.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JTextField:
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JTextArea:
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
Constructor Description
JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified number of rows and
int column) columns that displays specified text.
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:
JList:
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.
Constructor Description
Output:
JComboBox:
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
Constructor Description
import javax.swing.*;
public class ComboBoxExample
{ JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
} }
Output:
JScrollPane:
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane(Component,
int, int)
import java.awt.FlowLayout;
import javax.swing.JFrame;
import
javax.swing.JScrollPane;
import javax.swing.JtextArea;
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROL
LBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBA
R_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
Java Database Connectivity (JDBC) is an application programming interface (API) for the
programming language Java, which defines how a client may access any kind of tabular data,
especially relational database. It is part of Java Standard Edition platform, from Oracle
Corporation. It acts as a middle layer interface between java applications and database. The
JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these programming activities:
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4
types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1
driver is also called Universal driver because it can be used to connect to any of the databases.
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Type-2 driver:
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −
Type 1 − JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2 − JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed
on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 − JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type 4 − 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.