Notesjavadocx__2024_11_26_22_44_32

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 61

Annexure-A (Handwritten Notes)

Java Handwritten Notes (4).docx - Google Docs


https://www.linkedin.com/posts/neha-bhardwaj-bb51a2212_core-java-handwritten-
notes-activity-7081811428583649280-

Lecture Notes/OHPs/PPTs

Introduction to Java
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. Java is to be Write Once, Run Anywhere..
The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations were built to
suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for
Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java
ME respectively. Java was developed by James Gosling.
Initially it was named as Oak.
Features of Java
● Simple
● Object-Oriented
● Portable
● Platform Independent
● Secured
● Robust
● Distributed
● Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).Java has
removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc. There is no need to remove unreferenced objects because there
is an Automatic Garbage Collection in Java.
Object Oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour Object-oriented programming (OOPs)
is a methodology that simplifies software development and maintenance by providing
some rules.
● Basic concepts of OOPs are:
● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because there are no explicit pointers.
Robust
Robust simply means strong. Java is robust because It uses strong memory
management.There is a lack of pointers that avoids security problems. There is automatic
garbage collection in java which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.There are exception handling
and the type checking mechanism in Java. All these points make Java robust.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C+
+.Java supports dynamic compilation and automatic memory management (garbage
collection).

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set
top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside
Gosling's office, also went by the name ‘Green’ and ended up later being renamed as
Java, from a list of random words. Sun released the first public implementation as Java
1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-
times on popular platforms. On 13 November, 2006, Sun released much of Java as free
and open source software under the terms of the GNU General Public License (GPL). On
8 May, 2007, Sun finished the process, making all of Java's core code free and
opensource, aside from a small portion of code to which Sun did not hold the copyright.

Popular Java Editors

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available
First java program
class Simple {
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
//This is my first program
/*this is My first program in java. In
this print
only a message*/

Explanation
● Public-It is an access specifier. We should use a public keyword before the main()
method so that JVM can identify the execution point of the program. If we use private,
protected, and default before the main() method, it will not be visible to JVM.
● Static-You can make a method static by using the keyword static. We should call
the main() method without creating an object. Static methods are the method which
invokes without creating the objects, so we do not need any object to call the main()
method.
● Void -In Java, every method has the return type. Void keyword acknowledges the
compiler that main() method does not return any value.
● Main()-It is a default signature which is predefined in the JVM. It is called by JVM
to execute a program line by line and end the execution after completion of this method..
● String args[]-The main() method also accepts some data from the user. It accepts a
group of strings, which is called a string array. It is used to hold the command line
arguments in the form of string values.
Question :: What happens if the main() method is written without String args[]?
Answer:: The program will compile, but not run, because JVM will not recognize the
main() method. Remember JVM always looks for the main() method with a string type
array as a parameter.
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:
1. Open notepad and add the code as above.
2. Save the file as: simple.java.
3. Open a command prompt window and go to the directory where you saved the
class.
4. Assume it's C:\
5. Type javac simple.java and press enter to compile your code. If there are no errors
in your code, the command prompt will take you to the next line (Assumption : The path
variable is set).
6. Now,type java simple' to run your program.
7. You will be able to see ' Hello World ' printed on the window.
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All
characters available inside any comment are ignored by Java compiler
Java Editions
● JAVA SE(Standard Edition)-To develop client side stand alone applications.
● JAVA ME(Micro Edition)-To develop applications for mobile devices.
● JAVA EE(Enterprise Edition)-To develop server side applications such as Java
servlets and Java server pages.
● JAVA SE(Standard Edition)-To develop client side stand alone applications.
● JAVA ME(Micro Edition)-To develop applications for mobile devices.
● JAVA EE(Enterprise Edition)-To develop server side applications such as Java
servlets and Java server pages.
Java Virtual Machine (JVM)
JVM is a engine that provides runtime environment to drive the Java Code or
applications. It converts Java bytecode into machines language. JVM is a part of Java
Run Environment (JRE). In other programming languages, the compiler produces
machine code for a particular system
JRE(Java Runtime Environment)
JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.”
The Java Runtime Environment provides the minimum requirements for executing a
Java application; it consists of the Java Virtual Machine (JVM), core classes, and
supporting files.
Data types In Java

Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values. In java we have two categories of data type:
1) Primitive data types
2) Non-primitive data types
Arrays and Strings are non-primitive data types, we will discuss them later
in the coming tutorials. Here we will discuss primitive data types and literals in Java.
Java is a statically typed language. A language is statically typed, if the data type of a
variable is known at compile time. This means that you must specify the type of the
variable (Declare the variable) before use it.
Example::
int num;
char name;
string abc;
So in order to use the variable num, name, abc in our program, we must declare it first as
shown above. It is a good programming practice to declare all the variables (that you are
going to use) in the beginning of the program.
1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double. Java developers included these data types to maintain the portability of java as
the size of these primitive data types do not change from one operating system to another.
● byte, short, int and long data types are used for storing whole numbers.
● float and double are used for fractional numbers.
● char is used for storing characters(letters).
● boolean data type is used for variables that holds either true or false.
● Byte:This can hold whole number between -128 and 127. Mostly used to save
memory and when you are certain that the numbers would be in the limit specified by
byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

