0% found this document useful (0 votes)
8 views103 pages

Jarusha Java Notes 2024

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1995, designed for creating reusable code and modular programs. It includes a comprehensive development environment with tools like the Java Development Kit (JDK) and supports features such as multithreading, security, and dynamic linking. Java programs can be executed on any platform that supports Java, making it popular for internet programming and Android applications.

Uploaded by

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

Jarusha Java Notes 2024

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1995, designed for creating reusable code and modular programs. It includes a comprehensive development environment with tools like the Java Development Kit (JDK) and supports features such as multithreading, security, and dynamic linking. Java programs can be executed on any platform that supports Java, making it popular for internet programming and Android applications.

Uploaded by

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

Java Introduction

1. Java is an object-oriented, class-based, secured and general-purpose computer-


programming language.
2. JAVA was developed by JAMES GOSLINGat Sun Microsystemsin the year 1995.
3. It helps to create Reusable Code and Modular Programs.
4. Today ,Java is used for Internet Programming in the Distributed Environment of the
internet and for Android smartphone applications and the Internet Of Things.
5. It is a general-purpose programming language for developers to write once run
anywherei.e, compiled Java code can run on all platforms that support Java without the
need to recompile.
6. Java programs are Platform Independent Language which means they can be run on any
operating system with any processor
7. Java has features of C and C++ and has obtained its format from C, and OOP features
from C++.

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.

Application programming interface (API)


The java standard library for API includes hundreds of classes and methods grouped into
packages as follows :
[Link] support package [Link] package
2. Utilities package 5. AWT package
3. Input/output package 6. Applet package
Java Runtime environment (JRE)
JRE allows execution of program developed in java which contains
1. JVM (java virtual machine)
2. Runtime class libraries
3. User interface toolkit (AWT and Swing)
Features of Java
Simple , small and familiar Distributed
Compiled and interpreted Multithread and interactive
Platform independent and portable High performance
Object oriented Dynamic and extensible
Robust and secure Easy application development
Simple small and familar
1. Java is simple as it does not use pointers, preprocessor, header files, goto , operator
overloading and multiple inheritance.
2. Java is familiar because syntax is based on c++, easy to learn, and its syntax is simple,
small and easy to understand.
Object-oriented
1. Java is a true object-oriented programming language & supports all oops concepts like
Object, class, Abstraction, Encapsulation, Inheritance , Polymorphism .
2. Everything in Java is an object.
3. All java program code and data is defined within objects and classes .
4. Java library is vast set of classes , arranged in packages, that we can use in our programs
Platform Independent and portable
1. Java is platform independent were Java programs can be easily be transferred from one
computer to another,(write once, run anywhere, anytime).
2. Changes and upgrades in OS, processors and system resources will not force any changes in
java program
3. This is the reason java has become popular language for internet programming which
interconnects different kinds of systems worldwide.
Portability
1. Java ensures portability in two ways.
2. First java compiler generates byte code instructions that can be implemented on any machine.
3. Secondly, the size of the primitive data types is machine independent.
Secured
1. Security becomes an important issue for a language that is used for programming internet.
2. Attack of viruses and misuse of resources are everywhere.
3. Java systems not only verify all memory access but also ensure that no virus attack java
programs. so Java is best known for its security. With Java, we can develop virus-free systems.
[Link] of pointers in java ensures that java programs cannot access memory locations
without proper authorization.
5. Java Programs run inside a virtual machine sandbox
Robust (strong)
Java is robust language because:
1. It uses strong memory management& provides many safeguards to ensure reliable code.
2. It has strict compile time and runtime checking for data types.
3. It avoids security problems because pointers are not used.
4. There is Automatic Garbage Collection in java which runs on the Java Virtual Machine to
free objects which are not being used by a Java application anymore.
5. There are Exception Handling to handle runtime errors and eliminates system crash.
High-performance
Java programs are faster in execution when compared to other traditional interpreted
programming languages because Java byte code is close to native code.
Distributed
1. Java is designed as a distributed language for creating applications on networks.
2. It has the ability share both data and programs.
Multi-threaded and Interactive
1. Multithreaded means handling multiple tasks simultaneously.
2. Java supports multithread programs .
3. This means that we need not wait for application to finish one task before beginning another.
4. A thread is like a separate program, executing concurrently and It shares a common memory
area. Eg: we can listen to audio while downloading image.
Dynamic and extensible
1. Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods and object.
2. Java programs support functions written in c/c++. These functions are known as native
methods. 3. These methods are linked dynamically at runtime.
4. Java supports dynamic compilation and automatic memory management (garbage collection).
Java Virtual Machine (JVM)
1. Java Virtual Machine (JVM) is an abstract machine (which does not exist physically)
responsible for compiling and executing Java code. It is a part of the Java Runtime
Environment (JRE) which calls the main function of a program.
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications.
2. When we execute a Java program ,JVM converts the byte code to the machine-specific
code.
3. In other programming languages, the compiler produces machine code for a particular
system however java compiler produces code for a virtual machine known as JVMFirst,
java compiler converts java program into bytecode. ([Link] ->[Link])
4. Bytecode is an intermediate code between source code and machine code.
5. This .class file goes into various steps when we run it. These steps together describe the
whole JVM.

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

