Java Notes 2021
Java Notes 2021
Java Notes 2021
Unit – I
Java versions
Java Essentials:
Java produces applets (browser-run programs), which facilitate graphical user interface (GUI) and
object interaction by internet users. Prior to java applets, Web pages were typically static and non-
interactive. Java applets have diminished in popularity with the release of competing products, such as
Adode Flash and Microsoft Silver light.
Java applets run in a Web browser with Java Virtual Machine (JVM), which translates Java byte
code into native processor instructions and allows indirect OS or platform program execution.JVM
provides the majority of components needed to run byte code, which is usually smaller than executable
programs written through other programming languages. Byte code cannot run if a system lacks required
JVM.
Java program development requires a Java software development kit(SDK) that typically includes a
compiler, interpreter, documentation generator and other tools used to produce a complete application.
Development time may be accelerated through the use of integrated development environments
(IDE)-such as JBuilder, Netbeans, Eclipse or JCreator. IDEs facilitate the development of GUIs, which
include buttons, text boxes, panels, frames, scrollbars and other objects via drag-and-drop and point-and-
click actions.
3. Strings:
Strings also form an essential part of java programming. Implementations of concatenation,
searching parts of string etc. are an important part of Java and prove on to be highly useful
programming tools in the long run.
5. Methods:
There are many instances when similar tasks need to be carried out multiple times within a
program. Functions or methods come handy here. You will use hundreds of functions when
programming in any language hence it’s crucial to become adept at using them.
6. Classes:
In the real world, you will find many similar objects of the same kind. Java is essentially an
object-oriented language, an aspect of it which differentiates it from many low-level programming
languages such as C. Let’s take the example of a bicycle in the real world. Bicycles share properties
of having two wheels, a seat etc. We can say that someone’s bicycle is an instance of the class of
objects, bicycles. Even when programming in Java, you might have to create classes that contain
similar attributes and functions within them. Objects of that class can be called in a variety of
situations to make programming efficient, simpler and more concise.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries
+ other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Java C++
Java is pure object oriented programming C++ is semi object oriented language because
language. We can't design and develop our we can design and develop our programs and
programs and applications without object. applications, with and without object.
Java is Dynamic, Java allocates memory at run- C++ is static, C++ allocates memory at
time. compile-time.
Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.
Java does not support default argument value. C++ does support default argument value.
Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.
Java Features
1. Simple
2. Object-Oriented
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
2. Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
4. Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
Programming in Java P.SowmyaSree Page 6
5. Robust
6. 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.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
8. 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.
9. Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Programming in Java P.SowmyaSree Page 7
10. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.
11. Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
In this page, we will learn how to write the simple program of java. We can write a simple hello java
program easily after installing the JDK.
To create a simple java program, you need to create a class that contains the main method. Let's understand
the requirement first.
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.
o Create the java program
o Compile and run the java program
Let's create the hello java program: open the notepad and ttype the following code
1. class Simple
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello Java");
6. }
7. }
save this file as Simple.java
Output:
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte code.
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories -
> notepad and write a simple program as displayed below:
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
Class loader
Bytecode verifier
Interpreter
Runtime
Hardware
After the file is compiled successfully, byte code(.class file) is generated by the Compiler. When byte
code(.class file) is executed, the following steps are performed at runtime:
• Class loader which is in subsystem of JVM(Java Virtual Machine) loads the java class.
• Byte Code verifier checks the code fragments for illegal codes that can violate access right to the
object.
• Interpreter reads the byte code stream and then executes the instructions, step by step.
Data Types:
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648
(-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value
is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is
0.0F.
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Type casting is when you assign a value of one primitive data type to another type.
Example program
class MyClass
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}
}
Output:
D:\sowmya\javaprg>javac MyClass.java
D:\sowmya\javaprg>java MyClass
9
9.0
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example program
public class MyClass1
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}
}
Output:
D:\sowmya\javaprg>javac MyClass1.java
D:\sowmya\javaprg>java MyClass1
9.78
9
Branching Statements:
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
Syntax:
if(condition)
{
//code to be executed
}
Example program on if
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{ Output:
System.out.println("C grade");
D:\sowmya\javaprg>javac IfElseIfExample.java
}
D:\sowmya\javaprg>java IfElseIfExample
else if(marks>=70 && marks<80)
C grade
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
Syntax:
if(condition)
D:\sowmya\javaprg>javac JavaNestedIfExample2.java
D:\sowmya\javaprg>java JavaNestedIfExample2
You are not eligible to donate blood
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
Loops
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
o for loop
o while loop
o do-while loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it
is recommended to use for loop.
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false. It must return boolean value either true or false. It
is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
Syntax:
for(initialization;condition;incr/decr)
{
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
Statement
}
Output:
D:\sowmya\javaprg>javac NestedForExample.java
D:\sowmya\javaprg>java NestedForExample
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
for-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array)
{
//code to be executed
}
Output:
D:\sowmya\javaprg>javac ForEachExample.java
D:\sowmya\javaprg>java ForEachExample
12
23
44
56
78
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we
have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr)
{
//code to be executed
}
Output:
D:\sowmya\javaprg>javac LabeledForExample.java
D:\sowmya\javaprg>java LabeledForExample
1 1
1 2
1 3
2 1
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop.
Syntax:
while(condition)
{
//code to be executed
}
Output:
Example program on while loop
D:\sowmya\javaprg>javac WhileExample.java
D:\sowmya\javaprg>java WhileExample
class WhileExample 1
{ 2
3
public static void main(String[] args) 4
{ 5
6
int i=1; 7
while(i<=10) 8
{ 9
10
System.out.println(i);
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do
{
//code to be executed
}while(condition);
D:\sowmya\javaprg>javac DoWhileExample.java
class DoWhileExample D:\sowmya\javaprg>java DoWhileExample
{ 1
public static void main(String[] args) 2
3
{ 4
int i=1; 5
6
do{
7
System.out.println(i); 8
i++; 9
10
}while(i<=10);
}
}
Classes
A class is an entity that determines how an object will behave and what the object will contain.
In other words, it is a blueprint or a set of instruction to build a specific type of object.
Syntax: class Declaration
class <class_name>
{
field;
method;
Object:
An object is nothing but a self-contained component which consists of methods and properties to make a
particular type of data useful. Object determines the behavior of the class. When you send a message to an
object, you are asking the object to invoke or execute one of its methods.
From a programming point of view, an object can be a data structure, a variable or a function. It has a
memory location allocated. The object is designed as class hierarchies.
class Student{
//defining fields
int id=15;//field or data member or instance variable
String name="Sowmya";
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println("id="+s1.id);//accessing member through reference variable
System.out.println("name="+s1.name);
}
}
Output:
D:\sowmya\javaprg>javac Student.java
D:\sowmya\javaprg>java Student
id=15
name=Sowmya
Method calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).
class Student
{
int rollno; Output:
String name;
void insertRecord(int r, String n) D:\sowmya\javaprg>javac TestStudent4.java
{ D:\sowmya\javaprg>java TestStudent4
rollno=r; 111 kiran
name=n; 222 Raju
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class TestStudent4
Method overloading:
If two or more method in a class have same name but different parameters, it is known as method
overloading. Overloading always occur in the same class
Method overloading is one of the ways through which java supports polymorphism. Method overloading
can be done by changing number of arguments or by changing the data type of arguments. If two or more
method have same name and same parameter list but differs in return type are not said to be overloaded
method
class Calculate
{ Output:
void sum (int a, int b)
{ D:\sowmya\javaprg>javac Calculate.java
D:\sowmya\javaprg>java Calculate
System.out.println("sum is "+(a+b)) ;
sum is 13
} sum is 8.4
void sum (float a, float b)
{
System.out.println("sum is "+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
Characteristics of constructor
Types of Constructor
• Default Constructor
• Parameterize Constructor
Default Constructor:
Syntax
<class_name>()
{
}
class Employee
{
int Id;
String Name;
int Age;
long Salary;
void PutData()
{
System.out.print("\n\tEmployee Id : "+Id);
System.out.print("\n\tEmployee Name : "+Name);
System.out.print("\n\tEmployee Age : "+Age);
System.out.print("\n\tEmployee Salary : "+Salary);
}
}
}
Output:
D:\sowmya\javaprg>javac Employee.java
D:\sowmya\javaprg>java Employee
Employee Id : 2
Employee Name : Sumit
Employee Age : 31
Constructor Overloading:
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
void Display()
{
System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks);
}
}
class ConstructorOverloading
{
public static void main(String[] args)
{
Student S1 = new Student(1,"Kumar",78.53);
Student S2 = new Student("Sumit",89.42,2);
System.out.print("\n\tRoll\tName\tMarks\n");
S1.Display();
S2.Display();
Programming in Java P.SowmyaSree Page 34
}
}
The static keyword in Java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an
instance of the class.
Syntax
static <datatype><variable_name>;
Output:
Example program:
D:\sowmya\javaprg>javac StaticVariable1.java
class Student D:\sowmya\javaprg>java StaticVariable1
{ 111 Kiran AV College
int rollno;//instance variable 222 Ramu AV College
String name;
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
s1.display();
s2.display();
}
}
static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
{
System.out.println("Hello main");
}
}
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.
The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
Example
class Student
{ Output:
introllno;
String name; C:>javac TestThis2.java
float fee;
C:>java TestThis2
Student(introllno,Stringname,float fee) 111 ankit 5000
{ 112 sumit 6000
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();
}
}
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.
Example Program
class A{ Output:
void m(){System.out.println("hello m");}
void n(){ C:>javac TestThis4.java
System.out.println("hello n"); c:>java TestThis4
//m();//same as this.m() hello n
hello m
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Example Program
class A
{ Output:
A()
{ C:>javac TestThis5.java
System.out.println("hello a"); c:>java TestThis5
hello a
} 10
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}}
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
We can declare, instantiate and initialize the java array together by:
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.
for(data_type variable:array)
{
//body of the loop
}
Example:
Syntax
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example Program:
class Testarray3
{
public static void main(String args[]) Output:
{
C:>javac Testarray3.java
//declaring and initializing 2D array C:>java Testarray
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 1 2 3
//printing 2D array 2 4 5
4 4 5
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable
and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data
members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group
classes and interfaces in one place only.
Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
extends Keyword
extends is the keyword used to inherit the properties of a class.
Syntax:
class Base
{
.....
.....
}
class Derived extends Base
{
.....
.....
}
In java programming, multiple and hybrid inheritance is supported through interface only.
1.Single inheritance: In single inheritance, subclasses inherit the features of one superclass.
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{System.out.println("barking...");}
}
classBabyDog extends Dog
{
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2
{ Output:
public static void main(String args[])
{ C:>javac TestInheritance2.java
BabyDog d=new BabyDog(); C:>java TestInheritance2
d.weep(); Weeping…
d.bark(); barking…
d.eat(); eating…
}
}
3.Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one sub class
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{System.out.println("barking...");}
}
class Cat extends Animal
5.Hybrid Inheritance:
Note :For examples of multiple and hybrid inheritance refer interface topic :
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
class Vehicle
{
//defining a method
void run()
{System.out.println("Vehicle is running");}
} Output:
//Creating a child class
class Bike2 extends Vehicle C:>javac Bike2.java
C:>java Bike2
{
//defining the same method as in the parent class Bike is running safely
void run()
{System.out.println("Bike is running safely");}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.
Example:
class Animal
{ Output:
String color="white";
} C:>javac TestSuper1.java
class Dog extends Animal C:>java TestSuper1
{ black
String color="black"; white
voidprintColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.
Example:
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{ Output:
void eat()
{System.out.println("eating bread...");} C:>javac TestSuper2.java
void bark() C:>java TestSuper2
{System.out.println("barking...");} eating…
void work() barking…
{
super.eat();
The super keyword can also be used to invoke the parent class constructor.
Example:
class Animal
{
Animal() Output:
{System.out.println("animal is created");}
} C:>javac TestSuper3.java
class Dog extends Animal C:>java TestSuper3
{ animal is created
Dog() dog is created
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Final Keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
1. variable
2. method
If you make any variable as final, you cannot change the value of final variable(It will be constant).
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 you type the text and send the message. You don't know the internal processing about the
message delivery.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
A method which is declared as abstract and does not have implementation is known as an abstract method.
Syntax
Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>
{
a class extends another class, an interface extends another interface, but a class implements an interface.
interface Printable
{
void print();
Output:
}
interface Showable C:>javac A7.java
{ C:>java A7
void show(); Hello
} Welcome
class A7 implements Printable,Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
Programming in Java P.SowmyaSree Page 57
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Difference between abstract class and interface
Creating package:
While creating a package, you should choose a name for the package and include a package statement
along with that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement
in each source file, and it applies to all types in the file.
javac -d . Simple.java
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.
Access Protection
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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.
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is
the reverse process of autoboxing.
String is a sequence of characters. In java, objects of String are immutable which means a constant and
cannot be changed once created.
Creating a String
There are two ways to create string in Java:
• String literal
String s = “AV College”;
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
Example Program:
Output:
public class CharAtExample
{ C:>javac CharAtExample.java
public static void main(String args[]) C:>java CharAtExample
{ l
String name="hello world";
System.out.println(name.charAt(3));
}
}
String s1="python";
}}
3. String substring(int beginIndex):The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where start index is inclusive and end index is
exclusive. In other words, start index starts from 0 whereas end index starts from 1.
4. boolean contains(CharSequence s): The java string contains() method searches the sequence of characters in
this string. It returns true if sequence of char values are found in this string otherwise returns false.
Example program:
Output:
class ContainsExample
C:>javac ContainsExample.java
C:>java ContainsExample
{ true
public static void main(String args[]) true
false
{
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
Example program:
Output:
public class StringJoinExample C:>javac StringJoinExample.java
{ C:>java StringJoinExample
welcome-to-java-language
public static void main(String args[])
{
String joinString1=String.join("-","welcome","to","java language");
System.out.println(joinString1);
}
}
6. boolean equals(Object another) : The java string equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
Example program:
7. boolean isEmpty():The java string isEmpty() method checks if this string is empty or not. It returns true, if length of
string is 0 otherwise false. In other words, true is returned if string is empty otherwise it returns false.
Output:
Example program:
C:>javac IsEmptyExample.java
C:>java IsEmptyExample
public class IsEmptyExample true
{ false
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
8. String concat(String str): The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.
Example program:
public class ConcatExample
{
public static void main(String args[])
{ Output:
String s1="java string"; C:>javac ConcatExample.java
s1.concat("is immutable"); C:>java ConcatExample
java string
System.out.println(s1); java string is immutable so
s1=s1.concat(" is immutable so assign it explicitly"); assign it explicitly
System.out.println(s1);
}}
9. String replace(char old, char new): The java string replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.
Example program:
Output:
public class ReplaceExample1
C:>javac ReplaceExample1.java
{ C:>java ReplaceExample1
public static void main(String args[]) Jeve is e progremming lenguege
{
String s1="java is a programming language ";
String replaceString=s1.replace('a','e');
System.out.println(replaceString);
}
}
10. int indexOf(int ch): The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value and from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int returns index position for the given substring and from index
fromIndex)
Example program:
11. String toLowerCase():The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
Example program:
Output:
public class StringLowerExample
{ C:>javac StringLowerExample.java
public static void main(String args[]) C:>java StringLowerExample
{ Java language hello string
String s1="JAVA LANGUAGE HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}
12. String toUpperCase():The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.
Example program:
Output:
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
Exmple Program
2. insert()
It is used to insert the specified string with this string at the specified position.
Exmple Program
Output:
class StringBufferExample2 C:>javac StringBufferExample2.java
{ C:>java StringBufferExample2
public static void main(String args[]) HJavaello
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");
System.out.println(sb);
}}
Exmple program:
Output:
class StringBufferExample3 C:>javac StringBufferExample3.java
{ C:>java StringBufferExample3
public static void main(String args[]) HJavalo
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);
}
}
4. delete():The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
Example Program:
Output:
class StringBufferExample4 C:>javac StringBufferExample4.java
{
C:>java StringBufferExample4
Hlo
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5. reverse() : The reverse() method of StringBuilder class reverses the current string.
Example Program:
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of
the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
Example Program:
Output:
C:>javac StringBufferExample5.java
class StringBufferExample6
C:>java StringBufferExample5
{ 16
public static void main(String args[]) 16
{ 34
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Types of exceptions
we have three Types of Exceptions. You need to understand them to know how exception handling works
in Java.
• Errors − These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at
the time of compilation.
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of Java Exception classes are given below.
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
If an exception occurs at the particular statement of try block, the rest of the block code will
not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax: try
{
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not performing check
up before the code being used.
User-Defined Exception
If you are creating your own Exception that is known as custom exception or user-defined exception. Java
custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Example Program:
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
Output:
public static void main(String args[])
{ D:\sowmya java>javacTestCustomException1.java
try D:\sowmya java>java TestCustomException1
{
validate(13); Output:Exceptionoccured: InvalidAgeException:not valid
} rest of the code..
catch(Exception m)
{
System.out.println("Exception occured: "+m);.
}
System.out.println("rest of the code...");
}
}
Multitasking: Multitasking means running more than one process simultaneously is called Multitasking.
There are two types of multitasking:
• Process based
• Thread based
Process based multitasking : Running more than one processes simultaneously and each process is an
independent process of different application is called process based multitasking. Example, It allows us to
listen music using mp3 player while creating PowerPoint presentation using MS PowerPoint. Both Mp3
player and MS PowerPoint are independent applications.
Thread based multitasking : Running more than one processes simultaneously and each process is an
independent process of same application is called thread based multitasking. Example, While writing MS
word document, MS word can check the spelling and grammatical errors, at the same time it can also
auto-correct these spelling and grammatical errors. Both, error checking and auto-correct are independent
processes and comes under the same application.
Java Multithreading
Thread is an independent process of a single application. In Java, main() method is called the "main
thread" of our application and other program level threads are called child thread.
create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. publicintgetPriority(): returns the priority of the thread.
7. publicintsetPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
We create a class that extends the java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Example program
class Multi extends Thread
{ Output:
public void run()
{ D:\sowmya java>javac Multi.java
System.out.println("thread is running..."); D:\sowmya java>java Multi
} thread is running...
public static void main(String args[]).
{
Multi t1=new Multi();
t1.start();
}
}
Example Program
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
Running State:--
• If the thread is in execution then it is said to be in running state.
• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following conditions arise
1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by
using the resume() method.
2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method.
The sleeping method re-enters runnable state when the time elapses.
3. A thread can be made to wait until a particular event occur using the wait() method, which can be run
again using the notify( ) method.
Blocked State:--
• A thread is said to be in blocked state if it prevented from entering into the runnable state and so the
running state.
• The thread enters the blocked state when it is suspended, made to sleep or wait.
• A blocked thread can enter into runnable state at any time and can resume execution.
Dead State:--
• The running thread ends its life when it has completed executing the run() method which is called
natural dead.
• The thread can also be killed at any stage by using the stop( ) method.
//A.java
public class A extends Thread {
public void run()
{
System.out.println("Thread A");
System.out.println("i in Thread A ");
for(int i=1;i<=5;i++)
{
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Thread A Completed.");
}
}
//Main.java
public class Main
{
public static void main(String[] args)
{
//life cycle of Thread
// Thread's New State
A threadA = new A();
B threadB = new B();
// Both the above threads are in runnable state
D:\sowmya java>javacMain.java
D:\sowmya java>java Main
Thread A
i in Thread A
i=1
Main Thread End
Thread B
i in Thread B
i=1
i=2
i=3
i=4
i=5
Thread B Completed.
i=2
i=3
i=4
i=5
Thread A Completed.
Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which scheduling it chooses.
In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data
and another thread which is reading data at the same time, might create inconsistency in the application.
When there is a need to access the shared resources by two or more threads, then synchronization approach
is utilized.
Java has provided synchronized methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block, then no other thread can call that
method on the same object. All threads have to wait till that thread finishes the synchronized block and
comes out of that.
In this way, the synchronization helps in a multithreaded application. One thread has to wait till other
thread finishes its execution only then the other threads are allowed for execution.
Syntax
Synchronized(object)
{
//Block of statements to be synchronized
}
I/O devices are the pieces of hardware used by a human to communicate with a computer.Forinstance
,a keyboard or computer mouse is an input device for a computer ,while monitors and printers are output
devices.
Introduction:
Java performs Input/Output through the concept of Streams.A Stream is a sequence of data like a
stream of water that flows continuously.Java’s IO package mostly concerns itself with the reading of data
from a source and writing of data to a destination.
Source Program Destination
You can either read from stream or write to a stream.A stream is connected to datasource or a data
destination.Streams in java IO can be either byte based (reading and writing bytes) or character based
(reading and writing characters).
Java.io Package:
This package provides for system input and output through data streams, serialization and the file system.
Java defines two types of streams-
1. Byte Stream:It provides a convenient means for handling input and output of byte.
2. Character Stream: It provides a convenient menas for handling input and output of
characters.
Byte Stream Classes:
Byte stream is defined by using two abstract class at the top of hierarchy-
o InputStream
o OutputStream
Character Stream Classes: It is also defined by using two abstract class at the top of hierarchy-
• Reader
• Writer
File class: Files are a common source or destination of data in Java application. The file class is an
abstract representation of file and directory pathname. A pathname can be either absolute or relative. The
file class have several methods for working with directories and files,deleting and renaming directories or
files ,listing the contents of directory etc.
Creation of File Object: A File object is created by passing in a String that represents the name of a file,
or a String or another File object.
For Example: File f1=new File(“testFile.txt”);
Constructors:
Constructor Description
File(File parent,String child) It creates new File instance from a parent pathname and a
child pathname string.
File(Sting pathname) It creates a new File instance by converting the given
pathname string into an pathname.
File(String parent,String child) It creates a new File instance from a parent pathname string
and a child pathname string.
File(URL url) It creates a new File instance by converting the given
file:URL into an pathname.
Methods:
Modifier and Type Method Description
static File createTempFile(String prefix,String It creates an empty file in the
suffix) default temporary file directory,
using the given prefix and suffix to
generate its name.
boolean createNewFile() It automatically creates a new,
empty file named by this abstract
pathname if and only if a file with
this name does not yet exist.
boolean canWrite() It tests whether the application can
modify the file denoted by this
abstract pathname.String[]
boolean canExecute() It tests whether the application can
execute the file denoted by this
abstract pathname.
boolean canRead() It tests whether the application can
read the file denoted by this
abstract pathname.
boolean isAbsolute() It tests whether this abstract
pathname is absolute.
boolean isDirectory() It tests whether the file denoted by
this abstract pathname is a
directory.
boolean isFile() It tests whether the file denoted by
this abstract pathname is an normal
file.
String getName() It returns the name of the file or
directory denoted by this abstract
pathname.
String getParent() It returns the pathname string of
this abstract pathname’s parent,or
null if this pathname does not
name a parent directory.
declaration
public class FileInputStream extends InputStream
Methods:
Method Description
int available() It is used to return the estimated number of bytes that can be
read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int off, intlen) It is used to read up to len bytes of data from the input
stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
FileChannelgetChannel() It is used to return the unique FileChannel object associated
with the file input stream.
FileDescriptorgetFD() It is used to return the object.
protected void finalize() It is used to ensure that the close method is call when there
is no more reference to the file input stream.
void close() It is used to closes the stream.
declaration
public class FileOutputStream extends OutputStream
methods
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array
to the file output stream.
void write(byte[] ary, int off, intlen) It is used to write len bytes from the byte array starting
at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannelgetChannel() It is used to return the file channel object associated
with the file output stream.
FileDescriptorgetFD() It is used to return the file descriptor associated with
the stream.
void close() It is used to closes the file output stream.
FileOutputStream Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}
catch(Exception e) Output:
{
System.out.println(e); D:\sowmya java>javacFileOutputStreamExample .java
} D:\sowmya java>java FileOutputStreamExample
} success...
}
BufferedInputStream Class
Java BufferedInputStream is used to read information from . It internally uses buffer mechanism to make
the performance fast.
The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer automatically refilled from
the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer is created.
declaration
public class BufferedInputStream extends FilterInputStream
constructor
Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it
argument, the input stream IS, for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified
int size) buffer size and saves it argument, the input stream IS,
for later use.
Methods
method
Description
BufferedOutputStream Class:
Java BufferedOutputStream is used for buffering an output stream. It internally uses buffer to store
data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class.
constructors
constructor
Description
BufferedOutputStream(OutputStreamos) It creates the new buffered output stream which is used for
writing the data to the specified output stream.
BufferedOutputStream(OutputStreamos, int It creates the new buffered output stream which is used for
size) writing the data to the specified output stream with a specified
buffer size.
Methods
method
Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, intlen) It write the bytes from the specified byte-input stream into
a specified byte , starting with the given offset
void flush() It flushes the buffered output stream.
RandomAccessFile
This is used for reading and writing to random access file. A random access file behaves like a large of
bytes. There is a cursor implied to the array called file , 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 EOFExceptionis .
It is a type of IOException.
Constructor
Constructor Description
RandomAccessFile(File file,String Creates a random access file stream to read from,and
mode) optionally to write to,the file specified by the File
argument.
RandomAccessFile(String Creates a random access file stream to read from,and
name,String mode) optionally to write to, a file with the specified name.
Methods
Modifier and Type Method Description
void close() It closes this random access
file stream and releases any
system resources associated
with the stream
FileChannel getChannel() It returns the unique
FileChannel object associated
with this file.
int reading() It reads a signed 32-bit integer
from this file.
String readUTF() It reads in a string from this
file.
void seek(long pos) It sets the file-pointer offset,
measured from the beginning
of this file, at which the next
read or write occurs.
void writeDouble(double v) It converts the double
argument to along using the
doubleToLongBits method in
class Double, and then writes
that long value to the file as an
Introduction:
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. It Secured and can be executed by browsers running under
many platforms, including Linux, Windows, Mac Os etc. Plug-in is required at client browser to execute
applet
Java Plug-in is required in the browser at client side to execute applet. Java Plug-in is a software
product that serves as a bridge between a browser and an external Java Runtime Environment (JRE).
1. java.awt.*: Imports the Abstract Window Toolkit (AWT)classes. Applets interact with the
user(either directly or indirectly)through the AWT. The AWT contains support for a window-based,
graphical user interface.
2. The java.applet.*: Imports the applet package, which contains the class Applet. Every applet that
you create must be a subclass of Applet class.
import java.applet.Applet;
import java.awt.Graphics;
//Every applet must extend from java.applet.Applet class
public class HelloWorldApplet extends Applet
{
//paint method is called every time applet redisplay its output
public void paint(Graphics g)
{
g.drawString("Hello World",50,50);
}
}
3. Create a html file, example “HelloWorldApplet.html” and place the applet code in html file.
<html>
<body>
<applet code="HelloWorldApplet.class" width="300" height="300">
</applet>
</body>
</html>
Programming in Java P.SowmyaSree Page 100
4. There are two ways to run an applet.
❖ Executing the Applet within Java-compatible web browser. For executing an Applet in an
web browser, create short HTML file in the same directory and Run the HTML file then the
output is as follows:
❖ Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes
your applet in a window.
5. Execute the applet using applet viewer tool at command prompt as shown below-
D:\sowmyajava>appletviewer HelloWorldApplet.html
The class in the program must be declared ad public ,because it will be accessed by code that is outside the
program
Every Every Applet application must declare a paint() method. This method is defined by
AWT class and must be overridden by the applet. The paint( ) method is called each time when an applet
needs to redisplay its output.
Another important thing to notice about applet application is that, execution of an applet does not
begin at main( )method. In fact an applet application does not have any main( ) method.
1. Initial State: When a new applet is born or created, it is activated by calling init( ) method, At
this stage, new objects to the applet are created ,initial values are set, images are loaded and the
colors of the images are set. An applet is initialized only once in its lifetime.
2. Running State:An applet achieves the running state when the system calls the start() method.
This occurs as soon as the applet is initialized. An applet may also start when it is in idle state.
3. Idle State: An applet comes in idle state when its execution has been stopped either implicitly
or explicitly. An applet is implicitly stopped when we leave the page containing the currently
running applet. An applet is explicitly stopped when we call stop() method to stop its execution.
4. Dead State:An applet is in dead state when it has been removed from the memory. This can be
done by using destroy ( ) method.
5. Paint() : Apart from the above stages, Java applet also possess paint( ) method. This method
helps in drawing, writing and creating colored backgrounds of the applet. It takes an argument
of the graphics class. To use The graphics, imports the package java.awt.Graphics.
Applet Class:Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load and play
audio clips.
Most applets override these four methods. These four methods forms Applet lifecycle.
public void init(): init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
public void start(): start( ) method is called after init( ).This method is called to restart an applet after it
has been stopped.
public void stop(): stop( ) method is called to suspend thread that does not need to run when applet is not
visible.
public void destroy(): destroy( ) method is called when your applet needs to be removed completely from
memory.
public void destroy(): destroy( ) method is called when your applet needs to be removed completely from
memory.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void init()
{
setName("My Applet");
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawRoundRect(10,30,120,120,2,3);
}
}
3. Create the html file,example “MyApplet.html” and place the applet code in html file.
<html>
<body>
<applet code="MyApplet.class" width="300" height="300">
</applet>
</body>
</html>
4. Execute the applet using applet viewer tool at command prompt as shown below:
D:\sowmyajava>appletviewer MyApplet.html
Applets are displayed in a window and they use the AWT to perform input and output functions. Below are
the common methods used for displaying the output-
➢ To output a string to an applet, use drawstring( ),which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ).It has the following general form:
voiddrawString(String message,intx,int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location 0,0. The drawString( ) method will not recognize newline characters. If we want to start a line of
text in another line, we must do it manually, specifying the X,Y location where we want the line to begin.
➢ We can obtain the current settings for background and foreground colors by calling getBackground(
) and getForeground( ),respectively.They are also defined by Component and bear the general form:
ColorgetBackground( )
ColorgetForeground( )
importjava.applet.*;
importjava.awt.*;
public class MyApplet1 extends Applet
{
public void init()
{
setName("My Applet");
}
public void paint(Graphics g)
{
setBackground(Color.Green);
setForeground(Color.RED);
g.drawString("Using Colors in Applet",50,100);
}
}
2. Compile the above MyApplet1.java applet.
D:\sowmyajava>javac MyApplet1.java
3. Create the html file,example “MyApplet1.html” and place the applet code in html file
<html>
<body>
<applet code="MyApplet1.class" width="250" height="250"></applet></body>
</html>
D:\sowmyajava>appletviewer MyApplet1.html
Changing the state of an object is known as an event. Event handling is the process of how events
generated in Java GUI application are processed or handled.
Introduction: Any program that uses GUI (Graphical User Interface)such as Java application written for
windows, is event driven. Event describes the change in state of any object.
For Example: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.
Event handling process:A source generates an Event and sends it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and then return. Events are
supported by a number of Java packages, like java.util, java.awt and java.awt.event.
Types of Events:
//EventApplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>
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.
AWT Hierarchy
Component class: Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for remembering the
current foreground and background colors and the currently selected text font.
Container:
The Container is a component in AWT that can contain another component like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
Window:
The window is the containers 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, border or menu bars. It can have other
components like button, textfield etc.
Constructors of Frame:
Constructor Description
public Frame( ) Creates a Frame window with no name.
public Frame(String name) Creates a Frame window with a name.
Frame Methods:
Methods Description
Public void add(Component comp) This method adds the component, comp, to the
container Frame.
Public void setLayout(LayoutManger object) This method sets the layout of the components
in a container, Frame.
Public void remove(Component comp) This method removes a component, comp,
from the container, Frame.
Public void This method sets the size of a Frame in terms
setSize(intwidthPixel,intheightPixel) of pixels.
The default layout of Frame by which it positions the components in it is BorderLayout, manager.
Hence, if we add components to a Frame without calling it’s setLayout( ) method, these components are
automatically added to the center region using BorderLayout manager.
Note: Remember, using the BorderLayout manager, only one component can be placed in a region, hence
if multiple elements are added to a region, only the last element will be visible.
Creating a Frame:
frame.add(label);
frame.add(button);
frame.setSize(250,200);
frame.setVisible(true);
}
public static void main(String args[])
{
new FrameExample();
}
}
Output:
D:\sowmyajava>javac FrameExample.java
D:\sowmyajava>java FrameExample
Button
The button class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed.
D:\sowmyajava>javac ButtonExample.java
D:\sowmyajava>java ButtonExample
Output:
D:\sowmyajava>javac ButtonExample1.java
D:\sowmyajava>java ButtonExample1
Label
Output:
D:\sowmyajava>javac LabelExample.java
D:\sowmyajava>java LabelExample
Checkbox
The Checkbox 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".
Checkbox ClassDeclaration
public class Checkbox extends Component implements ItemSelectable, Accessible
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:
D:\sowmyajava>javac CheckboxExample.java
D:\sowmyajava>java CheckboxExample
Radio Buttons/CheckboxGroup:
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one
check box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits
the object class.
CheckboxGroup Example
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample()
{
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroupcbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg,
false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg,
true);
checkBox2.setBounds(100,150, 50,50);
D:\sowmyajava>javac CheckboxGroupExample.java
D:\sowmyajava>java CheckboxGroupExample
Container Class:
Container is the super class of all Java containers.
Following is the Container class signature-
Layouts:
The java.awt library provides 5 basic layouts. Each layout has its own significance and all of them
are completely different. The 5 layouts available in the java.awt library are:
1. Border Layout.
2. Grid Layout.
3. Card Layout.
4. Flow Layout
BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
D:\sowmyajava>javac Border.java
D:\sowmyajava>java Border
Grid Layout:
A GridLayout is a more organized way of arranging components. It divides the frame or
panel in the form of a grid containing evenly distributed cells. Each component get added to a particular
cell. The order of placement of components is directly dependant on the order in which they are added to
the frame or panel. The below image shows a 2 column 3 row GridLayout based Frame.
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output:
D:\sowmyajava>javac MyGridLayout.java
D:\sowmyajava>java MyGridLayout
Card Layout.
The CardLayout class manages the components in such a manner that only one component is visible
at a time. It treats each component as a card that is why it is known as CardLayout.
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Example program on FlowLayout
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Output:
D:\sowmyajava>javac MyFlowLayout.java
Unit-III
Chapter-4
Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It
is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
No AWT SWING
1 AWT components are platform- Java swing components are platform-
dependent. independent.
2 AWT components are heavyweight. Swing components are lightweight.
3 AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4 AWT provides less components than Swing provides more powerful components
Swing. such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5 AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added to create a
GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Constructors
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfigurationgc) It creates a Frame in the specified GraphicsConfiguration of
a screen device and a blank title.
JFrame(String title) It creates a new, initially invisible Frame with the specified
title.
JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfigurationgc) GraphicsConfiguration of a screen device.
Methods
Modifier Method Description
and type
Adds the specified child Component.
protected addImpl(Component comp,
void Object constraints, int index)
void setContentPane(ContainecontentP
ane) It sets the contentPane property
JFrame Example
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
Output:
D:\sowmyajava>javac FirstSwingExample.java
D:\sowmyajava>java FirstSwingExample
Japplet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet
class extends the Applet class.
<html>
<body>
<applet code="EventJApplet.class" width="300"
height="300">
</applet>
</body>
</html>
Output:
D:\sowmyajava>javac EventJApplet.java
D:\sowmyajava>appletviewer EventJApplet.html
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any other
component. It inherits the JComponents class.
It doesn't have title bar.
Declaration
public class JPanel extends JComponent implements Accessible
JPanel Example
import java.awt.*;
import javax.swing.*;
public class PanelExample
{
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
Jtable: The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable Example
import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTablejt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPanesp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new TableExample();
}
}
Output:
D:\sowmya\javaprg>javac TableExample.java
D:\sowmya\javaprg>java TableExample
The JDialog control represents a top level window with a border and a title used to take some form of input
from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
D:\sowmya\javaprg>javac DialogExample.java
D:\sowmya\javaprg>java DialogExample