byte num;
char name;

num = 113;
name =”k”
System.out.println(num);
System.out.println(“name”);

}
}
Output:
113 k
Try the same program by assigning value assigning 150 value to variable num, you
would get type mismatch error because the value 150 is out of the range of byte data
type. The range of byte as I mentioned above is -128 to 127.
● short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte
short num = 45678;
● int: Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

short num;

num = 150;
System.out.println(num);
}
}
Output:
150
The byte data type couldn’t hold the value 150 but a short data type can because it has a
wider range.
long:
Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

long num = -12332252626L;


System.out.println(num);
}
}
Output:
-12332252626
double: Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
class JavaExample {
public static void main(String[] args) {

double num = -42937737.9d;


System.out.println(num);
}
}
Output:
-4.29377379E7
float:Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
class JavaExample {
public static void main(String[] args) {

float num = 19.98f;


System.out.println(num);
}
}
Output:
19.98
boolean: holds either true of false.
class JavaExample {
public static void main(String[] args) {

boolean b = false;
System.out.println(b);
}
}
Output:
false
char: holds characters.
size: 2 bytes
class JavaExample {
public static void main(String[] args) {

char ch = 'Z';
System.out.println(ch);
}
}
Output:
Z

Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is an Integer literal.
char ch = 'A';
Here A is a char literal
● Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;
● Float Literals
Used for data type float and double.
double num1 = 22.4;
float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
● Char and String Literal
Used for char and String type.
char ch = 'Z';
String str = "BeginnersBook";

Variable
A variable is a name which is associated with a value that can be changed. For example
when I write int i=10; here variable name is i which is associated with value 10, int is a
data type that represents that this variable can hold integer values.
How to Declare a variable in Java

To declare a variable follow this syntax:


data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then later
assign the value to it.
For example: Here num is a variable and int is a data type. We will discuss the data type
in next tutorial so do not worry too much about it, just understand that int data type
allows this num variable to hold integer values.
int num;
Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
Variables naming convention in java

1) Variables naming cannot contain white spaces, for example: int num ber = 100; is
invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one words
do it like this: int smallNumber; int bigNumber;
4) Variable names are case sensitive in Java.
Java Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:
● Keywords
● Identifiers
● Constants
● Special Symbols
● Operators
Keywords:Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing so,
we are trying to assign a new meaning to the keyword which is not
allowed. Java language support following keywords:

Abstract Boolean Break Byte Case


Catch Char Class Const Continue
Default Do Double Else Enum
Extends Final Finally Float For
Goto If Goto Implements Import
Instanceof Int Interface Long Native
New Package Private Public Return
Short Static Super Switch void

Identifiers::Identifiers are used as the general terminology for naming of variables,


functions and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value
Constants:: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called as literals.Constants may belong to any of the data type.
Syntax:
final data_type variable_name;
Special Symbols::The following special symbols are used in Java having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; *
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces marks the start and end of a block of
code containing more than one executable statement.
comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
semi colon : It is an operator that essentially invokes something called an initialization
list.
assignment operator: It is used to assign values.
Operators
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
● Arithmetic Operators
● Unary Operators
● Assignment Operator
● Relational Operators
● Logical Operators
● Ternary Operator
● Bitwise Operators
● Shift Operators
● Instance of operator
● Precedence and Associativity
Relational Operator

public class Test