creating, Compiling, and Executing a Java Program


In java two types of programs can be developed:
[Link]-Alone Applications [Link] Applets
Standalone applications are programs written in java to perform tasks on a standalone local
computer. Executing standalone programs involves two steps:
1. Compiling source code to bytecode using javac compiler.
2. Executing the bytecode program using java interpreter.
Web applets are small java programs developed for internet applications .
An applet located in server can be downloaded via internet and executed on a local computer
using browser.

Step 1: Creating a Java Program


use any text editor or IDE to create and edit a Java source-code file.
Open notepad and save program as [Link]
public class Welcome
{
public static void main(String[] args)
{
[Link]("Welcome to Java");
}
}
Step 2: Compiling a Java Program
A Java compiler translates a Java source file([Link]) into a Java bytecode file
([Link]) as
javac [Link]

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) Primitive data types


In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double.
portability of java is because the size of these primitive data types do not change from one
operating system to another.

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

Data Default Default Range Example stores


Type Value size
boolean false 1 bit true and false boolean status = false true or false
(default)
char '\u0000' 2 byte 65,535 char ch = 'A' Single character
byte 0 1 byte (-28) to (28 -1) byte a = 10 Whole numbers
-128 to 127 (inclusive)
short 0 2 byte (-216) to (216 -1) short s = 100 stores integers
(whole numbers),
without decimals
int 0 4 byte (-231) to (231 -1) int a = 1000 stores integers
(whole numbers),
without decimals
long 0L 8 byte (-263) to (263 -1) long a = 100000L stores integers
(whole numbers),
without decimals
float 0.0f 4 byte Upto7 decimal digits stores floating
1. float f1 = 234.5f
point numbers,
with decimals,
double 0.0d 8 byte Upto16 decimal double d1 = 12. stores floating
digits 3 point numbers,
with decimals,
program to show java datatypes

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

Java conditional statements


Java has specific statements that allow us to check a condition and execute certain parts of code
depending on whether the condition is true or false. Such statementsare called conditional
statements.
In Java, there are two forms of conditional statements:•
1. if-else statement, to choose between two alternatives
2. switch statement, to choose between multiple alternatives
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
Java if Statement :The Java if statement tests the condition. It executes the if block if condition is true.
Syntax: //Java Program to show if statement.
if(condition) public class age
{ {
code to be executed public static void main(String[] args)
} {
int age=20;
if(age>18)
{
[Link]("Age is greater than 18");
}
}
}

Java if-else Statement


The if-else statement also tests the condition. if condition is true It executes the statements otherwise
else statements are executed.
Syntax: public class large
if(condition) {
{ public static void main(String[] args)
code if condition is true {
} int a=10,b =20;
else if(a>b)
{ {
code if condition is false [Link]("a largest");
} }
else
{
[Link]("b largest");
}
}

if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
Syntax: public class largest
if(condition1) {
{ public static void main(String[] args)
code to be executed if condition1 is true {
} int a=10,b=20,c=30;
else if(condition2) if(a>b&&a>c)
{ [Link](“largest” + a);
code to be executed if condition2 is true else if(b>c&&b>a)
} [Link](“largest” + b);
else if(condition3) else
{ [Link](“largest” + c);
code to be executed if condition3 is true }
} }
...
else
{
code to be executed if all the conditions are false
}
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition)
{
code to be executed
if(condition)
{
code to be executed
}
}

Java Switch Statement


