Jarusha Java Notes 2024
Jarusha Java Notes 2024
Java Essentials
1. Java environment includes a large number of development tools and hundreds of classes
and methods.
2. Java program development requires a java software development kit SDK , which includes
a compiler, interpreter, documentation generator and other tools like IDE.
3. The development tools are part of the system known as Java Development Kit (JDK) and
the classes and methods are part of Java Standard Library (JSL) also known as the
Application Programming Interface(API).
4. JDK :
It is a collection of tools that are used for developing java programs. It includes:
[Link] ( for viewing java applets)
2. javac (java compiler)
3. java (java interpreter)
4. javap (java disassembler)
5. javah (for c header files)
6. javadoc (for creating html documents)
7. jdb (java debugger)
1. To create a java program, we need to create a source code file using a text editor.
2. The source code is complied using the java compiler javac and executed using java interpreter
java.
3. The java debugger jdb is used to find error .
4. A compiled java program can be converted into a source code with the help of disassembler
javap.
Features of JVM
A. It converts byte code to the machine language.
B. JVM provides basic java functions like memory management, security, garbage collection,
etc.
C. Runs the program by utilizing JRE’s libraries and files.
D. JVM is an integral part of JRE.
E. It can execute the java program line by line. Therefore, it is also known as an interpreter.
F. The main functions of JVM include loading, linking, initializing, and compiling the
program.
G. Note: JVM can’t be installed alone. As JVM is a part of JRE, you need to install JRE. JVM
comes within it.
6. JVM performs the following operations:
A. Loads code
B. Verifies code
C. Executes code
D. Provides runtime environment
7. JVM provides definitions for the following
A. Memory area
B. Class file format
C. Register set
D. Garbage collected heap
E. Fatal error reporting
If there are no syntax errors, the compiler generates a bytecode file with a .class extension
as [Link]
Step 3: Executing a Java Program : use java command to execute the bytecode:
java Welcome output : Welcome to Java
[Link] keyword is used to declare a class in Java.
[Link] keyword is an access modifier that represents visibility. It means it is visible to all.
static :
1. static is a keyword, if we declare any method as static, it is known as static method.
2. no need to create object to invoke the static method
3. Static method are executed only once in the program.
4. main() method of java executes only once throughout the java program execution and hence
it declare must be static.
5. The main method is executed by the JVM, so it doesn't require to create object to invoke the
main method. So it saves memory.
void:
void is the return type of the method. It means it doesn't return any value. main() Method in
Java program execution starts with main(). If any class contain main() method known as main
class.
main() Method :
program execution starts with main(). If any class contain main() method known as main class.
String args[] :
String args[] is a String array used to hold command line arguments in the form of String values.
If any input value is passed through the command prompt at the time of running of the program
is known as command line argument .
By default every command line argument will be treated as string value and those are stored in a
string array of main() method.
[Link]("hello"); -> is output statement.
System –> Class out ->static Object println() –>method
System:
It is the name of standard class that contains objects that encapsulates the standard I/O devices
of your system. It is contained in the package [Link]. (default package)
out:
The object out represents output stream and is the static data member of the class System.
println:
The println() is method of out object that takes the text string as an argument and displays it to
the standard output i.e screen.
Data types
I. Variables are the names given to memory address for storing data values.
Datatype variableName = value; int a = 1000;
II. Data types specify the different sizes and values that can be stored in the variable.
In java, there are 2 types of data types.
1) Primitive data types 2) Non-primitive data types ( Arrays ,Strings, Classes, Interfaces)
1. byte, short, int and long data types are used for storing whole numbers.
2. float and double are used for fractional numbers.
3. boolean data type is used for variables that holds either true or false.
4. char is used for storing characters(letters).
5. String - stores text, such as "Hello". String values are surrounded by double quotes
class Datatype
{
public static void main(String[]args)
{
byte b=10;
char ch = 'A';
short s = 1000;
int m = 23643;
long a = 100000L;
float f1 = 234.5f ;
double d1 = 12.3;
[Link](b);
[Link](ch);
[Link](s);
[Link](m);
[Link](a);
[Link](f1);
[Link](d1);
}
}
D:\>javac Datatype
D:\>java Datetype
Type Casting/type conversion
In java, Converting one primitive datatype into another is known as type casting (type
conversion). There are two ways to convert : Widening and Narrowing.
Widening(Up casting) :
Converting a lower datatype to a higher datatype is known as widening. In this case the
casting/conversion is done automatically by the compiler without user [Link], it
is known as Implicit Type Casting.
publicclassWide
{
publicstaticvoid main(Stringargs[])
{
inti = 100;
floatf = l; // casting from int to float
[Link](f);
} } Output 100.0
Narrowing (down casting):
Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )”
explicitly. Therefore, it is known as Explicit Type Casting.
Variable=(type)variable;
publicclassNarrow
{
publicstaticvoid main(Stringargs[])
{
doubled = 100.04;
longl = (long)d; // casting from double to long
[Link](f);
}
}
Inboxing: conversion of primitive into non-primitive
int x=10;
Integer y=x;
Outboxing: conversion of non-primitive into primitive
Integerx=10;
int y=x;
Note: Integer is class ,int is primitive data type
command-line argument
1. The java command-line argument is an argument that is passed at the time of running the
java program.
2. The arguments passed from the keyboard can be received in the java program and it can
be used as an input.
3. It provides a way to check the behavior of the program for the different values.
4. We can pass both strings and primitive data types(int, double, float, char, etc) as
command-line arguments.
5. The arguments will be converted to strings and passed into the
main method string array argument.
6. In java program, main function accepts string array as an
argument.
7. The args[] contains the total number of arguments.
8. We can check these arguments using [Link] method.
9. The first argument is the file name always.
class Testcmd
{
public static void main(String args[])
{
[Link](" first argument is: " + args[0]);
[Link]("second argument is: " + args[1]);
}
}
Output:
D:\>javac Testcmd
D:\>java Testcmd hello hai
args[0] ->cmd
args[1] -> hello
args[2] ->hai
Syntax:
switch(expression)
{
case value1: code to be executed; break;
case value2: code to be executed; break;
case value3: code to be executed; break;
......
default: execute code if all cases are not matched;
}
Program to show switch
object class
1. An object is a real-world entity. 1. A class is a user defined blueprint or
2. An object is a runtime entity. prototype from which objects are created.
3. The object is an entity which has state 2. It represents thes et of properties or
and behavior. e.g. table,car methods that are common to all objects of
one type.
4. The object is an instance of a class.
3. It is a logical entity.
5. It can be physical or logical (tangible and
4. It can't be physical.
intangible).
A class in Java can contain:
6. Example of intangible object is the banking
1. Fields
system.
2. Methods
7. An object has three characteristics:
3. Constructors
A. State: represents the data (value) of an
4. Blocks
object.
5. Nested classes
B. Behavior: represents the behavior A. class is created using class keyword
(functionality) of an object such as deposit, B. class is created only once and no memory is
withdraw, etc. allocated.
C. Identity: An object identity is typically C. In Java, an object is created from a class.
implemented via a unique ID. The value of
the ID is not visible to the external user.
Objects are created using new keyword
Object is created as many times Create an object called "s" and print the value of
For object memory is allocated when it is created. age:
Create a Class
To create a class, use the keyword class public class Student
Syntax to declare a class: {
class Classname int age = 20;
{ public static void main(String[] args)
Fields declaration; {
Method declaration; Student s = new Student();
} [Link]([Link]);
Example: }
Create a class named "Student" with a variable }
age:
Unit II
Method declaration and invocation
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Use of methods :
To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed
by parentheses (). Java provides some pre-defined methods, such as [Link]()
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
Program:
public class Test
{
void Hello()
{
[Link]("hi");
}
constructors in Java
1. A constructor in Java is a special method that is used to initialize objects.
2. A constructor contains block of statements similar to a method
3. It is invoked when an instance of the object is created, and memory is allocated for the object.
4. It is a special type of method which is used to initialize the object.
5. It can be used to set initial values for object attributes
When is a constructor invoked
A. Every time an object is created using new() keyword, at least one constructor is called.
It calls a default constructor.
B. It is called constructor because it constructs the values at the time of object creation.
C. It is not necessary to write a constructor for a class.
D. It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
1) Constructor name and class name must be same.
2) A Constructor must have no return type.
3) A constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
[Link] constructor (no-arg constructor) [Link] constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
The default constructor is used to provide the default values to the object like 0, null, etc., depending on
the type. If there is no constructor in a class, compiler automatically creates a default constructor.
Syntax
classname( )
{
}
program to show default constructor that displays the default values
class Student3
{
int rno;
String name;
void display()
{
[Link]( rno +" " + name );
}
public static void main(String args[])
{
Student3 s1=new Student3(); //creating objects
Student3 s2=new Student3();
[Link](); //displaying values of the object
[Link]();
}
}
Output:
0 null
0 null
Output:
25 anu
26 priya
Constructor Overloading
1) In Java, a constructor is just like a method but without return type.
2) It can also be overloaded like Java methods.
3) Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists.
4) They are arranged in a way that each constructor performs a different task.
5) They are differentiated by the compiler by the number of parameters in the list and their types.
Program to show Constructor Overloading
class Student5
{
int rno;
String name;
int age;
this keyword
In java, this is a keyword and a reference variable that refers to the current object.
class Testthis
{
public static void main(String args[]){
Student s1=new Student(11,"anu",5000f);
Student s2=new Student(12,"suma",6000f);
[Link]();
[Link]();
}}
Java Array
1. An array is a collection of similar datatype elements that are stored in continuoues memory
location.
2. Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
3. Java array is an object which contains elements of a similar data type. It is a data structure where
we store similar elements. We can store only a fixed set of elements in the array.
4. Array in java is index-based, the first element of the array is stored at the 0 index.
Advantages
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
2. Random access: We can get any data located at an index position.
Disadvantages
1. 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. 1. Single Dimensional [Link] Array
One or single Dimensional Array in Java
An Array defined with one variablename and // Program to show array declare, initialize
with one dimension is known as one class Testarray
dimensional array. {
public static void main(String args[])
Syntax to declare array:
{
dataType[ ] arr;
int a[]=new int[5];
dataType [ ]arr; a[0]=10; //initialization
dataType arr[ ]; a[1]=20;
example: a[2]=70;
int [] a; a[3]=40;
int a[]; a[4]=50;
int []a;
Instantiation of an Array in Java for (int i=0; i<[Link]; i++)
arrayname = new datatype[size]; [Link](a[i]);
a=new int[3]; }
}
We can declare, instantiate and initialize the java Output:
array together by: 10 20 70 40 50
int a[ ]={11,22,33} ;
Examples
int[][] arr = new int[3][5];
Inheritance
Inheritance is a mechanism in which one object extends keyword
acquires all the properties and behaviors of a The keyword used extends is used to create
parent object.
it is used to create new classes from existing derived class from base class.
classes. Syntax :
In new class , you can reuse methods and fields of class baseclass
the parent class and also add new methods and {
fields in child class.( Code Reusability)
//methods and fields
Inheritance represents the IS-A relationship which
is also known as a parent-child relationship. }
Used For Method Overriding (so runtime class derivedclass extends baseclass
polymorphism can be achieved) {
//methods and fields
Super Class: The class whose features are }
inherited is known as superclass/ base class / extends is the keyword used to inherit the
parent class. properties of a class.
Sub Class: The new class that inherits features of The extends keyword indicates that you are
the other class is known as a subclass / derived making a new class that derives from an
class/ extended class /child class.
existing class.
The meaning of "extends" is to increase the
functionality.
Java single Inheritance Example
Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
Program to show single inheritance
import [Link].*;
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main( String args[ ] )
{
Programmer p = new Programmer();
[Link]("Programmer salary is:" + [Link]);
[Link]("Bonus of Programmer is:" + [Link]);
}
}
D:\java>javac [Link]
D:\java>java [Link]
Multiple Inheritance:
1. The process of deriving one
derived class from several base
classes is known as multiple
inheritance
[Link] does not support multiple
inheritance.
[Link] C extends Class A and
Class B both.
Multilevel Inheritance:
[Link] Multilevel Inheritance, one
class can inherit from a derived
class. [Link], the derived class
becomes the base class for the
new class.
[Link] C extends class B and
class B extends class A.
Hierarchical Inheritance:
[Link] Hierarchical Inheritance,
one class is inherited by many
sub classes.
[Link] B, C, and D inherit the
same class A.
Hybrid Inheritance:
[Link] inheritance is a
combination of Single and
Multiple inheritance.
Method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
Usage of Java Method Overriding Rules for Java Method Overriding
1. Method overriding is used to provide the 1. The method must have the same name as
specific implementation of a method in the parent class
which is already provided by its superclass. 2. The method must have the same
2. Method overriding is used for runtime parameter as in the parent class.
polymorphism 3. There must be an IS-A relationship
(inheritance).
example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7%, and 9% rate of interest.
class Bank
{
int Interest();
}
class SBI extends Bank
{
int Interest()
{
return 7;
}
}
class ANDHRA extends Bank
{
Int Interest()
{
return 8;
}
}
class TestBank
{
public static void main(String args[])
{
SBI S =new SBI();
[Link]("Rate of Interest is: "+[Link]());
ANDHRA A=new ANDHRA();
[Link]("Rate of Interest is: "+[Link]());
}
}
Super Keyword
1. The super keyword refers to superclass (parent) objects.
2. It is used to call superclass methods, and to access the superclass constructor.
3. The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
4. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
import [Link].*;
import [Link].*;
class Person
{
int id;
String name;
Person(int id,String name)
{
[Link]=id;
[Link]=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id, String name, float salary)
{
super(id,name); //reusing parent constructor
[Link]=salary;
}
void showlay() Output:
{
[Link](id+" "+name + " " + salary); D:\>javac [Link]
}
D:\>java Sp
}
class Sp 10 aruna 45000.00
{
public static void main(String[] args)
{
Emp e1=new Emp(10,"aruna",45000.00f);
[Link]();
}
}
final keyword
1. It is used to make a variable as a constant, Restrict method overriding, Restrict
inheritance.
2. In java language final keyword can be used in following way.
A. final keyword at variable level
B. final keyword at method level
C. final keyword at Class Level
final at variable level
A. final keyword is used to make a variable as a constant.
this is similar to const in other language.
B. A variable declared with the final keyword cannot be modified by the program after
initialization.
C. This is useful to universal constants, such as "pi".
final keyword in java example Without final keyword in java example
class circle class circle
{ {
public static final double pi=3.14159; public static final double pi=3.14159;
public static void main(string[] args) public static void main(string[] args)
{ {
[Link](pi); pi=4.1345f
} [Link](pi);
} }
}
Output: 3.14159 Output: error
Example:
class finaldemo
{
public static void main(string args[])
{
developer d=new developer();
[Link]();
}
}
output:
error
Abstract class
[Link] abstract keyword is a non-access modifier, used for classes and methods.
2. abstract class
A. it is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
B. It cannot be instantiated.
C. It needs to be extended.
[Link] method
[Link] is a method that can only be used in an abstract class, and it does not have a body. [Link]
body is provided by the subclass and its method should be implemented.
[Link] is a process of hiding the implementation details and showing only functionality to
the user.
[Link] can have final methods which will force the subclass not to change the body of the method.
Interfaces
}
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
There are two types: 1. built-in package 2. user-defined package.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Built-in Packages
[Link] Java API is a library of prewritten classes, included in the Java Development Environment.
[Link] library is divided into packages and classes.
[Link] can either import a single class (along with its methods and attributes), or a whole package
that contain all the classes
[Link] use a class or a package from the library, the import keyword is used
Syntax
// Import a single class // Import the whole package
Naming conventions
[Link](x);
User-defined-package
Java package created by user to categorized classes and interface.
The package keyword is used to create a package in java.
creating packages:
steps:
[Link] the package at the beginning of a file using package keywyord
package packagename;
2. define the class that is to be use package and declare it public
[Link] subdirectory under the directory where the main source file are stored
4. name the file as [Link]
5. compile the file. This creates .class file in the package directory.
d:\>md mypack;
d:\>cd mypack;
Step1: Step 2 :
open notepad , type , save file as open notepad , type , save file as
[Link] in mypack folder [Link] in java folder
D:\>javac [Link]
D:\>java Packtest
Hello
All syntax errors will be detected and Successfully compiled progams may
displayed by the java compiler .these errors produce wrong results due to wrong logic .
are known as Compile Time Errors. these errors are known as Runtime Errors.
2) NullPointerException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]()); //NullPointerException
3) NumberFormatException
The wrong formatting of any value may occur NumberFormatException.
Suppose I have a string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="hello";
int i=[Link](s);
//NumberFormatException
4)ArrayIndexOutOfBoundsException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[] = new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Types of Java Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions .
Eg: IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
Keyword Description
The "try" keyword is used to specify a block where we should place exception
try code. The try block must be followed by either catch or finally.
finally The "finally" block is used to execute compulsory the important code of the
program.
It is executed whether an exception is handled or not.
an example1 of Java Exception Handling where we using a try-catch statement to handle the
exception.
Example2:
class ThrowsExecp
{
public static void main(String args[])
{
String str = null;
[Link]([Link]());
}
}
1. Java uses try keyword to preface a block of code that is likely to cause an error
condition and throw an exception.
2. A catch block define by the keyword catch “catches” the exception “thrown” by the try
block and handles it appropriately.
3. The catch block is added immediately after the try block.
4. try statement should have atleast one catch statement otherwise compilation error will
occur.
5. try block can have one or more statements that could generate an exception.
6. If any one statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch block .
Syntax of Java try-catch
try
{
//code that may throw an exception
}
catch(ExceptionclassName ref)
{
}
Output:
Class TestCustom
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
Output:
Exception occured: InvalidAgeException:not valid
bye
throw throws
Java throw keyword is used to Java throws keyword is used to declare an
1) explicitly throw an exception. exception.
2) Checked exception cannot be Checked exception can be propagated with
propagated using throw only. throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the Throws is used with the method signature.
method.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
Multithreading in Java
There is context-switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads. At a time one thread is executed only.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java
new, runnable, non-runnable and terminated. There is no running state.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Dead state
1. when we create a thread object, the thread is born and is said to be in newborn state.
2. The thread is not scheduled for running.
3. At this state we can do only one of the follwoing things:
Schedule it for running using start() method
Kill it using stop() method.
4. If scheduled, it moves to the runnable state.
Runnable state
The runnable state means that thread is ready for execution and is waiting for the availability of
the processor.
The thread has joined the queue of threads that are waiting for theme in execution.
If all threads have equal priority then they are given time in FCFS manner.
Yeild() can be used if we want thread to gain control to another thread of equal prority before its
turn comes.
Running state
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread .
A running thread may relinquishes its control in one of the following cases:
1. It has been suspended using suspend() method.
A suspended thread can be revived by using the resume() method.
This approach is useful when we want to suspend a thread for some time due to certain reason,
but donot wan to kill it.
That is,
a thread can be defi ned by extending the [Link] class
or by implementing the [Link] interface.
The run() method should be overridden and should contain the code that will be executed by the
new thread.
This method must be public with a void return type and should not take any arguments.
1. Create a class by extending the Thread class and override the run() method:
class ThreadTest
{
public static void main(String [] args )
{
A t1 = new A();
B t1 = new B();
[Link]();
[Link]();
}
}
Create a class that implements the interface Runnable and override run() method:
Step 1:
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
Step 2 : Creating Object: MyThread
myObject = new MyThread();
[Link]();
class threadtest
{
public static void main(Strings args[])
{
Thread t=new [Link]();
[Link](“current thread”+ t);
[Link](“my thread”);
[Link](“after name change”+ t);
}
}
Thread Priority:
1. In java ,Each thread have a priority, which affects the order in which it is scheduled for
running.
2. Threads that have same priority are given equal treatment by the java scheduler and
therefore , they share the processor on FCFS first come first server basis.
3. Java permits us to set the priority of a thread using setPriority method as follows:
[Link](number);
4. Priorities are represented by a number between 1 and 10.
5. In most cases, thread schedular schedules the threads according to their priority (known
as preemptive scheduling.
MIN_PRIORITY =1
NORM_PRIORITY =5 (Default priority of a thread)
MAX_PRIORITY =10
class ThreadPriority
{
public static void main(String [] args )
{
A t1 = new A();
B t1 = new B();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
1. When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues.
2. For example, if multiple threads try to write within a same file then they may corrupt the data
because one of the threads can override data or while one thread is opening the same file at the
same time another thread might be closing the same file.
3. So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time.
4. This is implemented using a concept called monitors.
5. Each object in Java is associated with a monitor, which a thread can lock or unlock.
6. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks.
Stream
OutputStream:
Java application uses an output stream to write data to a destination; it may be a file, an array, io
device
InputStream:
Java application uses an input stream to read data from a source; it may be a file, an array, io
device .
The File class have several methods for working with directories and files such as creating new directories
or files, deleting and renaming directories or files, listing the contents of a directory etc.
methods
boolean createNewFile() It atomically creates a new, empty file named if a file name does not exist.
boolean canWrite() It tests whether the application can modify the file .
boolean canExecute() It tests whether the application can execute the file
boolean canRead() It tests whether the application can read the file .
import [Link].*;
public class FileDemo
{
public static void main(String[] args)
{
try
{
File file = new File("[Link]");
if ( [Link]() )
{
[Link]("New File is created!");
}
else
{
[Link]("File already exists.");
}
}
catch (IOException e)
{
}
}
}
void write(byte[] It is used to write [Link] bytes from the byte array to the file output
ary) stream.
void write(int b) It is used to write the specified byte to the file output stream.
import [Link];
methods
int read() It is used to read the byte of data from the input stream.
import [Link];
1. Scanner is a class in [Link] package used for performing the input of the primitive types
like int, double, etc. and strings
2. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
by default.
3. It provides many methods to read and parse various primitive values.
4. Java Scanner class is widely used to parse text for string and primitive types using a
regular expression.
5. Java Scanner class extends Object class .
[Link]();
}
methods
Method Description
1. void write(int b) It writes the specified byte to the buffered output stream.
In this example,
we are writing the textual information in the BufferedOutputStream object which is connected to the
FileOutputStream object.
The flush() flushes the data of one stream and send it into another.
import [Link].*;
public class BufferedOutputStreamExample
{
public static void main(String args[]) throws Exception
{
FileOutputStream fout = new FileOutputStream("D:\[Link]");
BufferedOutputStream bout = new BufferedOutputStream(fout);
[Link]();
[Link]();
[Link]();
[Link]("success");
}
}
Output:
Success
[Link]
Welcome to java
methods
int read() It read the next byte of data from the input stream.
It closes the input stream and releases any of the system resources associated with the
void close()
stream.
Example of Java BufferedInputStream
import [Link].*;
public class BufferedInputStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\[Link]");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while( (i = [Link]() ) != -1)
{
[Link]( (char)i );
}
[Link]();
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output: javaTpoint
Java - RandomAccessFile
1. RandomAccessFile class is used for reading and writing to random access file.
2. A random access file behaves like a large array of bytes.
3. There is a cursor implied to the array called file pointer, by moving the cursor we do the
read write operations.
4. If end-of-file is reached before than EOFException is thrown. It is a type of IOException.
Class declaration
Methods
1. read() : [Link]()
reads byte of data from file
2. readBoolean() :
reads a boolean from the file.
3. readByte() : [Link]()
reads a signed eight-bit value from file
4. readChar() : [Link]()
reads a character from the file, start reading from the File Pointer.
5. readDouble() : [Link]()
reads a double value from the file, start reading from the File Pointer.
6. readFloat() : [Link]()
reads a float value from the file, start reading from the File Pointer.
7. readInt() : [Link]()
reads a signed 4 bytes integer from the file, start reading from the File Pointer.
8. readLong() : [Link]()
reads a signed 64 bit integer from the file, start reading from the File Pointer.
Program to show RandomAccessFile:
import [Link].*;
try
double d = 1.5;
float f = 14.56f;
[Link](0);
[Link](d);
[Link](0);
[Link](0);
[Link](f);
[Link](0);
}
Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
1. init():
The init( ) method is the first method to be called
In this method, the applet object is created by the browser.
Because this method is called before all the other methods, programmer can utilize this
method to instantiate objects, initialize variables, setting background and foreground
colors in GUI etc.;
init() method is called at the time of starting the execution.
This is called only once in the life cycle.
2. start():
The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped.
In init() method, even through applet object is created, it is in inactive state.
To make the applet active, the init() method calls start() method.
init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is called
each time an applet’s HTML document is displayed onscreen.
This method is called a number of times in the life cycle;
3. paint():
This method takes a [Link] object as parameter.
This class includes many methods of drawing necessary to draw on the applet window.
This is the place where the programmer can write his code of what he expects from
applet like animation etc.
paint() method is called by the start() method.
This is called number of times in the execution.
4. stop():
The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page,
An applet can come any number of times into this method in its life cycle and can go back
to the active state (paint() method) whenever would like.
This method is called number of times in the execution.
5. destroy():
The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory
At this point, you should free up any resources the applet may be using.
The stop( ) method is always called before destroy( ).
the init() and destroy() methods are called only once in the life cycle.
But, start(), paint() and stop() methods are called a number of times.
Applet class
The [Link] class 4 life cycle methods and [Link] class provides 1 life cycle
methods for an applet.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
public abstract void drawLine(int x1, int y1, int x2, int y2):
is used to draw line between the points(x1, y1) and (x2, y2).
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
1. Events :
An event is a change in state of an object.
2. Events Source :
Event source is an object that generates an event.
3. Listeners :
A listener is an object that listens to the event.
A listener gets notified when an event occurs.
1. A source generates an Event and send it to one or more listeners registered with the source.
2. Once event is received by the listener, they process the event and then return.
3. Events are supported by a number of Java packages, like [Link], [Link] and [Link].
Sources of Events
1. Button
2. Checkbox
3. Choice
4. List
5. Menu Item
6. Scrollbar
7. Text Components
8. Window
Important Event Classes and Interface
1. Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java.
2. 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.
3. The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
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 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.
example of AWT where we are inheriting Frame class. Here, Button component on the Frame.
import [Link].*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}
}
Java AWT 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.
AWT Button Class declaration
The object of Label class is a component for placing text in a container. It is used to display a single line
of read only text.
Label Example
import [Link].*;
class LabelExample{
Label l1,l2;
[Link](l1);
[Link](l2);
[Link](400,400);
[Link](null);
[Link](true);
}
Java AWT TextField
The object of a TextField class is a text component that allows the editing of a single line text. It inherits
TextComponent class.
import [Link].*;
class TextFieldExample{
TextField t1,t2;
[Link](50,100, 200,30);
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
import [Link].*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
[Link](100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
[Link](100,150, 50,50);
[Link](checkbox1);
[Link](checkbox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output:
import [Link].*;
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are
following classes that represents the layout managers:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
Java 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:
import [Link].*;
import [Link].*;
[Link](b1,[Link]);
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
[Link](b5,[Link]);
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in
each rectangle.
import [Link].*;
import [Link].*;
[Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
[Link](b6);[Link](b7);[Link](b8);[Link](b9);
[Link](new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
} }
Java 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.
import [Link].*;
import [Link].*;
[Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
[Link](new FlowLayout([Link]));
//setting flow layout of right alignment
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Java Swing
1. Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications.
2. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
3. Unlike AWT, Java Swing provides platform-independent and lightweight components.
4. The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, Jmenu.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development
of desktop applications.
1. A container is a kind of component that holds and manages other components.
2. JComponent objects can be containers, because the JComponent class descends from
the Container class.
3. Three of the most useful container types are JFrame , JPanel, and JApplet.
4. A JFrame is a top-level window on your display. JFrame is derived from JWindow,
5. A JPanel is a generic container element used to group components inside of JFrames
and other JPanels.
6. The JApplet class is a kind of container that provides the foundation for applets that run
inside web browsers.
7. The add( ) method of the Container class adds a component to the container.
8. Thereafter, this component can be displayed in the container’s display area and
positioned by its layout manager.
9. You can remove a component from a container with the remove( ) method.
The methods of Component class are widely used in java swing that are given below.
Method Description
import [Link].*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructo Description
r
JTable() Creates a table with empty cells.
import [Link].*;
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"};
import [Link].*;
import [Link].*;
import [Link].*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}