{
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) ); } }
This will produce the following result
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Logical Operator
public class Test
{
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}}
This will produce the following result
Output
a && b = false
a || b = true
!(a && b) = true
Shift Operator(Left shift)
class OperatorExampl
e{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Shift Operator(Right shift)
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Ternary Operator
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Assignment Operator
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Bitwise Operator
1. Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits is 1, it
gives 1. If not, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
Example
Example 1: Bitwise OR
class BitwiseOR {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 | number2;


System.out.println(result);
}
}
Bitwise AND
Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1, it gives
1. If either of the bits is not 1, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)
Example
class BitwiseAND {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 & number2;


System.out.println(result);
}
}
Bitwise Complement
Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is denoted by
~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)
Example
class Complement {
public static void main(String[] args) {

int number = 35, result;

result = ~number;
System.out.println(result);
}
}
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding bits are
different, it gives 1. If corresponding bits are same, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)
Example
class Xor {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;


result = number1 ^ number2;
System.out.println(result);
}
}
Left Shift Operator
The left shift operator << shifts a bit pattern to the left by certain number of specified
bits, and zero bits are shifted into the low-order positions.
212 (In binary: 11010100)

212 << 1 evaluates to 424 (In binary: 110101000)


212 << 0 evaluates to 212 (In binary: 11010100)
212 << 4 evaluates to 3392 (In binary: 110101000000)
Right Shift Operator
The right shift operator >> shifts a bit pattern to the right by certain number of specified
bits.
212 (In binary: 11010100)

212 >> 1 evaluates to 106 (In binary: 01101010)


212 >> 0 evaluates to 212 (In binary: 11010100)
212 >> 8 evaluates to 0 (In binary: 00000000)
Example:
class RightShift {
public static void main(String[] args)
{

int number = 212, result;


System.out.println(number >> 1);
System.out.println(number >> 0);
System.out.println(number >> 8);
}
}

Decision Making in JAVA


Decision Making in programming is similar to decision making in real life. In
programming also we face some situations where we want a certain block of code to be
executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.

Java’s Selection statements:


● if
● if-else
● nested-if
● if-else-if
● switch-case
● jump – break, continue, return
These statements allow you to control the flow of your program’s execution based upon
conditions known only during run time.
If statement
if: if statement is the most simple decision making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain condition
is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.
Example of if
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;

if (i > 15)
System.out.println("10 is less than 15");

// This statement will be executed


// as if considers one statement by default
System.out.println("I am Not in if");
}
}
If else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else
if the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example if else
class IfElseDemo
{
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements
means an if statement inside an if statement. Yes, java allows us to nest if statements
within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example nested if
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Example –if else if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Switch case
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Switch case example
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Jump Statements
Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.
Break: In Java, break is majorly used for:
Terminate a sequence in a switch statement .
To exit a loop.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the innermost
loop.
Break example
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Continue:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the
loop’s end. The continue statement performs such an action.
Example of continue
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}
Return
The return statement is used to explicitly return from a method. That is, it causes a
program control to transfer back to the caller of the method.
Return example
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}
Looping Statements

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking time.
while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason it is also called Entry control loop.
Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for the
next iteration.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
Example while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
System.out.println("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;
}
}
}
For loop
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
Syntax:
for (initialization condition; testing condition;increment/decrement)
{
statement(s)
}
1. Initialization condition: Here, we initialize the variable in use. It marks the start of
a for loop. An already declared variable can be used or a variable can be declared, local
to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must return
a boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination:When the condition becomes false, the loop terminates marking
the end of its life cycle.
Example of for loop
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
Object and Class
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
What is an object in Java
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.
Class in JAVA
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
● Fields
● Methods
● Constructors
● Blocks
● Nested class and interface
Syntax to declare a class:
Class
class_name
{
field;
method;
}
Variable and method
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory
at runtime when an object or instance is created. That is why it is known as an instance
variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.The
code can be Reuse again and again .
Object and Class Example:
In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student class by new keyword and printing the
object's value.The main method inside the class.
Here, we are creating a main() method inside the class.
File: Student.java
//Java Program to illustrate how to define a class and fields
//Defining a Student class.

class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: The main outside the class
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name with
the class name which has main() method.

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Ways to initialize object
There are 2 ways to initialize object in Java.
● By reference variable
● By method

Object and Class Example: Initialization through reference: Initializing an object