1. The Java switch statement executes one statement from multiple conditions.
2. It is like if-else-if ladder statement.
3. the switch statement checks the equality of a variable against multiple values.
4. The case value must match with switch expression(byte, short, int, long string.
5. if correct match found it exectues the statement block of that case . if no match is found , default
is exectued.
6. The case value must be literal or constant. It doesn't allow variables.
7. The case values must be unique but not duplicate value
8. Every case should end with break keyword.
9. If no match is found , default is executed.
10. it is used in menu driven programs.

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

public class vowel


{
public static void main(String[] args)
{
char alpha=’a’;
switch(alpha)
{
case ‘a’: [Link]("vowel"); break;
case ‘e’: [Link]("vowel"); break;
case ‘i’: [Link]("vowel"); break;
case ‘o’: [Link]("vowel"); break;
case ‘u’: [Link]("vowel"); break;
default: [Link]("not vowel");
}
}
}
Loops in Java
The process of executing repeatedly block of statments for specified number of times or till given
codigion is satisfied is known as looping.
Types of loops:
[Link] loop [Link]-while loop [Link] loop

while loop do while loop for loop


It is pre-test loop It is post-test loop It is pre-test loop
Condition is given before Condition is given after Condition is given before
statements . statements . statements .
First condition is checkecd. Without checking condition, First condition is checkecd.
If condition is true then code statements are exectued for If condition is true then code will
will be executed repeatedly. first time. be executed repeatedly.
If condition is false loop will be If the number of iteration is If condition is false loop will be
stopped. not fixed, use while loop. stopped.
If the number of iteration is If the number of iteration is not
not fixed, use while loop. fixed, use while loop.
while(condition) do for (init; condition; incr/decr)
{ { {
code to be executed code to be executed code to be executed
} }while(condition); }
for(int i=1;i<=10;i++)
int i=1; int i=1; {
while(i<=10) do [Link](i);
{ { }
[Link](i); [Link](i);
i++; i++;
} }while(i<=10);
public class Test2 public class Test3 public class Test1
{ { {
p s v main(String[] args) p s v main(String[] args) p s v main(String[] args)
{ { {
int i=1; int i=1; for( int i=1; i<=10 ;i++)
do [Link](i);
while(i<=10)
{ }
{
}
[Link](i); [Link](i);
i++; i++;
} }while(i<=10);
} }
} }
Defining classes :creating objects and Classes in Java
Java is an object-oriented programming language. Everything in Java is associated with classes and
objects, along with its attributes and methods.

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:

public class Student The new keyword is used to allocate memory at


{ runtime. All objects get memory in Heap memory
int age = 20; area.
}
Note:a class should always start with an uppercase
first letter, and that the name of the java file
should match the class name.
A class can contain any of the following variable types.
Local variables –
Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed when
the method has completed.
Instance variables –
Instance variables are variables within a class but outside any method.
These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables –
Class variables are variables declared within a class, outside any method, with the
static keyword.

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

public static void main(String[] args)


{
Hello();
}
}

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

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different/same values to the distinct objects.
Parameters are also known as arguments
Syntax
classname(parameters )
{
}

Program to show parameterized constructor


class Student4
{
int rno;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
rno= i;
name = n;
}
//method to display the values
void display( )
{
[Link](rno+" "+name);
}

public static void main(String args[])


{
//creating objects and passing values
Student4 s1 = new Student4(25,"anu");
Student4 s2 = new Student4(26,"priya");

//calling method to display the values of object


[Link]();
[Link]();
}
}

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;

Student5(int i, String n) //creating two arg constructor


{
rno= i;
name = n;
}

Student5(int i ,String n, int a) //creating three arg constructor


{
rno= i;
name = n;
age=a;
}
void display()
{
[Link](rno + " " + name + " " + age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(25,"anu");
Student5 s2 = new Student5(26,"priya",20);
[Link]();
[Link]();
}
}
Output:
25 anu 0
26 priya 20

this keyword
In java, this is a keyword and a reference variable that refers to the current object.

Usage of java this keyword


1) this can be used to refer current class instance variable.
2) this can be used to invoke current class method (implicitly)
3) this() can be used to invoke current class constructor.
4) this can be passed as an argument in the method call.
5) this can be passed as argument in the constructor call.
6) this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
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.
class Student
{
int rollno;
String name;
Float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);}
}

class Testthis
{
public static void main(String args[]){
Student s1=new Student(11,"anu",5000f);
Student s2=new Student(12,"suma",6000f);
[Link]();
[Link]();
}}

Output: 11,"anu",5000f 12,"suma",6000f

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

Multidimensional Arrays can be defined as an array of arrays. Data in multidimensional arrays


are stored in tabular form (rows and columns.)

Examples
int[][] arr = new int[3][5];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];

Two – dimensional Array (2D-Array)


A. 2 D array is the simplest form of a multidimensional array.
B. 2 D array can be considered as array of one – dimensional array.
C. An Array defined with one variablename and with two dimensions is known as one
dimensional array.
Declaration : datatype[][] arrayname = new datatype[x][y];
example:
int[][] arr = new int[2][3];
int arr[][] = new int[2][3];
int [][]arr = new int[2][3];

Initialization: arrayname[rowindex][columnindex] = value;


example:
arr[0][0] = 10;
arr[0][1] = 11;
arr[1][0] = 12;
arr[1][1] = 13;
Multidimensional Java Array
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
Output:
123
245
445
Note : java program to show matrix multiplication compulsory
Java Inner Classes
[Link] class means one class which is a class Outer
member of another class. {
class Inner
[Link] class or nested class is a class which {
is declared inside the class or interface. public void show()
3. There are four types of inner classes in {
java. [Link]("nested class");
}
}
1) Nested Inner class }
2) Method Local inner classes
class Intest
3) Anonymous inner classes {
4) Static nested classes public static void main(String[] args)
{
Syntax of Inner class [Link] in = new Outer().new Inner();
[Link]();
class Outerclass }
{ }
//code
class Innerclass Output:
{ D:\>javac [Link]
//code D:\>java Intest
}
} In a nested class method
Advantage of java inner classes
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.
3) Code Optimization: It requires less code to
write.

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]

Types of inheritance in java


Single Inheritance:
1. The process of deriving one
derived class from one base class
is known as single inheritance
[Link] B extends only Class A.
[Link] A is a super class and Class
B is a Sub-class.

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.

[Link] the public and protected


members of Class A are inherited
into Class D,
first via Class B and secondly via
Class C.

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

final keyword at method level


A. When final keyword used with method defined in base class , then its sub classes cannot
override this method.
B. the compiler checks and gives an error if you try to override the method.
class Employee class FinalDemo
{ {
final void show() public static void main(String args[])
{ {
[Link]("Hello");
Developer d=new Developer();
}
[Link]();
}
class Developer extends Employee }
{ }
void show()
{
[Link]("Hai"); Output:
} error
}
final keyword at class level
1. when a class is defined with final keyword then the class cannot be used to derive
a new class.(subclass cannot be created)
2. when we want to restrict inheritance then make class as a final.

Example:

public final class A


{
......
......
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}

example of final keyword at class level


final class employee
{
int salary=10000;
}
class developer extends employee // it gives an error
{
void show()
{
[Link]("hello");
}
}

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.

abstract class Bank class TestBank


{ {
abstract int Interest(); public static void main(String args[])
} {
Bank b =new SBI();
class SBI extends Bank [Link]("Rate of Interest is: "+[Link]());
{
int Interest() Bank b=new ANDHRA();
{ [Link]("Rate of Interest is: "+[Link]());
return 7; }
} }
}
Output:
class ANDHRA extends Bank Rate of Interest is: 7
{ Rate of Interest is: 8
Int Interest()
{
return 8;
}
}

Interfaces

1. An interface is a blueprint of a class. Program to show interface


2. It has static constants and abstract
methods. interface Bank
3. There can be only abstract methods {
in the interface, not method body.
4. It is used to achieve abstraction and float interest();
multiple inheritance in Java. }
5. Java Interface also represents the IS-
A relationship. class SBI implements Bank
6. It cannot be instantiated just like the {
abstract class. public float interest()
Reasons to use interface in java {
1. It is used to achieve abstraction. return 9.15f;
2. By interface, we can support the }
functionality of multiple inheritance. }
How to declare an interface?
1. An interface is declared by using the
class Andhra implements Bank
interface keyword.
{
2. It provides total abstraction; means
public float interest()
all the methods in an interface are
{
declared with the empty body, and
return 9.7f;
all the fields are public, static and
}
final by default.
3. A class that implements an interface
}
must implement all the methods
declared in the interface. class Inter
{
Syntax:
interface interfacename
public static void main(String[] args)
{ {
constant fields Bank b=new SBI();
methods that abstract by default. s.o.p("rate of interest "+[Link]());
}
Bank b=new andhra();
s.o.p ("Rate of Interest is: "+[Link]());

}
}

a class extends another class, an


interface extends another interface, but
a class implements an interface.

Multiple inheritance in Java by interface


1. The process of deriving one derived class from several base classes is known as multiple
inheritance.
2. Java doesnot directly support multiple inheritance through classes due to the complexity.
3. It is implemented through interfaces.
4. If a class implements multiple interfaces, or an interface extends multiple interfaces, then
it is a multiple inheritance.
Program to show multiple inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Mtest implements Printable , Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}

public static void main(String args[])


{
Test t=new Test();
[Link]();
[Link]();
}
}
Output:
D:\java>javac [Link]
D:\>java>java [Link]
Hello
Welcome