means storing data into the object. Let's see a simple example where we are going to
initialize the object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Rainy";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Object and Class Example: Initialization through method::In this example, we are
creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. Here, we are displaying the state (data) of the objects
by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Creating multiple objects by one type only

class Rectangle
{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Constructor in JAVA
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
● Default constructor (no-arg constructor)
● Parameterized constructor
Default Constructor::A constructor is called "Default Constructor" when it doesn't have
any parameter.
Syntax of default constructor:
<class_name>()
{
}
Example-Default Constructor
● class Student3{
● int id;
● String name;
● //method to display the value of id and name
● void display(){System.out.println(id+" "+name);}

● public static void main(String args[]){
● //creating objects
● Student3 s1=new Student3();
● Student3 s2=new Student3();
● //displaying values of the object
● s1.display();
● s2.display();
● }
}
Parameterized Constructor::A constructor which has a specific number of parameters
is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Example
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Constructor Overloading
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
Example
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate
super class.

Example of Child class referring Parent class property using super keyword
In this example we will only focus on accessing the parent class property or variables.
class Parent
{
String name;

}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}

Parent and Child


Example of Child class referring Parent class methods using super keyword
In this example we will only focus on accessing the parent class methods.
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}

Parent
Child
Super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate
super class.
Example
class Parent
{
String name;

}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Abstraction in Java
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
● Interface (100%)
● Abstract class
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.
Points to Remember
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of
the method.
Example of abstract class
abstract class A
{
}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known
as an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Terms used in Inheritance
● Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
● Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
Syntax
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Example
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface
only. We will learn about interfaces later.
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends
the another class.

Multilevel inheritance: refers to a child and parent class relationship where a class
extends the child class. For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class
A.

Multiple Inheritance: refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both
classes A and B. Java doesn’t support multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single
program. For example class A & B extends class C and another class D extends class A
then this is a hybrid inheritance example because it is a combination of single and
hierarchical inheritance.
Single Inheritance
When a class extends to another class then it forms single inheritance. In the below
example, we have two classes in which class A extends to class B that forms single
inheritance.

class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}

public class B extends A{

public static void main(String[] args) {


B b = new B();
b.show();

}
}

a=10
Here, we can notice that show() method is declared in class A, but using child class
Demo object, we can call it. That shows the inheritance between these two classes.
Multilevel Inheritance
When a class extends to another class that also extends some other class forms a
multilevel inheritance. For example a class C extends to class B that also extends to class
A and all the data members an methods of class A and B are now accessible in class C.
Example:

class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}

class B extends A{
int b = 10;
void showB() {
System.out.println("b = "+b);
}
}

public class C extends B{

public static void main(String[] args) {


C c = new C();
c.show();
c.showB();
}
}
a=10
b=10
Hierarchical Inheritance
When a class is extended by two or more classes, it forms hierarchical inheritance. For
example, class B extends to class A and class C also extends to class A in that case both
B and C share properties of class A.

class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}

class B extends A{
int b = 10;
void showB() {
System.out.println("b = "+b);
}
}

public class C extends A{

public static void main(String[] args) {


C c = new C();
c.show();
B b = new B();
b.show();
}
}

Why multiple inheritance is not supported in Java?


● To remove ambiguity.
● To provide more maintainable and clear design.

Interface in JAVA
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
● It is used to achieve abstraction.
● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.
Syntax for Interface
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Example
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Static in JAVA