Difference between abstract class and interface

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract classcan extend another Java An interface can extend another Java interface
class and implement multiple Java only.
interfaces.
7) An abstract classcan be extended using An interface classcan be implemented using
keyword "extends". keyword "implements".
8) A abstract class can have class members Members of a interface are public by default.
like private, protected, etc.
abstract class Bank interface Printable
{ {
abstract int Interest(); void print();
} }
class SBI extends Bank interface Showable
{ {
int Interest() void show();
{ }
return 7; class Test implements Printable,Showable
} {
} public void print()
class ANDHRA extends Bank {
{ [Link]("Hello");
Int Interest() }
{ public void show()
return 8; {
} [Link]("Welcome");
} }

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

import [Link]; import [Link].*;


import [Link]; import [Link].*;
import [Link]; import [Link].*;
import [Link];
import [Link];

Naming conventions
[Link](x);

java-> package name


lang-> subpackage name
Math-> classname
sqrt(x)-> methodname

There are many built-in packages such


as java, lang, awt, javax, swing, net,
io, util, sql etc.

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

package message; import message.*;


class PackTest
public class Test {
{ public static void main(String args[])
public void msg() {
{ Test t=new Test();
[Link](“hello”); [Link]();
} }
}
}
Save the program as [Link]
Compile and run the program

D:\>javac [Link]
D:\>java Packtest
Hello

II. accessing package in other files


import [Link]; or import packagename.*;
or import [Link];

UNIT III Exception Handling


1. The Exception Handling in Java is a mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
2. Errors are of two types:
Compile time errors Runtime Errors

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.

1. Missing semicolon, double quotes in 1. Division by zero


strings 2. Accessing an element out of the
2. Use of undeclared variables bounds of an array.
3. Bad references to objects 3. Attempting to use a negative size
4. Misspelling of identifers and for an array
keywords 4. Converting invalid string to number
5. Mismatch of brackets in classes and 5. During type casting
methods.
In Java, an Exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Hierarchy of Java Exception classes
The [Link] 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 :

Exception and Exception Handling


1. An Exception is a condition that is caused by a runtime error in the program.
2. When the java interpreter encounters an errot such as division by zero , it creates an
exception object and throws it (informs user about the error)
3. If the exception object is not caught and handled properly , the interpreter will display an
error message and will terminate the program.
4. If we want the program to continue with the execution of remaining code, then we
should try to catch the exception object thrown by the error condition and then display
an appropriate message for taking corrective actions.
This is known as Exception Handling.
5. Exception handling process includes:
A. Find the problem (try)
B. Inform that an error has occurred(throw the exception)
C. Receive the error information(catch the exception)
D. Take corrective actions.(handle the exception)
The error handling code consists of two parts:
6. To detect errors and To throw exception
7. To catch exception and to take correct actions

Common Example of Java Exceptions


1) ArithmeticException
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException

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

The classes which inherit RuntimeException are known as unchecked exceptions.


Eg:ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError

There are 5 keywords which are used in handling exceptions in Java.

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.

catch The "catch" block is used to handle the exception.

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.

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

throws The "throws" keyword is used to declare exceptions.


It doesn't throw an exception.
It is always used with method signature.

Java Exception Handling Example

an example1 of Java Exception Handling where we using a try-catch statement to handle the
exception.

public class ExceptionExample


{
public static void main(String args[])
{
try
{
int x=100/0; //code that may raise exception
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("bye"); //rest code of the program
}
}
Output: Exception in thread main [Link]: / by zero
bye

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

Example2:

class ThrowsExecp
{
public static void main(String args[])
{
String str = null;
[Link]([Link]());
}
}

Output : Exception in thread "main" [Link]

Java try-catch block

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

Syntax of try-finally block


try
{
//code that may throw an exception
}
finally
{
}

Java catch block


1. Java catch block is used to handle the Exception by declaring the type of exception within
the parameter.
2. The catch block must be used after the try block only which means we can't use catch
block alone.
3. You can use multiple catch block with a single try block and it can be followed by finally
block later.
4. The catch statement is passed a single parameter, which is reference to the exception
object thrown by the try block.
5. If the catch parameter matches with the type of exception object , then the exceptoin is
caught and statements in the catch block will be exectued.
6. Otherwise, if the exception Is not caught and the default exception handler will cause the
execution to terminate.
Problem without exception handling
class Ex
{
public static void main(String[] args)
{
int data=10/0; //may throw exception
[Link]("rest of the code");
}
}
Output: Exception in thread "main" [Link]: / by zero
As displayed in the above example, the rest of the code is not executed .
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
public class EX1
{
public static void main(String[] args)
{
try
{
int data=10/0; //may throw exception
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("bye");
}
}
Output:
[Link]: / by zero
bye
Java finally block
1. Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
2. Java finally block is compulsory executed whether exception is handled or not.
3. For each try block there can be zero or more catch blocks, but only one finally block.
4. Java finally block follows try or catch block.
5. Finally block when defined, it is used to perform some operations like closing files and
releasing system resources.
syntax: Syntax:
try try
{ {
…………… ……………
……………. …………….
} }
finally catch(…)
{ {
………….. ……….
………….. ………..
} }
catch(…)
{
……….
………..
}
finally
{
…………..
…………..
}

Program to show finally block:

public class EX2


{
public static void main(String[] args)
{
try
{
int data=10/0; //may throw exception
}
catch(ArithmeticException e)
{
[Link](e);
}
finally
{
[Link]("I am in final block");
}
[Link]("bye");
}
}

Output: Exception caught:Division by zero


bye

Java throw keyword (throwing our own execeptions)

1. The Java throw keyword is used to explicitly throw an exception.


2. We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom(user defined) exception.

syntax for throw keyword : throw new exception;


example:
throw new IOException("sorry device error);
throw new ArithmeticException();
throw new NumberFormatException();

java throw keyword program:


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

public class TestThrow


{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[])
{
validate(13);
[Link]("bye");
}
}

Output:

Exception in thread main [Link]: not valid

Java throws keyword


1. 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.
2. 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.
3. Throws is specifed immediately afte the method declaration statement and just before
opening brackets.
Syntax :
returntype methodname() throws exceptionclassname
{
//method code
}
//[Link] example
class Ex2
{
static void divide() throws ArithmeticException
{
int a=45,b=0,rs;
rs = a / b;
[Link](" The result is : " + rs);
}
public static void main(String[] args)
{
try
{
Division();
}
catch(ArithmeticException Ex)
{ Output:
[Link]("caught the exceptoin : " + e); Error : / by zero.
} bye
[Link]("bye”);
}
}
}

Java Custom 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 of java custom exception.

class invalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}

Class TestCustom
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}

public static void main(String args[])


{
try
{
validate(13);
}
catch(Exception e)
{
[Link]("Exception occured: "+e);
}
[Link]("bye”);
}
}

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

1. Multithreading in java is a process of executing multiple threads simultaneously.


2. The aim of multithreading is to achieve the concurrent execution.
3. A thread is a lightweight sub-process, the smallest unit of processing.
4. Multiprocessing and multithreading, both are used to achieve multitasking.
5. However, we use multithreading than multiprocessing because threads use a shared
memory area.
6. They don't allocate separate memory area . so saves memory.
7. Threads are independent.
8. If there occurs exception in one thread, it doesn't affect other threads
9. Java Multithreading is mostly used in games, animation, etc.
10. You can perform many operations together, so it saves time.

As shown in the above figure, a thread is executed inside the process.

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

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

2. It has been made to sleep.


We can put a thread to sleep for some time using sleep(time) method where time is millisecs.
This means thread is out of the queue during this time period.
The thread re-enters the runnable state as soon as this time is elapsed.
3. It has been told to wait uintil some event occurs by using wait() method.
The thread can be scheduled to run again using the notify() method.
Blocked state:
 A thread is said to be blocked whne it is prevented form entering into the runnable state
and running state.
 This happens when the thread is suspended, sleeping,or waiting in order to satify certain
requirements.
 A blocked thread is considered has “not runnable” but not dead and can be resumed to
run again.
Dead state:
 Every thread has a life cycle.
 A running thread ends when it has completed executing its run() method.
 We can kill it by sending the stop message to it at any state .
 A thread can be killed as soon as it is born or while running or in blocked state.

Methods of Thread class


 getPriority()  resume()
 setPriority()  stop()
 getName()  isAlive()
 setName()  currentThread()
 run()  join()
 start()  getState()
 sleep()  yield()
 suspend()

Creating thread in java


Threads are objects in the Java language. They can be created by using two different mechanisms as

1. Create a class that extends the standard Thread class


2. Create a class that implements the standard Runnable interface.

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.

Method I: Extending the Thread Class

1. Create a class by extending the Thread class and override the run() method:

class MyThread extends Thread


{
public void run()
{
// thread body of execution
}
}

2. Create a thread object: MyThread t = new


MyThread();

3. Start Execution of created thread: [Link]();


Program [Link]: A simple program creating and invoking a thread
object by extending the standard Thread class.

class A extends Thread


{
public void run()
{
for(int i=2; i<=5; i=i+2)
{
[Link](“ from thread A ” + i);
}
[Link](“ exit from thread A ” );
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j=j+1)
{
[Link](“ from thread B ” + j);
}
[Link](“ exit from thread B ” );
}
}

class ThreadTest
{
public static void main(String [] args )
{
A t1 = new A();
B t1 = new B();
[Link]();
[Link]();
}
}

Method II: Implementing the Runnable Interface

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

Step 3: Creating Thread Object: Thread t = new Thread(myObject);

Step4: Start Execution:

[Link]();

/*A simple program creating and invoking a thread object by implementing


Runnable interface. */

class MyThread implements Runnable


{
public void run()
{
[Link](“ this thread is running ... ”);
}
}
class ThreadEx
{
public static void main(String [] args )
{
MyThread m=new MyThread();
Thread t = new Thread( m );
[Link]();
}
}
The main Thread:
When a java program starts up, one thread begins running immediately.
This is called main thread of your program, bcoz it is the one that is executed when your program begins.
The main thread is important for 2 reasons

It is the thread from which other “child” threads will be created.


Often it is the last thread to finish execution because it performs various shutdown process.
Although the main thread is created automatically when your program is started , it can be controlled
through a Thread object.

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.