The static keyword in JAVA is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
The static can be:
● Variable (also known as a class variable)
● Method (also known as a class method)
Java static variable ::If you declare any variable as static, it is known as a static
variable.The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of employees,
college name of students, etc.The static variable gets memory only once in the class area
at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Example
class Student{
int rollno;
String name;
String college="CGC";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects.If we make it static, this field will get the memory only
once.
Example
class Student{
int rollno;//instance variable
String name;
static String college ="CGC";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display ()
{
{System.out.println(rollno+" "+name+" "+college);
}

public class TestStaticVariable1{


public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Program of counter by static
As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Java static method ::If you apply static keyword with any method, it is known as static
method.A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.A
static method can access static data member and can change the value of it.
Example-
class Student{
int rollno;
String name;
static String college = "CGC";
//static method to change the value of static variable
static void change(){
college = "CGCTC";
}
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Neha");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
String
A String variable contains a collection of characters surrounded by double quotes:
Exp :: string varablename=” any string”;
public class Main {
public static void main(String[] args)
{
String a = "Hello";
System.out.println(a);
}
}
There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method
compareTo():The Java String class compareTo() method compares the given string with
the current string lexicographically. It returns a positive number, negative number, or 0.
If the first string is lexicographically greater than the second string, it returns a positive
number (difference of character value). If the first string is less than the second string
lexicographically, it returns a negative number, and if the first string is lexicographically
equal to the second string, it returns 0.
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0

1. class abc {
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
11. By Using equals() Method
12. class abc{
13. public static void main(String args[]){
14. String s1="Sachin";
15. String s2="Sachin";
16. String s3=new String("Sachin");
17. String s4="Saurav";
18. System.out.println(s1.equals(s2));//true
19. System.out.println(s1.equals(s3));//true
20. System.out.println(s1.equals(s4));//false
21. }
22. }
By using == method
The == operator compares references not values.
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpoo
l)
8. }
9. }
Java String substring()
The Java String class substring() method returns a part of the string.We pass beginIndex
and endIndex number position in the Java substring method where beginIndex is
inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0,
whereas the endIndex starts from 1.
There are two types of substring methods in Java string.
public String substring(int startIndex) // type - 1
and
public String substring(int startIndex, int endIndex) // type - 2

1. public class SubstringExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}

APPLETS
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Explanation
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.
5. 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.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
11. html>
12. <body>
13. <applet code="First.class" width="300" height="300">
14. </applet>
15. </body>
16. </html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is
not required but it is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
Program-1(Applet LifeCycle)
import java.applet.*;
import java.awt.*;
public class AppletLifeCycle extends Applet {
public void init()
{
System.out.println("init() called");

}
public void start ()
{
System.out.println("start() called");

public void paint(Graphics g)


{
System.out.println("paint() called");

public void stop()


{
System.out.println("stop() called");
}
}

Program-2(Graphics)
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Welcome",50, 50);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}

Program-3
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
//g.setColor(Color.black);

g.drawString("Welcome",50, 50);

g.setColor(Color.blue);

g.fillOval(170,200,30,30);

g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(20,31,20,300);
g.drawRect(70,100,30,30);

g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}

EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple exam
event handling in applet that prints a message by click on the button.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300"> </applet>
</body>
</html>

Program-1(Event Handling)

import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.List;
import java.awt.TextArea;
import java.awt.TextField;
class Myframe extends Frame
{
Myframe()
{
FlowLayout l1=new FlowLayout();
setLayout(l1);
Label label1=new Label("Name");
TextField t1=new TextField("BCA -5",10);
t1.setEchoChar('*');//Method used for password textfield

TextArea text=new TextArea("TextArea with 3 rows and 15


columns",3,15);// text area
Button b1=new Button("Ok");//Button

Checkbox c1=new Checkbox("Sports");


Checkbox c2=new Checkbox("Reading");

Label gender=new Label();


CheckboxGroup ch1=new CheckboxGroup();
Checkbox female=new Checkbox("Female",true,ch1);
Checkbox male=new Checkbox("Male",true,ch1);

Choice choice=new Choice();


choice.add("BCA");
choice.add("MCA");
choice.add("MBA");
choice.add("MA");
List lst1=new List(3,true);
lst1.add("Pascal");
lst1.add("C");
lst1.add("C++");
lst1.add("JAVA");

add(label1);
add(t1);
add(text);
add(b1);
add(c1);
add(c2);
add(gender);
add(female);
add(male);
add(choice);
add(lst1);
}
}

public class LabelDemo


{
public static void main (String args[] )
{
Myframe f1=new Myframe();
f1.setTitle("Frame created");
f1.setSize(600,400);
f1.setVisible(true);
}

Program-2
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Program-3
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){

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


label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}

Exception Handling in Java


An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time, that disrupts the normal flow of the program’s instructions.
Error: An Error indicates serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement
5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes :: The java.lang.Throwable class is the root class
of Java Exception hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered
as the unchecked exception. However, according to Oracle, there are three types of
exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Keywo Description
rd
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
Java Exception Keywords
.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Annexure-A (Handwritten Notes)


https://docs.google.com/document/d/1qpRh3FNdGFsN64vPi7kt9IfHSqCnkuWc/edit?
usp=sharing&ouid=115796792937713412170&rtpof=true&sd=true

You might also like