Thread class defines 3 constants :

MIN_PRIORITY =1
NORM_PRIORITY =5 (Default priority of a thread)
MAX_PRIORITY =10

class A extends Thread


{
public void run()
{
for(int i=2 ; i<5 ; i=i+2)
{
[Link](“ from thread A ” + i);
}
[Link](“ exit from thread A ” );
}
}
class B extends Thread
{
public void run()
{
for(int j=1 ; j<5 ; j=j+2)
{
[Link](“ from thread B ” + j);
}
[Link](“ exit from thread B ” );
}
}

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]();

[Link](“end of main thread”);


}
}
Java - Thread Synchronization

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.

the synchronization is mainly used to:

 To prevent thread interference.


 To prevent consistency problem.

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.

You keep shared resources within this block.

Following is the general form of the synchronized statement −


Syntax
synchronized(objectidentifier)
{
// Access shared variables and other shared resources
}
Input/output
Java .io package
1. Java I/O (Input and Output) is used to process the input and produce the output.
2. Java uses the concept of a stream to make I/O operation fast.
3. The [Link] package contains all the classes required for input and output operations.
4. We can perform file handling in Java by Java I/O API.

Stream

1. A stream is a sequence of data. In Java, a stream is composed of bytes.


2. In Java, 3 streams are created for us automatically.
3. All these streams are attached with the console(i/o deivces).

1) [Link]: standard output stream

2) [Link]: standard input stream

3) [Link]: standard error stream


OutputStream vs InputStream

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 .

Java File Class

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

New File is created!

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.


If you have to write primitive values(int, char, float , double values) into a file, use
FileOutputStream class.
You can write byte-oriented as well as character-oriented data through FileOutputStream class.

FileOutputStream class declaration:

public class FileOutputStream extends OutputStream

FileOutputStream class methods

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.

void close() It is used to closes the file output stream.

import [Link];

public class FileOutputStreamExample


{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\[Link]");
String s="Welcome to javaTpoint.";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}
catch(Exception e)
{
[Link](e);
}
}
}
Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file.


It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video

Java FileInputStream class declaration

public class FileInputStream extends InputStream

methods

int read() It is used to read the byte of data from the input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

import [Link];

public class DataStreamExample


{
public static void main(String args[])
{
try
{
FileInputStream fin = new FileInputStream("D:\[Link]");
int i=[Link]();
[Link]((char)i);
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Java Scanner Class

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 .

Java Scanner Class Declaration


public class Scanner extends Object

Java Scanner Class Methods


Example program
import [Link].*;
public class ScannerEx
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link](" Enter Your Details ");
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Name: " + name);

[Link]("Enter your age: ");


int i = [Link]();
[Link]("Age: " + i);

[Link]("Enter your salary: ");


double d = [Link]();
[Link]("Salary: " + d);

[Link]();
}

Java BufferedOutputStream Class

1. Java BufferedOutputStream class is used for buffering an output stream.


2. It internally uses buffer to store data.
3. It adds more efficiency than to write data directly into a stream.
4. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class.


OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\[Link]"));

Java BufferedOutputStream class declaration

public class BufferedOutputStream extends FilterOutputStream

methods

Method Description

1. void write(int b) It writes the specified byte to the buffered output stream.

2. void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:

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.

It is required if you have connected the one stream with 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);

String s="Welcome to java.";


byte b[]=[Link]();
[Link](b);

[Link]();
[Link]();
[Link]();

[Link]("success");
}
}

Output:

Success

[Link]

Welcome to java

Java BufferedInputStream Class

1. Java BufferedInputStream class is used to read information from stream.


2. It internally uses buffer mechanism to make the performance fast.

Java BufferedInputStream class declaration

public class BufferedInputStream extends FilterInputStream

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

data in "[Link]" file is java

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

public class RandomAccessFile extends Object

implements DataOutput, DataInput

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].*;

public class NewClass

public static void main(String[] args)

try

double d = 1.5;

float f = 14.56f;

RandomAccessFile r = new RandomAccessFile("[Link]", "rw");

[Link](0);

[Link](d);

[Link](0);

[Link](“double value is : " + [Link]());

[Link](0);

[Link](f);

[Link](0);

[Link]("float value is : " + [Link]() );

catch (IOException ex)

[Link]("Something went Wrong");

}
Java Applet

1. Applet is a Java program that can be embedded into a web page.


2. It runs inside the web browser and works at client side.
3. Applet is embedded in a HTML page using the APPLET or OBJECT tag and
hosted on a web server.
4. Applets are used to make the web site more dynamic and entertaining
5. All applets are sub-classes (either directly or indirectly) of [Link] class.
6. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer.
7. JDK provides a standard applet viewer tool called applet viewer.
8. In general, execution of an applet does not begin at main() method.

Lifecycle of 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

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.

common methods used in displaying the output in applet in java


Displaying Graphics in Applet
[Link] class provides many methods for graphics programming.
 public abstract void drawString(String str, int x, int y):
is used to draw the specified string.

 public void drawRect(int x, int y, int width, int height):


draws a rectangle with the specified width and height.

 public abstract void drawOval(int x, int y, int width, int height):


is used to draw oval with the specified width and height.

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

 public abstract boolean drawImage(Image img, int x, int y):


is used draw the specified image.

 public abstract void setColor(Color c):


is used to set the graphics current color to the specified color.

 public abstract void setFont(Font font):


is used to set the graphics current font to the specified font.

Example of Graphics in applet:


import [Link];
import [Link].*;

public class GraphicsDemo extends Applet


{
public void paint(Graphics g)
{
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](90,150,30,30,30,270);

}
}

[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

Event handling in java


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.
Components of Event Handling

Event handling has three main components,

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.

How Events are handled ?

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

Event Classes Description Listener Interface


generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released and also MouseListener
when it enters or exit a component
generated when input is received from
KeyEvent KeyListener
keyboard
ItemEvent generated when check-box or list item is clicked ItemListener
generated when value of textarea or textfield is
TextEvent TextListener
changed
generated when window is activated,
WindowEvent WindowListener
deactivated, , opened or closed
generated when component is hidden, moved,
ComponentEvent ComponentEventListener
resized or set visible
generated when component is added or
ContainerEvent ContainerListener
removed from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
generated when component gains or loses
FocusEvent FocusListener
keyboard focus

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener
AWT INTRODUCTION

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.

Methods of Component class

Method Description

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

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

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

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

Java AWT Example:


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

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)

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

public class Button extends Component implements Accessible

Java AWT Button Example


import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
[Link](50,100,80,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Java AWT Label

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.

AWT Label Class Declaration

public class Label extends Component implements Accessible

Label Example
import [Link].*;

class LabelExample{

public static void main(String args[]){

Frame f= new Frame("Label Example");

Label l1,l2;

l1=new Label("First Label.");

l2=new Label("Second Label.");

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

AWT TextField Class Declaration

public class TextField extends TextComponent

Java AWT TextField Example

import [Link].*;

class TextFieldExample{

public static void main(String args[]){

Frame f= new Frame("TextField Example");

TextField t1,t2;

t1=new TextField("Welcome to Javatpoint.");

[Link](50,100, 200,30);

t2=new TextField("AWT Tutorial");

[Link](50,150, 200,30);
[Link](t1); [Link](t2);

[Link](400,400);

[Link](null);

[Link](true);

Java AWT 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".

AWT Checkbox Class Declaration

public class Checkbox extends Component implements ItemSelectable, Accessible

Java AWT Checkbox Example

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:

Java AWT 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.
Note: CheckboxGroup enables you to create radio buttons in AWT.
There is no special control for creating radio buttons in AWT.

AWT CheckboxGroup Class Declaration

public class CheckboxGroup extends Object implements Serializable


Java AWT CheckboxGroup Example

import [Link].*;

public class CheckboxGroupExample


{
CheckboxGroupExample()
{
Frame f= new Frame("CheckboxGroup Example");

CheckboxGroup cbg = new CheckboxGroup();

Checkbox checkBox1 = new Checkbox("C++", cbg, false);


Checkbox checkBox2 = new Checkbox("Java", cbg, true);

[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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

import [Link].*;
import [Link].*;

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

[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].*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

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

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

import [Link].*;
import [Link].*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

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

Difference between AWT and Swing

No. Java AWT Java Swing

Java swing components are platform-


1) AWT components are platform-dependent.
independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

Swing provides more powerful


4) AWT provides less components than Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

AWT doesn't follows MVC(Model View


Controller) where model represents data, view
5) Swing follows MVC.
represents presentation and controller acts as
an interface between model and view.

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

public void add(Component c) add a component on another component.

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

public void setLayout(LayoutManager


sets the layout manager for the component.
m)

sets the visibility of the component. It is by default


public void setVisible(boolean b)
false.

There are two ways to create a frame:

By creating the object of Frame class (association)


By extending Frame class (inheritance)

Java Swing Examples

import [Link].*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame

JButton b=new JButton("click"); //creating instance of JButton


[Link](b);//adding button in JFrame

[Link](400,500); //400 width and 500 height


[Link](null); //using no layout managers
[Link](true); //making the frame visible
}
}

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

JTable jt=new JTable(data,column);


JScrollPane sp=new JScrollPane(jt);
[Link](sp);
[Link](300,400);
[Link](true);
}
public static void main(String[] args)
{
new TableExample();
}
}
Java JDialog
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 class declaration

the declaration for [Link] class.

public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

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

You might also like