Professional Documents
Culture Documents
1
Java OOPs Concepts
The main aim of object-oriented programming is to implement real-world entities, for
example, object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented design: 2
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Object
Any entity that has state and behaviour is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects
can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like colour, name, breed, etc. as well as behaviours like wagging the tail,
barking, eating, etc.
3
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class does not
consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
4
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to
draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when
classes are aware of each other. If a class has the details information of another class, there is strong
coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field. You can use interfaces for the weaker coupling because there is no concrete
implementation.
5
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task into
separate parts. The java.io package is a highly cohesive package because it has I/O related classes
and interface. However, the java. util package is a weakly cohesive package because it has unrelated
classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be associated with
one object or many objects. There can be four types of association between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one
prime minister (one to one), and a prime minister can have many ministers (one to many). Also,
many MP's can have one prime minister (many to one), and many ministers can have many
departments (many to many).
Association can be unidirectional or bidirectional. 6
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object
contains other objects as a part of its state. It represents the weak relationship between objects. It is
also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is
another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the relationship
where one object contains other objects as a part of its state. There is a strong relationship between
the containing object and the dependent object. It is the state where containing objects do not have
an independent existence. If you delete the parent object, all the child objects will be deleted
automatically.
7
Figure: Data Representation in Procedure-Oriented Programming
9
10
11
12
13
Difference between JDK, JRE and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can
be executed. It can also run those programs which are written in other languages and compiled to
Java bytecode.
VMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the JVM: specification,
implementation, and instance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
14
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a
set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
15
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
16
17
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 open-source, aside
from a small portion of code to which Sun did not hold the copyright.
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 is
guaranteed to be Write Once, Run Anywhere. 18
Features of Java
Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
Platform Independent − Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This
byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is
being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be
easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX
subset. 19
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error
checking and runtime checking.
Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
The development process is more rapid and analytical since the linking is an incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high performance.
Distributed − Java is designed for the distributed environment of the internet.
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
20
What is an Application?
It is a stand-alone Java program that runs with the support of a virtual machine in a client or server side. Also
referred to as an application program, a Java application is designed to perform a specific function to run on any
Java-compatible virtual machine regardless of the computer architecture. An application is either executed for the
user or for some other application program. Examples of Java applications include database programs,
development tools, word processors, text and image editing programs, spreadsheets, web browsers etc.
Java applications can run with or without graphical user interface (GUI). It’s a broad term used to define any kind
of program in Java, but limited to the programs installed on your machine. Any application program can access any
data or information or any resources available on the system without any security restrictions. Java application
programs run by starting the Java interpreter from the command prompt and are compiled using the javac
command and run using the java command. Every application program generally stays on the machine on which
they are deployed. It has a single start point which has a main() method.
21
What is an Applet?
Unlike a Java application program, an applet is specifically designed to be executed within an HTML web document
using an external API. They are basically small programs – more like the web version of an application – that require
a Java plugin to run on client browser. They run on the client side and are generally used for internet computing. You
can execute a Java applet in a HTML page exactly as you would include an image in a web page. When you see a
HTML page with an applet in a Java-enabled web browser, the applet code gets transferred to the system and is
finally run by the Java-enabled virtual machine on the browser.
Applets are also compiled using the javac command but can only run using the applet viewer command or with a
browser. A Java applet is capable of performing all kinds of operations such as play sounds, display graphics, perform
arithmetic operations, create animated graphics, etc. You can integrate an applet into a web page either locally or
remotely. You can either create your own applets locally or develop them externally. When stored on a local system,
it’s called a local applet. The ones which are stored on a remote location and are developed externally are called
remote applets.
22
Browsers come with Java Runtime environment (JRE) to execute applets and these browsers are called Java-
enabled browsers. The web page contains tags which specify the name of the applet and its URL (Uniform
Resource Locator) – the unique location where the applet bytecodes reside on the World Wide Web. In simple
terms, URLs refer to the files on some machine or network. Unlike applications, Java applets are executed in a
more restricted environment with harsh security restrictions. They cannot access the resources on the system
except the browser-specific services.
Definition of Application and Applet – Applets are feature rich application programs that are specifically designed to be
executed within an HTML web document to execute small tasks or just part of it. Java applications, on the other hand,
are stand-alone programs that are designed to run on a stand-alone machine without having to use a browser.
Execution of Application and Applet– Applications require main method() to execute the code from the command line,
whereas an applet does not require main method() for execution. An applet requires an HTML file before its execution.
The browser, in fact, requires a Java plugin to run an applet.
. 23
Compilation of Application and Applet–Application programs are compiled using the “javac” command and further executed
using the java command. Applet programs, on the other hand, are also compiled using the “javac” command but are executed
either by using the “applet viewer” command or using the web browser
Security Access of Application and Applet – Java application programs can access all the resources of the system including data
and information on that system, whereas applets cannot access or modify any resources on the system except only the
browser specific services.
Restrictions of Application and Applet – Unlike applications, applet programs cannot be run independently, thus require
highest level of security. However, they do not require any specific deployment procedure during execution. Java
applications, on the other hand, run independently and do not require any security as they are trusted.
25
Advantage of Java Bytecode
Platform independence is one of the soul reasons for which James Gosling started the formation of
java and it is this implementation of bytecode which helps us to achieve this. Hence bytecode is a
very important component of any java program. The set of instructions for the JVM may differ from
system to system but all can interpret the bytecode. A point to keep in mind is that bytecodes are
non-runnable codes and rely on the availability of an interpreter to execute and thus the JVM comes
into play.
Bytecode is essentially the machine level language which runs on the Java Virtual Machine.
Whenever a class is loaded, it gets a stream of bytecode per method of the class. Whenever that
method is called during the execution of a program, the bytecode for that method gets invoked.
Javac not only compiles the program but also generates the bytecode for the program. Thus, we
have realized that the bytecode implementation makes Java a platform-independent language.
This helps to add portability to Java which is lacking in languages like C or C++. Portability ensures
that Java can be implemented on a wide array of platforms like desktops, mobile devices, severs and
many more. Supporting this, Sun Microsystems captioned JAVA as "write once, run anywhere" or
"WORA" in resonance to the bytecode interpretation.
26
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
27
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It
is not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
28
class A {
int data=50; //instance variable
static int m=100;
//static variable, which belong to the class initialize only once at the start of execution
void method ()
{
int n=90;//local variable
}
}//end of class
30
31
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
32
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example: Boolean one = false
33
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Example: short s = 10000, short r = -5000
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
34
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum
value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default
value is 0. The long data type is used when you need a range of values more than those provided by
int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited.
The double data type is generally used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3
35
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0)
to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = ‘A’
Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of the world's written
languages.
Unicode is a universal international standard character encoding that is capable of representing most
of the world's written languages.
36
tates
37
38
Java Programming
Course Code: IT 201
MODULE – II
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Java Package
Package is a collection of related classes. Java uses package to group related classes, interfaces and
sub-packages.
We can assume package as a folder or a directory that is used to store similar files.
In Java, packages are used to avoid name conflicts and to control access of class, interface and
enumeration etc. Using it becomes easier to locate the related classes and it also provides a good
structure for projects with hundreds of classes and other files.
Example, Suppose, we have some math related classes and interfaces then to collect them into a simple
place, we have to create a package.
2
3
Advantage of java package
1) Java package is used to categorise the classes and interface so that they can be easily maintained.
2) Java package provides access protection
3) Java package removes naming collision.
How to Create a Package
Creating a package in java is quite easy, simply include a package command followed by name of the package as the
first statement in java source file.
Any classes declared within that file will belong to the specified package.
package mypack;
public class employee
{
String empId;
String name;
4
}
The above statement will create a package with name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class you define to be part of mypack
package must be stored in a directory called mypack.
If we not use the package statement , the class name are put into the default package which has no name.
We can create hierarchy of packages simply separate each package name from the one above it by use of a . Period
5
java is base or core package.
lang is subpackage.
.* ,denotes built in classes, methods and data members available within the subpackage of lang.
We cannot rename a package, without renaming the directory in which classes are stored.
6
Class file will store inside package
c:\foldername>pkg>dir // abc1.class file will store in pkg
7
Example
package pkg;
import java.io.*;
import java.util.Scanner;
public class abc1
{ int a;
public void input()
{
Scanner in= new Scanner(System.in);
System.out.println("Enter number");
8
a=in.nextInt();
}
public void disp()
{
System.out.println("hello");
9
How to import Java Package
To import java package into a class, we need to use java import keyword which is used to access package and its
classes into the java program.
Use import to access built-in and user-defined packages into your java source file so that your class can refer to a
class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:
10
a) Accessing package without import keyword
If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the same
package will not be accessible. For this approach, there is no need to use the import
statement. But you will have to use the fully qualified name every time you are accessing the
class or the interface. This is generally used when two packages have classes with same
names. For example: java.util and java.sql packages contain Date class.
11
Example
In this example, we are creating a class A in package pack and in another class B, we are accessing it while creating object
of class A.
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
12
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
output
Hello
13
Import the Specific Class
Package can have many classes but sometimes we want to access only specific class in our program in that case, Java allows us
to specify class name along with package name. If we use import packagename.classname statement then only the class with
name classname in the package will be available for use.
Example:
In this example, we created a class abc1 stored into pkg package and in another class Testing, we are accessing Demo class by
importing package name with class name.
import pkg.abc1;
class testing
{
public static void main(String args[])
{
14
abc1 objecta=new abc1();
objecta.input();
objecta.disp();
}
}
If we use packagename.* statement, then all the classes and interfaces of this package will be
accessible but the classes and interface inside the subpackages will not be available for use.
The import keyword is used to make the classes of another package accessible to the current package.
15
Example :
In this example, we created a class First in learnjava package that access it in another class Second by using
import keyword.
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}
//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
} }
Output 16
Hello
// WAP to use classes from two different package.
Sol: first create two package and class
Import both package & Create object of the two class inside third class.
Call method using object in third class.
// Q Create a package called “Arithmetic” that contains methods to deal with all arithmetic operations. Also,
write a program to use the package.:
//Note: First create a directory by name “Arithmetic” and move to that directory, create the following file and
compile the file in the same directory.
17
//import java.io.*;
package arith;
public class Mymath
{
public int add(int x,int y)
return x+y;
}
public int sub(int x,int y)
return x-y;
}
18
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
return x%y;
19
Note: Move to parent directory, write the following file and execute it.
import arith.Mymath;
class Test5
{
public static void main(String as[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
} 20
}
Output:
/*
13
40
1.6
*/
Q Write a java program to implement the concept of creating packages and importing classes
from user defined package p1. In p1 package student class is created, import this class to
another package p2.
21
Subpackage
Package inside package is known as subpackage.
// save as p1.java
package m1;
public class p1
{
public void show1()
{
System.out.println("welcome");
}
}
// save class p2.java
package m1.m2; //subpackage
public class p2
22
{
public void show2()
{
System.out.println("welcome 2 package");
}
}
// save p3.java
import m1.m2.*; //importing classes m1.m2
public class p3
{ public static void main(String args[])
{
System.out.println("Subpackage");
m1.m2.p2 y = new m1.m2.p2();
y.show2();
}
23
}
24
Java Programming
Course Code: IT 201
MODULE – V
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or fields to indicate some
additional information which can be used by java compiler and JVM.
Annotations in Java are used to provide additional information, so it is an alternative option for XML and Java marker
interfaces.
2
Built-In Java Annotations used in other annotations
o @Target
o @Retention
o @Inherited
o @Documented
@Override
@Override annotation assures that the subclass method is overriding the parent class method. If it is not so, compile time
error occurs.
Ex.
class A{
void eatSomething(){System.out.println("eating something");}
}
3
class D extends A{
@Override
void eatsomething(){System.out.println("eating foods");} //should be eatSomething
}
class annotation{
public static void main(String args[]){
A a=new D();
a.eatSomething();
}}
Output : compile time error
4
@SuppressWarnings
import java.util.*;
class annotation1{
@SuppressWarnings("unchecked")
// if we make comment above line then warning will be given
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("Raj");
list.add("anil");
list.add("Rahul");
5
for(Object obj:list) //passing through for loop
System.out.println(obj);
}}
anil
rahul
6
If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time because we are using
non-generic collection.
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints warning. It informs user that it may be
removed in the future versions. So, it is better not to use such methods.
class A{
void m(){System.out.println("hello m");}
@Deprecated
void n(){System.out.println("hello n");}
}
7
class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output
At Compile Time:
Note: annotation3.java uses or overrides a deprecated APINote: Recompile with -Xlint:deprecation for details.
At Runtime:
hello n
8
Built-in Annotations used in custom annotations in java
•@Target
•@Retention
•@Inherited
•@Documented
@Target
The java.lang.annotation.ElementType enum declares many constants to specify the type of element where annotation is to be
applied such as TYPE, METHOD, FIELD etc. Let's see the constants of ElementType enum:
9
Element Types Where the annotation can be applied
FIELD fields
METHOD methods
CONSTRUCTOR constructors
PARAMETER parameter
10
Example to specify annoation for a class
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
RetentionPolicy Availability
RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will not be
RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM .
12
Example to specify the RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
In real scenario, java programmer only need to apply annotation. We doesn't need to create and access annotation. Creating
and Accessing annotation is performed by the implementation provider. On behalf of the annotation, java compiler or JVM
performs some additional operations.
13
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the annotation to be inherited to
subclasses.
@Inherited
@interface ForEveryone { }
class Superclass{}
class Subclass extends Superclass{}
14
@Documented
Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.
15
Points to remember for java custom annotation signature
16
Types of Annotation
There are three types of annotations.
1.Marker Annotation
2.Single-Value Annotation
3.Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.
17
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
18
How to apply Single-Value Annotation
Let's see the code to apply the single value annotation.
@MyAnnotation(value=10)
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
19
We can provide the default value also.
For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
20
Example of custom annotation: creating, applying and accessing annotation
//Creating annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation
{
int value();
}
21
//Applying annotation
class Hello{
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello annotation");}
}
//Accessing annotation
class testannotation3{
public static void main(String args[])throws Exception{
22
MyAnnotation p=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+ p.value());
}
}
23
Maven
Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build,
dependency and documentation.
It simplifies the build process like ANT. But it is too much advanced than ANT.
Current version of Maven is 3.
There are many problems that we face during the project development. They are discussed below:
1) Adding set of Jars in each project: In case of struts, spring, hibernate frameworks, we need to add set of jar files in each
project. It must include all the dependencies of jars also.
2) Creating the right project structure: We must create the right project structure in servlet, struts etc, otherwise it will not
be executed.
3) Building and Deploying the project: We must have to build and deploy the project so that it may work.
24
Maven simplifies the above mentioned problems. It does mainly following tasks.
1. It makes a project easy to build
2. It provides uniform build process (maven project can be shared by all the maven projects)
3. It provides project information (log document, cross referenced sources, mailing list, dependency list, unit test reports
etc.)
4. It is easy to migrate for new features of Maven
5. Apache Maven helps to manage
o Builds
o Documentation
o Reporting
o Releases
o Distribution
25
Build Tool
A build tool takes care of everything for building a process. It does following:
o Generates source code (if auto-generated code is used)
o Generates documentation from source code
o Compiles source code
o Packages compiled code into JAR of ZIP file
o Installs the packaged code in local repository, server repository, or central repository
26
Ant Maven
Ant doesn't has formal conventions, so we need to Maven has a convention to place source code, compiled
provide information of the project structure in build.xml code etc. So we don't need to provide information about
file. the project structure in pom.xml file.
Ant is procedural, you need to provide information Maven is declarative, everything you define in the
about what to do and when to do through code. You pom.xml file.
need to provide order.
The ant scripts are not reusable. The maven plugins are reusable.
You can download and install maven on windows, linux and MAC OS platforms. Here, we are going to learn how
to install maven on windows OS.
To install maven on windows, you need to perform following steps:
1.Download maven and extract it
2.Add JAVA_HOME and MAVEN_HOME in environment variable
3.Add maven path in environment variable
4.Verify Maven
1) Download Maven
To install maven on windows, you need to download rfirst.
Download Maven latest Maven software from Download latest version of Maven
For example: apache-maven-3.1.1-bin.zip
Extract it. Now it will look like this:
28
29
2) Add MAVEN_HOME in environment variable
Right click on MyComputer -> properties -> Advanced System Settings -> Environment variables -> click new button
Now add MAVEN_HOME in variable name and path of maven in variable value. It must be the home directory of maven
i.e. outer directory of bin. For example: E:\apache-maven-3.1.1 .It is displayed below:
31
4)Verify maven
To verify whether maven is installed or not, open the command prompt and write:
mvn −version
Now it will display the version of maven and jdk including the maven home and java home.
Let's see the output:
32
Maven Repository
A maven repository is a directory of packaged JAR file with pom.xml file. Maven searches for dependencies in the repositories.
There are 3 types of maven repository:
1. Local Repository
2. Central Repository
3. Remote Repository
Maven searches for the dependencies in the following order:
Local repository then Central repository then Remote repository.
33
If dependency is not found in these repositories, maven stops processing and throws an error.
34
Update location of Local Repository
We can change the location of maven local repository by changing the settings.xml file. It is located
in MAVEN_HOME/conf/settings.xml, for example: E:\apache-maven-3.1.1\conf\settings.xml.
Let's see the default code of settings.xml file.
settings.xml
...
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
35
| Default: ${user.home}/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
..
</settings>
Now change the path to local repository. After changing the path of local repository, it will look
like this:
settings.xml
...
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd
/settings-1.0.0.xsd">
36
.
<localRepository>e:/mavenlocalrepository</localRepository>
...
</settings>
Maven central repository is located on the web. It has been created by the apache maven community itself.
The path of central repository is: http://repo1.maven.org/maven2/.
The central repository contains a lot of common libraries that can be viewed by this
url http://search.maven.org/#browse
37
3) Maven Remote Repository
Maven remote repository is located on the web. Most of libraries can be missing from the central repository such as JBoss
library etc, so we need to define remote repository in pom.xml file.
Let's see the code to add the jUnit library in pom.xml file.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging> 38
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
39
Maven pom.xml file
POM is an acronym for Project Object Model. The pom.xml file contains information of project and configuration
information for the maven to build the project such as dependencies, build directory, source directory, test source directory,
plugin, goals etc.
Maven reads the pom.xml file, then executes the goal.
Before maven 2, it was named as project.xml file. But, since maven 2 (also in maven 3), it is renamed as pom.xml.
Elements of maven pom.xml file
For creating the simple pom.xml file, you need to have following elements:
40
Element Description
groupId It is the sub element of project. It specifies the id for the project
group.
artifactId It is the sub element of project. It specifies the id for the artifact
(project).
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
42
Maven pom.xml file with additional elements
Here, we are going to add other elements in pom.xml file such as:
Element Description
43
File: pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
44
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
45
Maven Plugins
The maven plugins are central part of maven framework, it is used to perform specific goal.
According to Apache Maven, there are 2 types of maven plugins.
1. Build Plugins
2. Reporting Plugins
Build Plugins
These plugins are executed at the time of build. These plugins should be declared inside
the <build> element.
Reporting Plugins
These plugins are executed at the time of site generation. These plugins should be declared inside
the <reporting> element.
46
Maven Core Plugins
Plugin Description
resources copies the resources to the output directory for including in the
JAR.
When we build a Maven project, it executes a set of clearly defined tasks based on the project pom.xml configuration and
the command-line options. This standard set of tasks creates the maven build lifecycle.
The benefit of a clearly defined lifestyle is that we have to remember only a few sets of commands to compile, build, install,
and deploy our projects.
48
Maven Build Phases
Maven build lifecycle goes through a set of stages, they are called build phases. For example, the default lifecycle is
made up of the following phases.
•validate
•compile
•test
•package
•verify
•install
•deploy
The build phases are executed sequentially. When we run a maven build command, we specify the phase to be
executed. Any maven build phases that come before the specified phase is also executed. For example, if we
run then it will execute validate, compile, test, and package phases of the project.
49
$ mvn plugin-prefix:goal
A build phase is made up of a set of goals. Maven goals represent a specific task that contributes to the building and
managing of a project.
Sometimes, a maven goal is not bound to a build phase. We can execute these goals through the command line.
50
Role of POM in Build Lifecycle
The maven builds executed through the command line runs a set of phases and goals. The pom.xml
configuration plays a major role in setting up the project build lifecycle.
The value of pom.xml file defines the set of goals to be executed by the maven build. For example, if
it’s jar then the following phases and goals will be executed.
51
Phase Goal
process-resources resources:resources
compile compiler:compile
process-test-resources resources:testResources
test-compile compiler:testCompile
test surefire:test
package jar:jar
install install:install
deploy deploy:deploy
52
We can also configure goals in the pom.xml file using the plugins element. This is mostly required when you have created a
custom plugin and want to execute any specific goal for a build phase.
Maven GAV
The GAV as project unique identifier - project coordinates. Maven coordinates and defines a set of identifiers which can be
used to uniquely identify a Maven component. This can for example be used to define the exact version of the JUnit test
library which should be used for the project
Maven coordinates.
Maven coordinates identify uniquely a project, a dependency, or a plugin defined in POM. Each entity is uniquely
identified by the combination of a group identifier, an artifact identifier, and the version (and, of course, with the packaging
and the classifier).
53
54
Java Programming
Course Code: IT 201
MODULE – IV
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Event
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as
result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Types of Event
Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a
person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as background events. Operating
system interrupts, hardware or software failure, timer expires, an operation completion are the example of background
events.
2
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism
have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle the events..
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred
event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java
implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received
, the listener process the event an then returns.
3
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The
user interface element is able to delegate the processing of an event to the separate piece of code. In this model, Listener
needs to be registered with the source object so that the listener can receive the event notification. This is an efficient
way of handling the event because the event notifications are sent only to those listener that want to receive them.
Now the object of concerned event class is created automatically and information about the source and the event get
populated with in same object.
4
Points to remember about listener
In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some
public abstract callback methods which must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class cannot act as a listener class for a source
object.
Callback Methods
These are the methods that are provided by API provider and are defined by the application programmer and invoked by the
application developer. Here the callback methods represent an event method. In response to an event java jre will fire
callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the source must register itself to the listener.
5
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event
package provides many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener 6
Steps to perform Event Handling
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
o MenuItem
o TextField
o Checkbox
o Choice
o List
8
Java Event Handling Code
We can put the event handling code into one of the following places:
• Within class
• Other class
• Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
9
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
/* public void setBounds(int x axis, int y axis, int width, int height); have been used in the above example that sets the
position of the component it may be button, textfield etc.*/
//register listener
b.addActionListener(this);//passing current instance
10
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
} 11
Output
//
12
Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
13
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
14
}
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
15
Output
16
We can also use the anonymous class to implement the ActionListener.
18
Output
19
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 java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
20
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
21
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.
The text can be changed by an application but a user cannot edit it directly.
23
Output:
24
Java AWT Label Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
TextField tf; Label l; Button b;
LabelExample(){
tf=new TextField();
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b=new Button("Find IP");
25
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
26
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}
}
Output:
27
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.
29
30
Q Java AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
31
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
32
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()= =b1){
c=a+b;
}else if(e.getSource()= =b2){
c=a-b; }
String result=String.valueOf(c);
tf3.setText(result);
} 33
public static void main(String[] args) {
new TextFieldExample();
}
}
Output
enter value in a=10 and b=20 then click on + or -
34
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.
AWT TextArea Class Declaration
public class TextArea extends TextComponent
Java AWT TextArea Example
import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300); 35
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:
36
37
Java AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample extends Frame implements ActionListener{
Label l1,l2;
TextArea area;
Button b;
TextAreaExample(){
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
38
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
}
39
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
Output:
40
41
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 java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
42
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
} } 43
Output:
44
Java AWT Checkbox Example with ItemListener
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
45
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
46
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
47
public static void main(String args[])
{
new CheckboxExample();
}
}
Output:
48
AWT CheckboxGroup Class Declaration
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false); 49
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
50
} }
Output:
51
52
Java Programming
Course Code: IT 201
MODULE – III
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
A program in execution is often referred as process. A thread is a subset(part) of the process. if a program or
process is subdivided into smaller tasks or jobs each such task is called as thread.
A single process or a program may have many threads that can run simultaneously and do different task at a time.
A process of running more than one thread concurrently is known as multithreading.
Threads are lightweight subprocesses each thread runs its own independent execution path and shares common
memory space.
If one thread triggers an exception, it doesn’t effect the other threads which are executing concurrently
• Ex: in a Web browser we may do the following tasks at the same time:
· 1. scroll a page,
· 2. download an applet or image,
· 3. play sound,
· 4 print a page
2
• Java Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its
companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of
Java.
It provides constructors and methods to support multithreading. It extends object class and implements
Runnable interface.
Thread class also defines many methods for managing threads. Some of them are:
3
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified time
start() start a thread by calling run() method
activeCount() Returns an estimate of the number of active threads in the current
thread's thread group and its subgroups.
When a Java program starts up, one thread begins running immediately. This is usually called the main thread of
your program, because it is the one that is executed when your program begins. The main thread is created
automatically when your program is started, it can be controlled through a Thread object. To do so, you must
obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. This
method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you
can control it just like any other thread.
Syntax
Static Thread current Thread();
In the following program, a reference to the current thread(the main thread, in this case) is obtained by
calling currentThread( ), and this reference is stored in the local variable mth. Next, the program displays the
name of thread. The program then calls setName( ) to change the internal name of the thread. Name of the thread
is then redisplayed. Next, the program then calls stop( ) to stop the thread.
Note: the Exiting ThreadMain statement not executed, because thread stopped. 5
6
Creating a thread
There are two ways to create a thread:
Implementing Runnable
Step1: As a first step the thread should be created through implementing a runnable interface
Syntax:
public class classname implements runnable
{
}
Step2 : Define a run() inside the thread. The run() method can be used only after implementing the runnable
interface. The actual code which represent the functionality of a thread is introduce by a run() method and it is
also the entry point for that thread.
7
Syntax
public void run()
{
}
Step 3: place the run() method inside the class which implements
a runnable interface.
Ex.
public class abc implements Runnable
{
public void run()
{for(int i=1;i<=10;i++)
{
System.out.println(i*5);
}
8
}}
Step 4:
Instantiate a thread class inside the main() method and use that object to execute a thread. It has following steps
Create an object for the class that implements the Runnable interface.
Pass the object as a parameter using one of the Thread constructors given below while creating Thread object.
The instantiation can be done using anyone of the following two Thread constructors.
1) Thread (Runnable r)
2) Thread (Runnable r, String n)
Where r, is the object of the class that implements Runnable interface and n is the name given for the newly
created thread.
Ex. // Generating table of 5 using above steps
9
class abc implements Runnable // abc become thread
{
public void run() // logic is defined
{
System.out.println("Thread started its execution");
for(int i=1;i<=10;i++)
System.out.println(i+"* 5 ="+ i*5);
System.out.println("Thread completed its execution");
} }
public class firstthread{
public static void main(String args[])
{
abc r = new abc();
Thread t= new Thread(r);
t.start();
10
} }
Extending Thread class
This is another way to create a thread by a new class that extends Thread class and create an instance of
that class. The extending class must override run() method which is the entry point of new thread.
11
classMyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
mt.start();
}
}
Output:
concurrent thread started running..
12
In this case also, we must override the run() and then use the start() method to run the thread. Also, when you create
MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class
object acts as Thread class object.
13
for(int i=1;i<=5;i++)
{
Thread.sleep(1000);
System.out.println(i);
}
}catch(Exception e)
{
14
public class firstthread1{
public static void main(String args[])
{
first f1 = new first();
Thread t1= new Thread(f1);
Thread t2=new Thread(new first());
//t1.run();
t1.start();
//t2.run(); //t1.run sequential result shown
t2.start(); // start(), show parallel result
} }
15
Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling
it chooses.
3 constants defined in Thread class:
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.
16
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
17
}
Test it Now
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
18
/* The two threads have been created MT is the main thread which generates the multiplication table of 5
and FIB is the second thread which generates the Fibonacci series. Both threads are created by
extending the Thread class. Priorities will be set for both threads through their objects in the main thread.
*/
class mt extends Thread
{
public void run()
{
System.out.println("First thread multiplication started");
for(int i=1;i<=10;i++)
{
System.out.println(i+"* 5 ="+(i*5));
}
}
} 19
class fib extends Thread
{
public void run()
{System.out.println("Second thread Fibonacci started");
int f=0,s=1,t,i,max=10;
System.out.println(f+"\n"+s);
for(i=2;i<max;i++)
{t=f+s;
System.out.println(t);
f=s;
s=t;
}}}
20
public class tpriority1{
public static void main(String args[])
{
final int MIN_PRIORITY=1;
final int MAX_PRIORITY=10;
fib f=new fib();
f.setPriority(Thread.MAX_PRIORITY);
System.out.println("The priority of second thread Fibonacci started"+f.getPriority());
f.start();
mt m=new mt();
m.setPriority(Thread.MIN_PRIORITY);
System.out.println("The priority First thread started"+m.getPriority());
m.start();
}} 21
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.
General Syntax:
synchronized (object)
{
//statement to be synchronized
}
Every Java object with a critical section of code gets a lock associated with the object. To enter critical section a thread need to obtain the
corresponding object's lock.
22
Why use Synchronization
can be suspended, resumed, or stopped completely based on your requirements. There are various static methods
26
Sr.No. Method & Description
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
27
Example
import java.io.*;
class first extends Thread
29
class Threadsr //in the main class Threadsr
{
public static void main(String args[]) throws IOException
{
first f= new first(); // object f is created
f.start(); //start() method is called which in turn call run() method of the class
System.out.println("Thread is suspended");
f.suspend();
System.out.println("Resume enter 1, stop: enter any number"); // Run
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String ch=br.readLine();
int c= Integer.parseInt(ch);
30
if(c==1)
{
System.out.println("Thread resume from suspended state");
f.resume();
}
else
{
System.out.println("Thread has been stopped"); // thread once stopped will never resume
f.stop();
}
}
}
31
// WAP to demonstrate how we can make sure that the main thread gets executed
after the child thread finish
import java.io.*;
class A extends Thread
{
public void run()
{
System.out.println("ThreadA started");
for(int i=1; i<=4; i++)
{
System.out.println("\t from ThreadA:i=" +i);
}
System.out.println("Exit from A");
}
32
}
class B extends Thread
{
public void run()
{
System.out.println ("ThreadB started");
for(int j=1; j<=4; j++)
{
System.out.println("\t from ThreadB:j=" +j);
}
System.out.println("Exit from B");
}
} 33
class C extends Thread
{
public void run()
{
System.out.println("ThreadC started");
for(int k=1; k<=4; k++)
{
System.out.println("\t from ThreadC:k=" +k);
}
System.out.println("Exit from C");
}
}
34
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
System.out.println("Start ThreadA");
threadA.start();
System.out.println("Start ThreadB");
threadB.start();
System.out.println("Start ThreadC");
threadC.start();
35
System.out.println ("Waiting for Thread A, B, C to stop");
try
threadA.join();
threadB.join();
threadC.join();
}
catch(InterruptedException e)
{
}
System.out.println("End of main thread");
}
} 36
37
Java Programming
Course Code: IT 201
MODULE – III
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Files and I/O Stream
Files are the most important mechanism for storing data permanently on mass storage devices. Storing the data ensures that
it is not lost when the machine is switched off. Files can contain data in binary format that can be interpreted by programs, but
not easily by humans.
The most important operations on files are: creation, reading from, writing to, renaming and deleting. To do all these
operations on a file the input has to read from the keyboard using I/O streams.
File class:
To execute reading and writing operations on a file the first and foremost thing to do is to open the file before the operations
and to close it after completing the action on it.
2
Opening a file means to indicate to the operating system that the programmer wants to operate on a file from within a java
program and the O/s verifier whether the operation is possible and allowed. There are two ways of opening a file: opening
for reading and opening for writing, which cause different behaviors of the O/S.
Closing a file means to indicate to the operating system that the file that was previously opened is not being used anymore
by the program.
Closing a file also has the effect of ensuring that the data written on the file is effectively transferred to the hard-disk.
Exceptions
File operations can typically cause unexpected situations that the program is not capable of handling.
For example : A programmer trying to open a file for reading specifies a filename that does not exist, such situation are called
exceptions.
3
The methods for opening a file for reading can generate an exception of type IOException therefore, any method that calls
such methods must declare explicitly that it can itself generate an exception of that type.
The type of exception that a method can generate is specified in the throws clause, which must be added method
declaration, before body of the method.
For example
public static void main(String args[]) throws IOException
{
// coding
}
4
The file class is defined in java.io package and it is used in various stream related activities. The file class deals directly with
files and the file system. That is it does not specify how information is retrieved from or stored in files it describe the
properties of that file. It does not actually change the contents of the file.
A file object is used to obtain or manipulate the information associated with a disk file. That it can obtain the permission, time
date, directory path and can be used to navigate subdirectory hierarchies.
Returns the name of the file or directory denoted by this abstract pathname.
2 public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise.
8
Writing text files
To write strings of text on a file do the following
1) Open the file for writing by creating an object of the class File Writer associated to the name of the file and creating an
object of the class Printwriter associated to the FileWriter object created.
2) Write text on the file by using the print and println methods of the Printwriter object
3) Close the file when you have finished writing to it.
Example
//Create a text file called shc.txt and write on its the string
"welcome to File handling"
//File class operatoins
import java.io.*;
public class writingonfile
{
public static void main(String args[]) throws IOException
{
// opening the file for writing
FileWriter f=new FileWriter("shc.txt"); 10
//creation of objec for writing
PrintWriter out= new PrintWriter(f);
//writing text on file
out.println("Welcome to file handling");
//closing the output channel and the file
out.close();
f.close();
}
}
11
Reading from a text file
To read strings of text from a file do following:
1) Open the file for reading by creating an object of the class FileReader and an object of the class BufferedReader associated
to the FileReader object just created.
2) Read the lines of text from the file by using the readLine method of the Bufferedreader object.
3) Close the file when you have finished reading from it.
//Q1 open a text file called shc.txt, reads from it a line of text and print it on console
import java.io.*;
public class readingfromfile
{
public static void main(String args[]) throws IOException
{
// opening the file for reading
14
Renaming and deleting a file:
To delete a file, i:e remove it completely from the mass- storage device, the method delete is invoked on an object of type File
created with the name of the file to delete.
File f1 = new File (“shc.txt”);
Boolean b= f1.delete();
if b is true, then the file has been deleted successfully.
Construction of the class file does not generate an exception if file does not exist.
To rename a file, invoke the method renameto() on two objects of type file that represents respectively the file
to rename and new name to give to the file.
File f1 = new File(“oldname.txt”);
File f2 = new File (“newname.txt”);
Boolean b = f1.renameTo(f2);
If b is true, then the file has been renamed successfully.
If newname.txt file already exist then, it will be overwritten.
15
//Q1 Rename and deleting file
import java.io.*;
public class rename
{
public static void main(String args[]) throws IOException
{
// opening the file for reading
FileReader f=new FileReader("shc.txt");
//Rename a file
File f1=new File ("sheenu.txt");
File f2 =new File ("amit.txt");
Boolean b =f1.renameTo(f2);
//if b is true then the file has been renamed successfully
Boolean d= f2.delete();
// if d is true then the file has been deleted successfully
16
} }
Streams
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks We will see the most commonly
used examples one by one
17
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to
byte streams but the most frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an input file into an output file
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
18
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
} 19
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output
for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that
FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt"); 20
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
21
Standard Streams
All the programming languages provide support for standard I/O where the user's program can take input from a keyboard
and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be
aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams:
Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream and
represented as System.in.
Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used for
standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used
for standard error stream and represented as System.err.
22
Example:
Program, which creates InputStreamReader to read standard input stream until the user types a "q" to quit.
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read() 23
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
24
Reading and Writing Files
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is
used for writing data to a destination.
The two important streams are FileInputStream and FileOutputStream.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types
of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a file object using
File() method as follows −
25
File f = new File("C:/java/hello");
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to
26
Sr.No. Method & Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an
IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called
when there are no more references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data
and -1 will be returned if it's the end of the file.
4 public int read(byte[ ] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it
is the end of the file, -1 will be returned.
5 public int available() throws IOException{}
27
Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to
write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the
file. First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods,
which can be used to write to stream or to do other operations on the stream.
28
Sr.No Method & Description
.
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream
is called when there are no more references to this stream. Throws an IOException.
Writes w.length bytes from the mentioned byte array to the OutputStream. 29
Example
//Read single character
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("c:\\java\\jdk1\\bin\\Sample.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
} }
30
Example
//Read all characters in file
import java.io.FileInputStream;
public class DataStreamExample1 {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("c:\\java\\jdk1\\bin\\Sample.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
} }
31
Example
//Write Bytes to a file
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("c:\\java\\jdk1\\bin\\Sample2.txt");
fout.write(65); // write A in file sample2.txt
fout.close();
System.out.println("success..."); // display success on monitor
}catch(Exception e){System.out.println(e);}
}
}
32
Example
// Writing string to file
import java.io.FileOutputStream;
public class FileOutputStreamExample1 {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java.";
byte b[ ]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
33
}
Example
//FileReader
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("c:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
} 34
Example
//File writer
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to java.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
} 35
36
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Operators in Java
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
2
Java Operator Precedence
5
Java Arithmetic Operators
Java arithmatic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
Java Arithmetic Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
6
Java Arithmetic Operator Example: Expression
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}
}
Ans 21
7
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.
Java Left Shift Operator Example
class OperatorExample{
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
} }
Output:
40
80
80
8
240
Java Right Shift Operator
The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right
operand.
Java Right Shift Operator Example
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
}}
Output:
2
5
2
9
10
11
12
13
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the value on its right to the operand on its left.
16
type cast:
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Ex
class Simple{
public static void main(String[] args){
float f=10.5f;
17
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10
18
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words which acts as a
key to a code. These are predefined words by Java so it cannot be used as a variable or object
name. List of Java Keywords
A list of Java keywords or reserved words are given below:
1. abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide the
implementation of interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True
and False values only.
3. break: Java break keyword is used to break loop or switch statement. It breaks the current flow
of the program at specified condition.
4. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
5. case: Java case keyword is used to with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must
be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode 19
characters.
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
10.default: Java default keyword is used to specify the default block of code in a switch
statement.
11.do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the
program several times.
12.double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point
numbers.
10.else: Java else keyword is used to indicate the alternative branches in an if statement.
11.enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
10.extends: Java extends keyword is used to indicate that a class is derived from another class
or interface.
20
11.final: Java final keyword is used to indicate that a variable holds a constant value. It is applied
with a variable. It is used to restrict the user.
12.finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether exception is handled or not.
13.float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
14for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some conditions become true. If the number of iteration is fixed, it is
recommended to use for loop.
15 . if: Java if keyword tests the condition. It executes the if block if condition is true.
16 . implements: Java implements keyword is used to implement an interface.
17. import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
18instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
19 . int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
20. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods. 21
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java
Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the
garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be
accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within package and outside
the package but through inheritance only. It can't be applied on the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword
in Java is used for memory management mainly.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
22
38. super: Java super keyword is a reference variable that is used to refer parent class object. It can be used to
invoke immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test value. The
switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded
code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to
throw custom exception. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exception can be propagated
with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as transient, it will
not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be
followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times.
If the number of iteration is not fixed, it is recommended to use while loop. 23
Literals in Java
Literals is an identifier whose value is fixed and does not change during the execution of the program.
Types of Literals
Integer Literals
Integer Literals are numbers that has no fractional pars or exponent. It refers to the whole numbers. Integers always
begin with a digit or + or -.
We can specify integer constants in
• Decimal
• Octal
• Hexadecimal
It consists of any combination of digits taken from the set 0 to 7. However the first digit must be 0, in order to identify
the constant as octal number.
Example:
int a = 0374; //Octal Constant
int b = 097; // Error: 9 is not an octal digit.
25
Floating-point Literals
Floating-point Literals are also called as real constants. The Floating Point contains decimal points and can contain
exponents. They are used to represent values that will have a fractional part and can be represented in two forms –
fractional form and exponent form.
In the fractional form, the fractional number contains the integer part and fractional part. A dot (.) is used to separate
the integer part and fractional part.
Example:
float x = 2.7f;
In the exponential form, the fractional number contains constants a mantissa and exponent. Mantissa contains the
value of the number and the exponent contains the magnitude of the number. The exponent, if any present,
specifies the magnitude of the number as a power of 10.
Character Literals
Character Literals are specified as single character enclosed in pair of single quotation marks. Single character
constants are internally represented as ASCII codes.
String Literals
String Literals are treated as an array of char. By default, the compiler adds a special character called the ‘null
character’ (‘\0’) at the end of the string to mark the end of the string.
26
Example:
String str = “good morning”;
Boolean literals
There are two Boolean literals
• true represents a true Boolean value
• false represents a false Boolean value
Escape sequences
Escape characters (also called escape sequences or escape codes) in general are used to signal an alternative
interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence and
has special meaning to the java compiler.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if
you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the
sentence: She said "Hello!" to me. you should write:
System.out.println("She said \"Hello!\" to me.");
27
Escape sequences available in java are:
\t - Insert a tab in the text at this point.
\b - Insert a backspace in the text at this point.
\n - Insert a newline in the text at this point.
\r - Insert a carriage return in the text at this point.
\f - Insert a formfeed in the text at this point.
\' - Insert a single quote character in the text at this point.
\" - Insert a double quote character in the text at this point.
\\ - Insert a backslash character in the text at this point.
28
Java Variables - Dynamic Initialization
Initialization is the process of providing value to a variable at declaration time. A variable is initialized once in its life
time. Any attempt of setting a variable's value after its declaration is called assignment. To use a local variable you
have to either initialize or assign it before the variable is first used. But for class members, the compulsion is not so
strict. If you don't initialize them then compiler takes care of the initialization process and set class members to
default values.
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is called
dynamic initialization. The following piece of code (DynamicInitializationDemo.java) demonstrates it.
/* DynamicInitializationDemo.java */
public class DynamicInitializationDemo
{
public static void main(String[] args)
{
//dynSqrt will be initialized when Math.sqrt
//will be executed at run time
double dynSqrt = Math.sqrt (16);
29
System.out.println("sqrt of 16 is : " + dynSqrt);
}
}
OUTPUT
======
sqrt of 16 is : 4.0
Other functions
abs(), ceil(), exp(), pow(a,b)
identifier
Identifiers in Java. A Java identifier is the symbolic name that is used for identification purpose. In Java, an identifier can be a
variable name, constant name, method name, class name, array name, packages name or an interface
For example : int score = 100;
30
Here, the score is a variable (an identifier)
• An identifier is a sequence of characters that may consist of letters (A-Z, a-z) digits (0-9), an underscore character ( _ ) or
The dollar sign $.
31
• An identifier cannot start with a digit and must not contain any spaces or tabs.
• It is good programming practice to use the identifier names that reflect the meaning of the programming element being
used.
• Java is case sensitive. Not using the proper uppercase and lowercase letters for an identifier causes a compilation error
typically.
32
33
Java Programming
Course Code: IT 201
MODULE – II
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Interface
Interface is a concept which is used to achieve abstraction in Java. This is the only way by which we can achieve full
abstraction. Interfaces are syntactically similar to classes, but you cannot create instance of an Interface and their
methods are declared without any body. It can have When you create an interface it defines what a class can do
It can have only abstract methods and static fields. However, from Java 8, interface can have default and static
When an interface inherits another interface extends keyword is used whereas class use implements keyword to
inherit an interface.
2
Advantages of Interface
It Support multiple inheritance
It helps to achieve abstraction
It can be used to achieve loose coupling.
Syntax:
interface interfacename {
// fields
// abstract/private/default methods
}
When no access specifier is included then default access result and the interface is only available to other members of the
package in which it is declared. When it is declared as public, the interface can be used by any other code.
3
Implement interface
Once an interface defined one or more class can implement that interface. To implement an interface include the
implements clause in a definition and the create a methods define by interface.
Syntax
class classname implements interface
{
// class body
}
4
If a class implements more than one interface the interfaces are separated with a comma.
When you implement a interface it must be declared as public.
Example of interface
import java .lang.*
Interface inter{
public String disptext(); /no implementation of method
}
public class imp implements inter
{
public static void main(String args[])
{ Imp inter1=new imp();
String str = inter1.disptext();
System.out.println(str);
}
5
public String disptext()
{
return “I love java”; //declare in the interface
} }
C:> javac imp.java
C:> java imp
Output
I love java
6
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
7
EXAMPLE
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Q Interface area is implemented by rectangle and circle class to find an area. Write a java program to runtime
polymorphism with the help of interfaces.
11
import java.io.*;
import java.util.*;
interface area
{
final static float pi=3.14f;
float compute(float x, float y);
}
class rectangle implements area
{
public float compute(float x, float y)
{
System.out.println("\n compute method of rectangle");
return(x*y);
}
12
}
class circle implements area
{
public float compute(float x, float y)
{
System.out.println("\n compute method of circle");
return(pi*x*x);
}
}
class interfacetest
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cir=new circle(); 13
//area area;
//area=rect;
System.out.println("area of rectangle=" + rect.compute(10,20));//200
area=cir;
System.out.println("area of circle=" + cir.compute(10,0)); // 314
}
}
14
15
Java Programming
Course Code: IT 201
MODULE – IV
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Java AWT CheckboxGroup Example with ItemListener
import java.awt.*;
import java.awt.event.*;
5
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It
inherits Component class.
import java.awt.*;
public class ChoiceExample
{
6
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
7
}
public static void main(String args[])
{
new ChoiceExample();
} }
Output
8
Java AWT Choice Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Button b=new Button("Show");
b.setBounds(200,100,50,20);
9
final Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
f.add(c);f.add(label); f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
10
String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample();
}
}
11
Output
12
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items. It
inherits Component class.
import java.awt.*;
public class ListExample
{
13
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
14
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
15
Java AWT List Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500,100);
Button b=new Button("Show");
16
b.setBounds(200,150,80,30);
final List l1=new List(4, false);
l1.setBounds(100,100, 70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100,200, 70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
17
l2.add("CodeIgniter");
f.add(l1); f.add(l2); f.add(label); f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()){
data += frame + " ";
}
18
label.setText(data);
}
});
}
19
Output:
20
Java AWT Canvas
The Canvas control represents a blank rectangular area where the application can draw or trap input events from the user. It
inherits the Component class.
AWT Canvas class Declaration
public class Canvas extends Component implements Accessible
23
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see
invisible number of rows and columns.
25
Java AWT Scrollbar Example with AdjustmentListener
import java.awt.*;
import java.awt.event.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
final Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
26
f.add(s);f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
} });
}
public static void main(String args[]){
new ScrollbarExample();
}
27
}
Output:
28
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the
MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.
29
Java AWT MenuItem and Menu Example
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
30
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
31
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output
32
33
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach any other component. It inherits
the Container class.
36
Java AWT Dialog
The Dialog 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 Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't
have.
37
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
38
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
39
new DialogExample();
}
}
Output:
40
41
Java Programming
Course Code: IT 201
MODULE – III
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Applet
An applet is a small windows-based program that is embedded in the browser and works on the client side.
An applet needs the AWT for interaction with the user by way of some GUI components such as Textbox, Button,
Checkboxes etc. Applets are displayed in a window and expect an AWT to perform I/O operations.
An applet provides the developer an event driven approach, whereby the execution flow of the program is decided by user
actions such as mouse-click, key-press etc.
There are two types of applets available, AWT based applets and the second one is swing based applets or Japplet. Even
though the swing-based applet is widely used to develop java based GUI applications. The AWT based applet is used for
developing single window-based applications.
Basic fundamentals
The AWT based applets directly inherits the applet class and override all its member functions before start using the applet in
a program, two important packages need to be included in the program, java.applet and java.awt.
Java .awt package is needed to show output result in applet program.
Applets are executed by web browser or appletviewer provided by the SDK.
2
To become an applet, a java class should extend the applet class before using its properties.
A main() method is not defined in the applet to start execution just like console base java program.
An applet outputs its results through the AWT method drawstring() in X,Y coordinate position on the
window.
After it is successfully developed and compiled, the applet program can be executed in two ways.
In the first method, a separate HTML file will be created and class name of an applet is specified in the
applet tag.
Using second method , an applet tag is specified in the comments before the declaration of a public class.
After all parts of the applet program are declared the applet program can be executed by a java enabled web
browser or applet viewer.
3
Applet class
Applet class provides all necessary support for applet execution, such as initializing and destroying of applet. It also
provide methods that load and display images and methods that load and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
• init() :
init() is the first method to be called. This is where variable are initialized. This method is called only once during the
runtime of applet.
• start() :
start() method is called after init(). This method is called to restart an applet after it has been stopped.
• stop() :
stop() method is called to suspend thread that does not need to run when applet is not visible.
4
• destroy() :
destroy() method is called when your applet needs to be removed completely from memory.
Note: The stop() method is always called before destroy() method.
public void paint(Graphic G):
Another method is provided by component class, which is used to paint something on the screen or output the result
of an applet.
Then execute
C:>java>bin>appletviewer abc.java
6
Commonly used methods of Graphics class:
void drawString(String str, int x, int y): is used to draw the specified string.
void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height.
void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height.
void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
void boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
void setColor(Color c): is used to set the graphics current color to the specified color.
7
void setFont(Font font): is used to set the graphics current font to the specified font.
import java.applet.*;
import java.awt.*;
public class demo extends applet
{
public void paint(Graphics g)
{
g.drawString("welcome",100,100);
}
}
X coordinate ,Y coordinate to draw something on window, the upper leftmost corner is always taken as a starting point every
applet has its own area on the screen known as canvas where it creates a display. The java Coordinate system has the origin(0,0)
in the upper left corner. The X coordinate increases horizontal to the right and the Y co-ordinate increases vertically downwards.
Positive X and Y axis will be taken. The values of (X,Y) are in pixels.
8
Graphics in an applet
The java.awt.Graphics package provides methods to draw various shapes such as lines, rectangles, polygons and ovals on
the screen using X,Y coordinates. The values for X and Y are specified in pixels.
g.setColor(Color.red);
g.fillRect(100,50,200,100);
}}
9
//WRITE AN APPLET TO DRAW Red, Yellow and green Oval.
import java.awt.*;
import java.applet.*;
public class oval extends Applet
{
public void paint(Graphics g)
{
g.drawOval(100,100,75,50);
g.setColor(Color.red);
g.fillOval(100,100,75,50);
g.drawOval(100,160,75,50);
g.setColor(Color.yellow);
g.fillOval(100,160,75,50); 10
g.drawOval(100,220,75,50);
g.setColor(Color.green);
g.fillOval(100,220,75,50);
}
}
//WRITE APPLET PROGRAM TO COMPUTE ADDITION OF TWO NUMBER AND RETURN SUM.
import java.awt.*;
import java.applet.*;
public class num extends Applet
{
public void paint(Graphics g)
{
11
int a=10;
int b=20;
int sum=a+b;
String s= "sum = "+ String.valueOf(sum);
g.drawString(s,100,100);
}
}
12
//WRITE AN APPLET TO DRAW AN POLYGON.
import java.awt.Graphics;
import java.applet.*;
import java.awt.Color;
14
15
Java Programming
Course Code: IT 201
MODULE – IV
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is notified against ActionEvent. The
ActionListener interface is found in java.awt.event package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered component.
public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the ActionListener class, you need to follow 3
steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3
Java ActionListener Example: On Button click
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
4
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Java.");
}
}
5
Output
7
tf.setText("Welcome to Java.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
Output
8
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The
MouseListener interface is found in java.awt.event package. It has five methods.
9
Java MouseListener Example
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);
} 10
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");
}
11
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();
}
}
12
output
13
Java MouseListener Example 2
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
14
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseListenerExample2();
} }
Output
15
Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. The
MouseMotionListener interface is found in java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given below:
public abstract void mouseDragged(MouseEvent e);
public abstract void mouseMoved(MouseEvent e);
18
Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The ItemListener
interface is found in java.awt.event package. It has only one method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox
component.
19
Java ItemListener Example
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);
20
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) {
21
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();
}
}
22
Output:
23
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. The KeyListener
interface is found in java.awt.event package. It has three methods.
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
25
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed"); 26
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output
27
Java KeyListener Example 2: Count Words & Characters
import java.awt.*;
import java.awt.event.*;
28
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
} 29
public void keyTyped(KeyEvent e) {}
30
31
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Control Statement
________________________________________
If Else Statement
In Java, if statement is used for testing the conditions. The condition matches the statement it returns true else it
returns false. There are four types of If statement they are:
i. if statement
ii. if-else statement
iii. if-else-if ladder
iv. nested if statement
if Statement
In Java, if statement is used for testing conditions. It is used for only true condition.
Syntax:
if(condition)
{
//code
}
2
Example:
3
if-else Statement
In Java, the if-else statement is used for testing conditions. It is used for true as well as for false condition.
Syntax:
if(condition)
{
//code for true
}
Else
{
//code for false
}
public class IfElseDemo1 {
public static void main (String[] args)
{ 4
int marks=50;
if (marks > 65)
{
System.out.print("First division");
}
else
{
System.out.print("Second division");
}
}
}
5
if-else-if ladder Statement
In Java, the if-else-if ladder statement is used for testing conditions. It is used for testing one condition from multiple
statements.
Syntax:
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions 6
}
Nested if statement
In Java, the Nested if statement is used for testing conditions. In this, one if block is created inside another if block when the
outer block is true then only the inner block is executed.
Syntax:
if(condition)
{
//statement
if(condition)
{
//statement
}
}
7
Example:
8
Nested try block
In Java, there can be multiple try blocks. A try block within another try block is known as nested try block. In a program
when any block of code can cause an error and the entire program can cause another error then try blocks are made.
try
{
statements
try
{
Statements
try
{
statements
}
catch (Exception e)
{
}
9
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Example
class NestedDemo1
{
public static void main(String args[])
{
try{
10
try{
System.out.println("Divide 39/0");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
} try{
int a[]=new int[8];
a[8]=4;
}
11
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
12
For Loop
In Java, for loop is used for executing a part of the program again and again. When the number of execution is fixed then it is
suggested to use for loop. In java there are 3 types of for loops, they are as follows:
1. Simple for loop
2. For-each loop
3. labelled for loop
Syntax:
for(initialization; condition; increment/decrement)
{
//statement
}
13
Parameters:
1) Initialization
It is the initial condition which is executed only once at the starting of a loop. It is an optional condition.
2) Condition
It is used to test a condition each time while executing. The execution continues until the condition is false. It is an optional
condition.
3) Statement
It is executed every time until the condition is false.
4) Increment/Decrement
It is used for incrementing and decrementing the value of a variable. It is an optional condition.
14
Example for simple For loop
public class ForDemo1
{
public static void main(String[] args)
{
int n, i;
n=2;
for(i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+n*i);
}
}
} 15
Example for Nested for loop
public class ForDemo2
{
public static void main(String[]args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
} }
16
}
for-each Loop
In Java, for each loop is used for traversing array or collection. In this loop, there is no need for increment or decrement
operator.
Syntax:
for(Type var:array)
{
//code for execution
}
Example:
public class ForEachDemo1
{
public static void main(String[] args)
{
Int a[]={20,21,22,23,24};
17
for(int i:a)
{
System.out.println(i);
}
}
}
Syntax:
switch(expression)
{
case value1:
//code for execution;
break; //optional
case value2:
20
// code for execution
break; //optional
......
......
......
Case value n:
// code for execution
break; //optional
default:
code for execution when none of the case is true;
}
21
While Loop
In Java, While loop is a control statement. It is used for iterating a part of the program several times. When the number of
iteration is not fixed then while loop is used.
Syntax:
while(condition)
{
//code for execution
}
Example:
public class WhileDemo1
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
} 22
}
Example for infinite while loop
public class WhileDemo2
{
public static void main(String[] args)
{
while(true)
{
System.out.println("infinitive while loop");
}
}
}
23
do-while loop
In Java, the do-while loop is used to execute a part of the program again and again. If the number of iteration is not fixed then
the do-while loop is used. This loop executes at least once because the loop is executed before the condition is checked.
Syntax:
do
{
//code for execution
}while(condition);
Example:
public class DoWhileDemo1
{
public static void main(String[] args)
{
Int i=1;
do {
System.out.println(i);
i++;
}while(i<=10);
}
}
24
Break Statement
In Java, a break statement is used inside a loop. The loop is terminated immediately when a break statement is encountered
and resumes from the next statement.
Syntax:
jump-statement;
break;
Example:
public class BreakDemo1 {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==8){
break;
}
System.out.println(i);
}
}
} 25
Example using break in do while loop
public class BreakDoWhileDemo1
{
public static void main(String[] args)
{
int i=1;
do
{
if(i==15)
{
i++;
break;
}
System.out.println(i);
i++;
}while(i<=20);
}
}
26
continue Statement
In Java, the Continue statement is used in loops. Continue statement is used to jump to the next iteration of the loop
immediately. It is used with for loop, while loop and do-while loop.
jump-statement;
continue;
Example:
public class ContinueDemo1
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}}} 27
Example:
public class ContinueDemo2 {
public static void main(String[] args) {
xy:
for(int i=1;i<=5;i++){
pq:
for(int j=1;j<=5;j++){
if(i==2&&j==2){
continue xy;
}
System.out.println (i+" "+j);
}
} }
} 28
Java return Keyword
Java return keyword is used to complete the execution of a method. The return followed by the appropriate value that is
returned to the caller. This value depends on the method return type like int method always return an integer value.
Points to remember
o It is used to exit from the method.
o It is not allowed to use return keyword in void method.
o The value passed with return keyword must match with return type of the method.
Example
public class ReturnExample1 {
int display()
{
return 10;
}
29
public static void main(String[] args) {
ReturnExample1 e =new ReturnExample1();
System.out.println(e.display());
}
}
Output
10
30
Example
public class ReturnExample2 {
void display ()
{
return null;
}
public static void main (String [] args) {
ReturnExample2 e =new ReturnExample2();
e. display ();
}
}
Output:
Void methods cannot return a value
31
/* Java Program Example - Interchange Two Numbers */
import java.util.Scanner;
public class swap
{
public static void main(String args[])
{
int a, b, temp;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Value of A and B :\n");
System.out.print("A = ");
a = scan.nextInt();
System.out.print("B = ");
b = scan.nextInt();
temp = a;
a = b;
b = temp;
System.out.print("Number Interchanged Successfully..!!\n");
System.out.print("A = " +a);
System.out.print("\nB = " +b);
} 32
}
/* Java Program Example - Convert Fahrenheit to Centigrade */
import java.util.Scanner;
import java.util.Scanner;
public class table
{
public static void main(String args[])
{
int num, i, tab;
Scanner scan = new Scanner(System.in);
class table2{
static int sum=0; // static is required
static int t=2,p;
public static void main(String args[])
{
System.out.println(args[0]); // pass the base address i:e args[0]
}
}
}
// input java table2 10 output is tableof 2 i:e 2 4 6 8 10--------=20
35
/* Java Program Example - Calculate Arithmetic Mean */
import java.util.Scanner;
armean = sum/n;
37
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
38
System.out.println (numb1);
System.out.println (numb2);
39
// Java Program Example WAP enter character and Check Alphabet or Not
import java.util.Scanner;
public class alphabet
{
public static void main(String args[])
{
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Character : ");
ch = scan.next().charAt(0); // enter character x
import java.util.Scanner;
43
/* Java Program Example - Find Largest of Three Numbers */
import java.util.Scanner;
if(big<b)
{ 44
if(b>c)
{
big = b;
}
else
{
big = c;
}
}
else if(big<c)
{
if(c>b)
{
big = c; } 45
{
big = b;
}
}
else
{
big = a;
}
46
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods
to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest
way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long,
double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
We first create an object of scanner class then we used the methods of scanner class.
2
Consider the statement:
The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(),
next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.
3
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as a
string.
5
Example
import java.util.Scanner;
class in{
public static void main(String args[]){
Scanner a=new Scanner(System.in);
System.out.println("Enter your Enrollno");
int rollno= a.nextInt();
System.out.println("Enter your full name");
String name=a.next(); // accept single word Rahul in Rahul singh
System.out.println("Enter your fee");
double fee=a.nextDouble();
System.out.println("Enrollno:"+rollno+" name:"+name+" fee:"+fee);
a.close(); // Close the scanner
}
6
}
// Wap to get input from user integer ,float and string
import java.util.Scanner;
class input
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string "+s);
System.out.println("Enter an integer");
7
a = in.nextInt();
System.out.println("You entered integer "+a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
9
System.out.println("Enter a 1 value of float");
a = in.nextFloat();
System.out.println("You entered float ="+a);
10
The example of Scanner class (pp) with delimiter. The \s represents whitespace.
import java.util.*;
public class pp{
public static void main(String args[]){
String input = "20 apple 40 orange 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt()); //20
System.out.println(s.next()); // apple
System.out.println(s.nextInt()); // 40
System.out.println(s.next()); // orange
System.out.println(s.nextInt()); // 30
System.out.println(s.next()); // tea
System.out.println(s.next()); // biscuits
s.close();
11
}}
//WAP enter your name and and find average of three number
import java.util.Scanner;
public class average {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.print("Enter your name: ");
// String name=s.nextLine(); ---------------------- accept single word only AMIT
String name=s.nextLine(); // accept full string i:e full name AMIT SINGH
System.out.print("Enter marks in three subjects: ");
int marks1=s.nextInt();
int marks2=s.nextInt();
int marks3=s.nextInt();
12
double average = (marks1+marks2+marks3)/3.0;
System.out.println("\nName: "+name);
System.out.println("Average: "+average);
}
}
1.Buffer Memory : BufferedReader has larger buffer memory(8KB or 8192 chars) than Scanner which has (1KB or 1024 chars). It
means if you are reading a large String than you should use BufferedReader. If the user input is short or other than String, you
can use Scanner.
13
2. Functionality : BufferedReader is used to read the data only. Scanner not only read the data but also parse the data.
Scanner uses regular expression to read and parse text. It can use custom delimiter and parse text into primitive data type for
e,g short,long,int using nextShort(),nextLong(), nextInt() methods. BufferedReader can only read String using readLine()
method.
3. Performance : BufferedReader is faster than Scanner because BufferedReader does not need to parse the data.
4. Data type : BufferedReader can read only String. Scanner can read String as well as primitive data types (int, float, double,
long, short).
5. Introduction to JDK : BufferedReader was introduced in JDK 1.1 while Scanner was introduced in JDK1.5 .
6. Synchronization : BufferedReader is synchronized while Scanner is not. For multi-threading applications BufferedReader is
preferred.
7. Checked Exception : BufferedReader throws CheckedException(i.e IOException) while Scanner does not throw any
CheckedException.
8. Package : BufferedReader class is present in java.io package while Scanner class is present in java.util package.
14
We input from user using DataInputStream.java, BufferedReader and Scanner.
DataInputStream:
The readLine ( ) method of DataInputStream reads a line at a time and return as a string irrespective of what the
line contains.
Example
import java.io.*;
public class abc
{
public static void main(String args[]) throws IOException
{ //when we use throws IOException then we don’t use try catch
// dis is an object
DataInputStream dis = new DataInputStream(System.in);
// in is an object of input stream define in system class
System.out.println("Enter your name: ");
String str1 = dis.readLine(); //sheenu rizvi
15
System.out.println(" your name is " + str1); // your name is sheenu rizvi
System.out.println("Enter a number: ");
String str2 = dis.readLine(); //75
int x = Integer.parseInt(str2); // convert to integer
//parse is to convert string into integer
System.out.println("Enter a double value: ");
String str3 = dis.readLine(); //76.75
double y = Double.parseDouble(str3);// convert to double
if(x > y)
System.out.println("First number " +x + " is greater than second number " + y);
else
System.out.println("First number " +x + " is less than second number " + y);
BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it can get the
efficient reading of characters, arrays, etc. It inherits the reader class and makes the code efficient since we can
read the data line-by-line with the readline() method.
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
Example
import java.io.*;
import java.lang.*;
class kentry
{
public static void main(String args[ ])
{
BufferedReader o = new BufferedReader(new InputStreamReader(System.in));
18
OR
//InputStreamReader r= new InputStreamReader(System.in);
//BufferedReader o = new BufferedReader(r);
try
{
String name=" ";
int age=0;
float basic=0;
System.out.println("Enter Name");
name=o.readLine(); // read input line by user
System.out.println("Enter age");
age=Integer.parseInt(o.readLine());
System.out.println("enter salary");
basic=Float.parseFloat(o.readLine());
19
System.out.println("\n name= "+ name);
System.out.println("\n age= "+ age);
System.out.println("\n basic= "+ basic);
}catch(IOException e)
{
System.out.println(e);
}
}
}
20
Example
import java.io.*;
class ab
{
public static void main(String args[])throws Exception
{
int a,b,c;
BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter the two numbers to add:");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c = a+b;
System.out.println("\nSum of two numbers:"+ c);
}
21
}
//Command Line
import java.io.*;
public class rad
{
public static void main(String args[])
{
double radius;
double pi=3.14;
radius = Double.valueOf(args[0]).doubleValue();
double a=pi*radius*radius;
System.out.println(args[0]+"sqrtmeters"+" " + args[1]);
}
}
c>java>jdk1>bin> java rad 2 4 enter
22
( Value passed through command line)
Example
class fibonicci{
public static void main(String args[])
{ int a=0,b=1,c,s=0;
for(int i=1;i<10;i++)
{ c=a+b;
s=s+c;
a=b;
b=c;
}
System.out.println("The sum of fibonicci series upto 10 terms is:-"+s);
}
}
23
OUTPUT:-
c:\jdk1.2\bin>javac fibonicci.java
c:\jdk1.2\bin>java fibonicci
import java.io.DataInputStream;
class adigit
{
public static void main(String args[])
24
{
DataInputStream in =new DataInputStream(System.in);
int n=0;
int sum=0,r,c;
try{
System.out.println("enter number");
n=Integer.parseInt(in.readLine());
}catch(Exception e)
{System.out.println(e); }
c=n;
while(n>0)
{
r=n%10;
n=n/10;
sum=sum+r; 25
}
System.out.println("The number is " + c);
System.out.println("Sum of digit" + sum);
}
}
C:\Java\jdk1\bin>javac adigit.java
Note: adigit.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
C:\Java\jdk1\bin>java adigit
enter number
234
The number is 234
26
Sum of digit 9
Example
class marks
{
public static void main(String args[])
{
int m1=60,m2=70,m3=80,tot=0;
float per=0;
tot=m1+m2+m3;
per=tot/3;
if(per>80)
{
System.out.println("m1="+m1+" "+"m2="+m2+" "+"m3="+m3+" "+"total="+tot+" "+"percentage"+"="+per+"
"+"grade"+"="+"A");
27
}
else if(per>60 && per<=80)
{
System.out.println("m1"+"="+m1+" "+"m2"+"="+m2+" "+"m3"+"="+m3+" "+"total"+"="+tot+"
"+"percentage"+"="+per+" "+"grade"+"="+"B");
}
else if(per>45 && per<=60)
{
System.out.println("m1"+"="+m1+" "+"m2"+"="+m2+" "+"m3"+"="+m3+" "+"total"+"="+tot+"
"+"percentage"+"="+per+" "+"grade"+"="+"C");
}
else if(per>33 && per<=45)
{
System.out.println("m1"+"="+m1+" "+"m2"+"="+m2+" "+"m3"+"="+m3+" "+"total"+"="+tot+"
"+"percentage"+"="+per+" "+"grade"+"="+"D");
28
}
else if(per<=33)
{
System.out.println("YOU ARE FAIL");
}
}
}
Example
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
29
{
int n, c, fact = 1;
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
30
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
31
32
Java Programming
Course Code: IT 201
MODULE – IV
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Layout manager
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:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
2
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
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:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the
components.
Example of BorderLayout class:
4
import java.awt.*;
import javax.swing.*;
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");;
5
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
} 6
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the
components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns along with
given horizontal and vertical gaps.
7
Example of GridLayout class
import java.awt.*;
import javax.swing.*;
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");
8
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}} 9
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.
2 FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. 10
3 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical
gap.
11
import java.awt.*;
import javax.swing.*;
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");
12
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
13
}
}
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four
constants. They are as follows:
14
Example of BoxLayout class with Y-AXIS:
15
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
16
setVisible(true); }
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
17
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample2 extends Frame {
Button buttons[];
public BoxLayoutExample2() {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
18
setSize(400,400);
setVisible(true);
}
19
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each
component as a card that is why it is known as CardLayout.
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given name.
20
Example of CardLayout class
21
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
22
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
} 23
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
24
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each
component occupies one or more cells known as its display area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size.
25
Modifier and Type Field Description
gridbag constraints.
protected GridBagConstraints defaultConstraints It is used to hold a gridbag constraints
compatibility
protected static int MINSIZE It is smallest grid that can be
a per-component string.
protected void adjustForGravity(GridBagConstraints It adjusts the x, y, width, and
constraints, Rectangle r)
height fields to the correct
compatibility
GridBagConstraints getConstraints(Component comp) It is for getting the constraints
the x axis.
27
float getLayoutAlignmentY(Container parent) It returns the alignment along
the y axis.
int[][] getLayoutDimensions() It determines column widths
grid.
protected getLayoutInfo(Container parent, int sizeflag) This method is obsolete and
GridBagLayoutInfo
supplied for backwards
compatibility.
protected GetLayoutInfo(Container parent, int sizeflag) This method is obsolete and
GridBagLayoutInfo
supplied for backwards
compatibility.
Point getLayoutOrigin() It determines the origin of the
container.
double[][] getLayoutWeights() It determines the weights of
rows.
protected Dimension getMinSize(Container parent, GridBagLayoutInfo It figures out the minimum size
info)
of the master based on the
information from
getLayoutInfo.
28
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid); 29
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
30
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
31
setDefaultCloseOperation(EXIT_ON_CLOSE); } }
32
GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the
Group class.
Group is an abstract class and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another where as ParallelGroup aligns its child on top of each other.
The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.
GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing
the vertical axis. Each component must exists in both a horizontal and vertical group, otherwise an IllegalStateException is
thrown during layout, or when the minimum, preferred or maximum size is requested.
33
Nested Classes
static class GroupLayout.Alignment Enumeration of the possible ways Parallel Group can align its children.
Class GroupLayout.Group Group provides the basis for the two types of operations supported by
Class GroupLayout.SequentialGroup It is a Group that positions and sizes its elements sequentially, one after another
34
Fields
35
Constructors
36
Modifier and Type Field Description
void addLayoutComponent(Component component, It notify that a Component has been added to the parent container.
Object constraints)
void addLayoutComponent(String name, Component It notify that a Component has been added to the parent container.
component)
GroupLayout.Parall createBaselineGroup(boolean resizable, boolean It creates and returns a ParallelGroup that aligns it's elements along the
elGroup anchorBaselineToTop) baseline.
GroupLayout.Parall createParallelGroup() It creates and returns a ParallelGroup with an alignment of
elGroup
Alignment.LEADING
GroupLayout.Parall createParallelGroup It creates and returns a Parallel Group with the specified
elGroup
(GroupLayout.Alignment alignment) alignment.
GroupLayout.Parall createParallelGroup It creates and returns a ParallelGroup with the specified alignment and
elGroup
(GroupLayout.Alignment alignment, resize behavior.
boolean resizable)
GroupLayout.Seque createSequentialGroup() It creates and returns a SequentialGroup.
ntialGroup
boolean getAutoCreateContainerGaps() It returns true if gaps between the container and components that
positioning components.
float getLayoutAlignmentX(Container parent) It returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent) It returns the alignment along the y axis.
37
Dimension maximumLayoutSize(Container parent) It returns the maximum size for the specified container.
Java SpringLayout
A SpringLayout arranges the children of its associated container according to a set of constraints. Constraints are nothing
but horizontal and vertical distance between two component edges. Every constrains are represented by a
SpringLayout.Constraint object.
Each child of a SpringLayout container, as well as the container itself, has exactly one set of constraints associated with
them.
Each edge position is dependent on the position of the other edge. If a constraint is added to create new edge than the
previous binding is discarded. SpringLayout doesn't automatically set the location of the components it manages.
38
Nested Classes
39
Fields
40
Useful Methods
it should be discarded.
void layoutContainer(Container parent) It lays out the specified container.
Dimension maximumLayoutSize(Container It is used to calculates the maximum size dimensions for the specified container,
parent) given the components it contains.
Dimension minimumLayoutSize(Container It is used to calculates the minimum size dimensions for the specified container,
parent) given the components it contains.
Dimension preferredLayoutSize(Container It is used to calculates the preferred size dimensions for the specified container,
parent) given the components it contains. 41
42
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Objects and Classes in Java
In object-oriented programming technique, we design a program using objects and
classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
2
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:
o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
o 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. 3
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.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
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.
5
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
________________________________________
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
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.
6
Here, we are creating a main() method inside the class.
//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);
} }
Output:
0 7
null
Object and Class Example: 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.
9
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
class Student{
int id;
String name;
}
class TestStudent2 {
public static void main (String args[]){
Student s1=new Student();
s1.id=101;
s1.name="ABCD";
System.out.println (s1.id + " "+ s1.name); //printing members with a white space
}
}
Output: 10
101 ABCD
We can also create multiple objects and store information in it through reference variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="ABCD”;
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 ABCD
11
102 Amit
2) 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.
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"); 12
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
13
Object and Class Example: Employee
Example where we are maintaining records of employees.
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000); 14
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
output
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
15
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the
time of object creation only.
If you have to use an object only once, an anonymous object is a good approach.
For example:
16
Example of an anonymous object in Java.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
Output:
Factorial is 120
17
Creating multiple objects by one type only
Example:
//Java Program to illustrate the use of Rectangle class which has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
18
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();
}
}
Output:
55
45
19
Example
Java Program to demonstrate the working of a banking-system where we deposit and withdraw amount from our account.
Creating an Account class which has deposit() and withdraw() methods
class Account
{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
20
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
21
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
22
a1.withdraw(15000);
a1.checkBalance();
}
}
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
23
// ADDITION of two number using object and METHOD
class add1{
int a,b;
void add()
{
System.out.println("sum="+(a+b)); // output 30
}
}
class add2{
public static void main(String args[])
{
add1 ob=new add1(); // ob is object
ob.a=10;
ob.b=20; //initialize value using dot . opertor
ob.add();
}
} 24
Example
// ADDITION of two number using object and parametarised METHOD i;e passing arguments
class add1{
void add(int x ,int y)
{
System.out.println(x+y); // output 30
}
}
class add3{
public static void main(String args[])
{
add1 ob=new add1(); // ob is object
} 25
}
Example of Return
Class add1{
Int a,b;
Int area()
{
return a*b;
}}
Class add2{
public static void main (String args[])
{
add1 ob = new add1();
ob.a=5;
ob.b=10;
int mul = ob.area();
System.out.println(mul);
} }
26
Constructors 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-argument 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.
27
Rules for creating Java constructor
There are two rules defined for the constructor.
2. Parameterized constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
Output:
111 Karan 0
222 Aryan 25
34
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.
35
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another
like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
36
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i, String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
37
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan 38
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is
no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i, String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){ 39
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
40
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the class.
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//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);}
42
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
43
Program of the counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance
variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is
incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.
//Java Program to demonstrate the use of an instance variable which get memory each time when we create an object of the
class.
class Counter{
int count=0;//will get memory each time when the instance is created
Counter()
{
count++;//incrementing value
System.out.println(count);
}
44
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
1
1
45
Program of counter by static variable
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);
}
Output:
1
2
3
47
2) 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.
class Calculate{
static int cube(int x){
return x*x*x;
}
Output: 125 51
Restrictions for the static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
55
56
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
String class
In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:
char[] ch={'j','a','v','a','c','H','e','l',l','o'};
String s=new String(ch);
is same as:
String s="javacHello";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
2
The java. lang.String class implements Serializable, Comparable and
CharSequence interfaces.
3
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create
strings in java by using these three classes.
4
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.
For mutable strings, you can use StringBuffer and StringBuilder classes.
String s="welcome"; 5
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in
the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool, that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
6
2) By new keyword
1. String s=new String("Welcome");
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed
in the string constant pool. The variable s will refer to the object in a heap (non-pool).
7
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
output
java
strings
example
8
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No. Method Description
1 char charAt(int index) returns char value for the particular index
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end
index.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> returns a joined string.
elements)
9
10 boolean equals(Object another) checks the equality of string with the
given object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified
char value.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check
case.
17 String[] split(String regex, int limit) returns a split string matching regex and
limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index 10
starting with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index
starting with given index.
You can get substring from the given string object by one of the two methods:
public String substring(int startIndex): This method returns new String object containing the substring of the given string from
specified startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the
given string from specified startIndex to endIndex.
15
Java String class methods
The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations
on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based
or mobile application.
17
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output:
1010
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator)
etc.
2. By = = operator
3. By compareTo() method
20
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string for equality. String class
provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
21
} }
2) String compare by == operator
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
22
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is
less than, equal to or greater than second string.
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
23
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
24
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for
creating mutable string.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
26
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
27
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
28
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
29
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is
16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
} 30
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer
class except that it is non-synchronized. It is available since JDK 1.5.
The only thing that is needed is to replace keyword string buffer by string builder in all the methods in example.
31
Java String tokenizer
In Java, StringTokenizer is used to break a string into tokens based on provided delimiter. Delimiter can be specified
either at the time of object creation or on a per-token basis.
Its object internally maintains a current position within the string to be tokenized. It is located into java.util package.
In string, tokenizer objects are maintained internally and returns a token of a substring from the given string.
32
33
Following are the constructors in string tokenizer
1. StringTokenizer(String str)
2. String nextToken()
34
4. booleanhasMoreElements()
5. Object nextElement()
6. intcountTokens()
Example:
In this example, we are using Stringtokenizer to break string into tokens based on space.
import java.util.StringTokenizer;
35
public class TokenDemo1
{
public static void main(String args[])
{
StringTokenizer obj = new StringTokenizer("Welcome to Java "," ");
while (obj.hasMoreTokens())
{
System.out.println(obj.nextToken());
}
}
}
Output
Welcome to Java
36
Example to understand tokenizer, here we are breaking string into tokens based on the colon (:)
delimiter.
import java.util.*;
public class TokenDemo2{
public static void main(String args[])
{
String a= " : ";
String b= "Welcome : to : Java : . : How : are : You : ?";
StringTokenizer c = new StringTokenizer(b, a);
int count1 = c.countTokens();
for (int i = 0; i<count1; i++)
System.out.println("token [" + i + "] : "
+ c.nextToken());
37
StringTokenizer d= null;
while (c.hasMoreTokens())
System.out.println(d.nextToken());
}
}
38
Nested classes
A class defined within another class is known as Nested class. The scope of the nested class is bounded by the scope
of its enclosing class. Thus if class B is defined within class A, then B is known to A.
A nested class has access to the members ,including private members of the class in which it is nested.
Syntax:
class Outer{
//class Outer members
class Inner{
//class Inner members
}
39
Example of Inner class(Member class)
class Outer
{
public void display()
{
Inner in=new Inner();
in.show();
}
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}
40
class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
ot.display();
}
}
output
Inside inner
41
Example: How to check a number is even or odd using class and object in java.
import java.util.Scanner;
class Test {
int n, i, p = 1;
Scanner sc = new Scanner(System.in);
void input() {
System.out.print("Enter a number:");
n = sc.nextInt();
}
void check() {
if (n % 2 == 0) {
System.out.println("Number is even:" + n);
} else {
System.out.println("Number is odd:" + n);
}
} 42
}
class Main {
}
}
Output:
Enter a number:4
Number is even:4 43
Array of Objects in Java
Java is an object-oriented programming language. Most of the work done with the help of objects. We know that an array is a collection of the
same data type that dynamically creates objects and can have elements of primitive types. Java allows us to store objects in an array. In Java,
the class is also a user-defined data type. An array that conations class type elements are known as an array of objects. It stores the reference
variable of the object.
Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use
any of the following statements to create an array of objects.
Syntax:
44
Command line arguments
The command line argument is the argument that passed to a program during runtime. It is the way to pass argument to the
main method in Java. These arguments store into the String type args parameter which is main method parameter.
To access these arguments, you can simply traverse the args parameter in the loop or use direct index value because args is
an array of type String.
For example, if we run a HelloWorld class that contains main method and we provide argument to it during runtime, then
the syntax would be like.
import java.io.*;
class table1{
}
}
}
// input java table2 10 (single value 10 pass), output is tableof 2 i:e 2 4 6 8 10--------=20
48
// sum of inputted number through command line
class command{
//static int sum=0; // static is required
public static void main(String args[])
{
int sum=0;
for(int i=0;i<args.length;i++)
{
//System.out.println("args["+i+"] " +args[i]);
sum=sum+Integer.parseInt(args[i]);
}
//convert string args[i] to integer to add in integer sum
System.out.println("sum="+sum);
}
}
import java.io.*;
import java.util.*;
import java.io.File;
public class rfile
{
public static void main(String []args)
{
int b;
if(args.length!=1) // if name of file not pass with rfile student.txt
{
System.out.println("Program accept one command line argument exiting 1"); 50
System.exit(1);
System.out.println("hello");
//not show this message hello if string not pass with java rfile
}
File f=new File(args[0]);// f is an object and name of file passed with args[0]
if(f.isDirectory())
{
System.out.println(" it is directory ");
}
if (f.isFile())
{
System.out.println("Reading contents from file " + args[0]);
// pass name of file
51
try{
FileInputStream f1=new FileInputStream(f);
// f is object above
/* read() method reads the next byte of the data from inputstream and return in range of 0 to 255 as int. if no bytes is
present due to end of stream its return value -1. */
while ((b=f1.read())!=-1)
{
System.out.print((char)b); // b will display data
}
f1.close();
}catch(IOException e){
System.out.println(e);
}
} 52
else
{
System.out.println("file not present ");
}
}
}
Output
Compile: javac rfile.java
53
Java System.exit() Method
In Java, exit() method is in the java.lang.System class. This method is used to take an exit or terminating from a running program.
It can take either zero or non-zero value. exit(0) is used for successful termination and exit(1) or exit(-1) is used for unsuccessful
termination. The exit() method does not return any value.
Example:
In this program, we are terminating the program based on a condition and using exit() method.
import java.util.*;
import java.lang.*;
class ExitDemo1
{
public static void main(String[] args)
{
int x[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
54
for (int i = 0; i<x. length; i++)
{
if (x[i] >= 40)
{
System.out.println("Program is Terminated...");
System.exit(0);
}
else
System.out.println("x[" + i + "] = " + x[i]);
}
}
}
55
56
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Array
An array is a collection of similar data types. Array is a container object that hold values of homogeneous type. It is
also known as static data structure because size of an array must be specified at the time of its declaration.
Array starts from zero index and goes to n-1 where n is length of the array. In Java, array is treated as an object
and stores into heap memory. It allows to store primitive values or reference values.
Initialization of Array
Initialization is a process of allocating memory to an array. At the time of initialization, we specify the size of array to
reserve memory area.
Initialization Syntax
4
Create An Array
Lets create a single dimensional array.
class Demo
{
public static void main(String[] args)
{
int[] arr = new int[5];
for(int x : arr)
{
System.out.println(x);
} }
}
Output 0 0 0 0 0
5
In the above example, we created an array arr of int type and can store 5 elements. We iterate the array to access
its elements and it prints five times zero to the console. It prints zero because we did not set values to array, so all
the elements of the array initialized to 0 by default.
We can set array elements either at the time of initialization or by assigning direct to its index.
or
arr[1] = 105
Here, we are assigning a value to array’s 1 index. It is useful when we want to store dynamic data into the array. 6
Array Example
Here, we are assigning values to array by using both the way discussed above.
class Demo
{
public static void main(String[] args)
{
int[] arr = {1,2,3,4,5};
for(int x : arr)
{
System.out.println(x);
}
7
// assigning a value
arr[1] = 10;
System.out.println("element at first index: " +arr[1]);
}
}
Output
1
2
8
Accessing array element
we can access array elements by its index value. Either by using loop or direct index value. We can use loop like: for, for-
each or while to traverse the array elements.
class Demo
{
public static void main(String[] args)
{
int[] arr = {10,20,30,40,50};
9
for(int i=0;i<arr.length;i++)
{ //length give number of element stored in array
//length is not a method of the array object //rather length is an instance variable
System.out.println(arr[i]);
}
}
}
11
// The following code stores the numbers from 1 to 5 in a seven element int array.
13
The following for each iteration of the for loop
Syntax :
for(<data type> <variable name>:<array name>)
{
//code
}
Ex:
public class arr {
public static void main(String args[]) {
int[] a ={3,4,7,9};
for ( int x: a ) {
System.out.println(x);
}
}} 14
// WAP enter 5 values and display them.
import java.util.Scanner;
class array1
{
public static void main(String args[])
{
int i;
//int a[];
//a=new int[5]; // initialize array with name of array i:e a in int a[]
16
// Program for Linear Search
18
Program for Binary Search
public class arr1 {
public static void main(String args[]) {
int[] a = {2, 7, 20, 35, 45, 50, 85}; // a sorted array not containing duplicates
int target = 35; // the element to be searched
int left = 0;
int middle;
int right = a.length - 1;
while (left <= right) {
middle = (left + right) / 2;
if (a[middle] == target) {
System.out.println("Element found at index " + middle); //output element found at index 3
break;
} else if (a[middle] < target) { 19
left = middle + 1;
} else if (a[middle] > target) {
right = middle - 1;
}
}
} }
20
Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have multiple rows and multiple
columns unlike single dimensional array, which can have only one row index.
It represents data into tabular form in which data is stored into row and columns.
21
Initialization of Array
datatype[ ][ ] arrayName = new int[no_of_rows][no_of_columns];
The arrayName is the name of array, new is a keyword used to allocate memory and no_of_rows and no_of_columns both
are used to set size of rows and columns elements.
Like single dimensional array, we can statically initialize multi-dimensional array as well.
22
Example:
class Demo
{
public static void main(String[] args)
{
int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
for(int i=0;i<3;i++)
{
for (int j = 0; j < 5; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
// assigning a value
System.out.println("element at first row and second column: " + arr[0][1]);
}
}
23
12345
6 7 8 9 10
11 12 13 14 15
element at first row and second column: 2
24
Q1. Addition of two matrix
Q2. Subtraction of two matrix
Q3 Multiplication of two matrix
Wap enter numbers in 2*2 matrix and show their sum
import java.io.*;
import java.util.*;
public class twod
{
public static void main(String[] args)
{
int a[][] = new int[2][2];
int sum=0;
Scanner in = new Scanner(System.in);
System.out.println("enter values from keyboard");
25
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
a[i][j] = in.nextInt();
28
WAP enter name of 2 student and display them.
import java.io.*;
import java.util.*;
}
}
}
System.out.println("\n");
}
} } 30
Java Program Example - Concatenate String
import java.util.Scanner;
public class concat
{
public static void main(String args[])
{
String str1, str2;
Scanner scan = new Scanner(System.in);
System.out.print("Enter First String : ");
str1 = scan.nextLine();
System.out.print("Enter Second String : ");
str2 = scan.nextLine();
System.out.print("Concatenating String 2 into String 1...\n");
31
str1 = str1.concat(" "+str2);
32
/* Java Program Example - Find Length of String */
import java.util.Scanner;
System.out.print("Total Number of Words in Entered Sentence is " + countWords(sentence)); // sentence pass to function
}
}
Example
Print Odd and Even Numbers from an Array
public class oddeven{
public static void main(String args[]){
int a[]={2,3,6,7,4,5};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++){
35
if(a[i]%2!=0){
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++){
if(a[i]%2==0){
System.out.println(a[i]);
}
}
}}
//odd 3 7 5 even 2 6 4
36
Example to multiply two matrices of 3 rows and 3 columns.
*/
public class multiply{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
import java.io.*;
class largest1
{
public static void main(String args[]) throws IOException
{InputStreamReader reader =new InputStreamReader(System.in);
BufferedReader in =new BufferedReader (reader);
int i,large;
int mark[]= new int[5];
String text;
large=0;
for(i=0;i<5;i++)
{System.out.println("enter a number"); 39
text=in.readLine();
mark[i]=Integer.parseInt(text);
if(mark[i]>large)
large=mark[i];
}
System.out.println("largest value =" +large);
}
}
40
WAP to keep entering the strings till “STOP” is entered
import java.util.Scanner;
class string1
{
public static void main(String args[])
{
Scanner b= new Scanner(System.in);
String s[]=new String[10];
int i=0;
do
{s[i]=b.nextLine();
i++;
}while(!(s[i-1].equalsIgnoreCase("STOP")));
for(int y=0;y<i;y++)
System.out.println(s[y]);
41
}}
42
Java Programming
MODULE – I
1
Access Modifiers
Access modifiers in Java specifies the visibility or scope of variables and methods of a class i.e they control the
accessibility of members of a class. The concept of access modifiers implements data abstraction in Java. We can
impose different levels of protection on the members (fields, methods, constructors ) of a class so that we can
restrict the access to certain variables or methods from outside the class.
default access modifier: If we do not use any modifier with a class, variable or a method then, they can be accessed
by any other classes in the same package (a package is a collection of classes).
public access modifier: If a class, method or variable is declared as public, then they can be accessed from any
other class. However, if we are trying to access a public class in another package then that class has to be imported.
2
private access modifier: This is most restrictive and private variables or methods cannot be accessed even by
the objects of the same class. They can be accessed only by the public methods of that class. Using private
modifier with variables, an object hides data from the external world (data abstraction). A good object oriented
design strategy is to make fields private and provide access to them using public methods.
protected access modifier: This modifier makes the variables and methods accessible to all classes and
subclasses in the same package and also to subclasses in the other packages. Subclass is a class derived from
another class.
3
Inheritance
Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class
to inherit property of another class. When a Class extends another class it inherits all non-private members including fields
and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to
describe inheritance in Java.
Inheritance in Java
4
Let us see how extends keyword is used to achieve Inheritance. It shows super class and sub-class relationship.
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class
}
5
Now based on above example. In OOPs term we can say that,
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Purpose of Inheritance
1. It promotes the code reusabilty i.e the same methods and variables which are defined in a parent/super/base
class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Disadvantages of Inheritance
Main disadvantage of using inheritance is that the two classes (parent and child class) gets tightly coupled.
This means that if we change code of parent class, it will affect to all the child classes which is inheriting/deriving
the parent class, and hence, it cannot be independent of each other.
6
Example
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
7
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
output
Child method
Parent method
8
9
1) Single Inheritance
public class A{
…………
……………
}
public class B extends A {
………..
………..
}
11
12
Example of inheritance
class parent
{
public void a()
{
System.out.println("Parent method");
}
}
public class child extends parent {
public void b()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
child cobj = new child();
cobj.b(); //method of Child class
cobj.a(); //method of Parent class
}
13
}
/*output
child method
parent method
*/
private members
The private members of the superclass remain private (accessible within the superclass only) in the superclass
and hence are not accessible directly to the members of the subclass.
However, the subclass can access them indirectly through the inherited accessible methods of the superclass.
class Base
{
private int numl; //private member
public void setData(int n)
{
numl = n; //private member accessed within the class
}
14
public int getData()
{
return numl; //private member accessed within the class
} }
// output
// Sum = 60
Protected variable can be accessed only by code in a subclass or the same package.
A protected field or method in a public class can be accessed directly by all classes within the same package
and its subclasses even if the subclasses are in different packages.
It is more restrictive than default (or package) access.
class Num //super class
{
protected int x, y; //protected Members
16
Num(int a, int b)
{
x=a;
y=b;
}
public void showxy()
{
d.showxy();
d.add();
d.show();
}
}
/*
output
x=5
y=6
z=11
19
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
class parent
{
String name;
int a;
}
public class child1 extends parent {
String name;
/* output
value = 10
*/
21
Method overriding
Declaring a method in sub class which is already present in parent class is known as method overriding.
Overriding is done so that a child class can give its own implementation to a method which is already provided by
the parent class. In this case the method in parent class is called overridden method and the method in child class
is called overriding method. Only the method in the subclass will be executed by default.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
22
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
23
// output
Boy is eating
/*
in above example, We have two classes: A child class Boy and a parent class Human.
The Boy class extends Human class. Both the classes have a common method void eat().
Boy class is giving its own implementation to the eat() method or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here. Child class wants to give its own implementation so that when it
calls this method, it prints Boy is eating instead of Human is eating.
*/
Method overriding is example of runtime polymorphism because during method call which method (parent class or
child class) is to be executed is determined by the type of object.
24
Method Overloading :
Method Overloading is a feature that allows a class to have more than one method having the same name, if their
argument lists are different.
class sample
{
public static void main(String args[]) 25
{
overload1 obj = new overload1();
obj.disp('z');
obj.disp('z',12);
}
}
/*
Output:
z
z 12
*/
26
Example 2: Overloading – Difference in data type of parameters
In this example, method disp() is overloaded based on the data type of parameters –
We have two methods with the name disp(), one with parameter of char type and another method with the parameter
of int type.
*/
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
class sample2
27
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
/*
Output:
a
5
*/
28
Abstract Class:
class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods (methods
without body) as well as concrete methods (regular methods with body).
abstract class a
{
abstract void call(); // abstract method i:e no coding here
void call2()
{
System.out.println("this is a concrete method. ");
}
}
29
class b extends a // Write code in extends
{
void call()
{
System.out.println("b's implementation of call. ");
}
}
class abstractdemo
{ //abstract class has no object
public static void main(String args[]) // It cannot be initiate
{ // abstract class is class which has abstract method
b b1=new b(); //object created
b1.call();
b1.call2();
}
}
/*output
b's implement of call
this is concrete method
30
*/
Java Final Modifier
Final modifier is used to declare a field as final. It can be used with variable, method or a class.
If we declare a variable as final then it prevents its content from being modified. The variable acts like
a constant. Final field must be initialized when it is declared.
If we declare a method as final then it prevents it from being overridden.
If we declare a class as final the it prevents from being inherited. We can not inherit final class in Java.
Final variable
In this example, we declared a final variable and later on trying to modify its value. But final variable cannot be
reassigned so we get compile time error.
public class Test {
final int a = 10;
public static void main(String[] args) {
Test test = new Test();
test.a = 15; // compile error 31
System.out.println("a = "+test.a);
}
}
Output
error: The final field Test. a cannot be assigned
32
Final Method
A method which is declared using final keyword known as final method. It is useful when we want to prevent a method
from overridden.
Ex
Class A{
final void meth( )
{ System.out.println(“This is final method”);
}
}
Class B extends A{
void meth()
{ 33
//cant over ride error
System.out.println(“illegal”);
} }
34
Final Class
A class can also be declared as final. A class declared as final cannot be inherited. The String class
in java.lang package is an example of a final class.
Ex
Final class A{
//….
}
Class B extends A{
//error cant sub class A
}
// it is illegal for B to inherit A since A is declared as final.
35
Static Blank Final Variable
A blank final variable declared using static keyword is called static blank final variable. It can be initialized in static
block only.
Static blank final variables are used to create static constant for the class.
Example
In this example, we are creating static blank final variable which is initialized within a static block, we used class
name to access that variable because for accessing static variable we don’t need to create object of that class.
public class Demo{
// static blank final variable
static final int a;
static {
// initialized static blank final
a = 10;
}
36
public static void main(String[] args) {
System.out.println("a = “ + Demo.a);
}
}
Output
a=10
37
Runtime polymorphism with the help of abstract classes
import java.io.*;
abstract class a
{
abstract String getdata();
public void print()
{
System.out.println("I am in abstract class a\n");
System.out.println(getdata());
System.out.println("I am back in abstract class a");
}
}
class b extends a
38
{
String getdata()
{
System.out.println("I am in getdata method of class b");
return("Hello...the vaue returned to class a\n");
}
}
public class abst
{
public static void main(String args[])
{
System.out.println("\n showing runtime polymorphism\n");
b b1=new b();
b1.print();
}
}
39
40
Java Programming
Course Code: IT 201
MODULE – I
Dr. Sheenu Rizvi
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow.
1
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
2
Runtime Polymorphism in Java
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
3
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
Upcasting in Java
4
class A { }
class B extends A{ }
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type.
For Example:
interface I{ }
class A{ }
class B extends A implements I{ }
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object. 5
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its
run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the subclass method is invoked at
runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
8
(a, b) -> a+b // parameters without types, can be used to sum and concat two strings as well.
(int a, int b) -> return (a+ b); // lambda expression with return statement
(int []) -> {multiple statements; return index;} // it can have multiple statements
In these sample examples, we have variety of lambda expression such as zero argument and single statement, multiple
arguments, lambda with return statement, etc. although return statement is optional and it can have multiple statements as
well.
From Java 8 and later, we can implement such abstract methods using a lambda expression. This is the
strength of lambda expression, notice it does not have any name that's why it is also known as an
anonymous function.
9
Example.
interface Runnable{
public void run();
}
public class Demo {
public static void main(String[] args) {
int speed=100;
// new approach (lambda expression) to implement
Runnable r=()->{
System.out.println("Running at the speed of "+speed);
};
r.run();
}
}
10
Output: Running at the speed of 100
Example: Lambda Expression With Parameter
Lambda Expression can have zero, one, or multiple parameters as we do with methods. Type of parameter is inferred by the
lambda so it is optional, we may or may not mention parameter. See the example wherein second lambda expression we
mentioned type of parameter.
interface Runnable{
public void run (int speed);
}
public class Demo {
public static void main(String[]args) {
int speed=100;
// lambda expression:
Runnable r=(carSpeed)->{
System.out.println("Running at the speed of "+ carSpeed);
}; 11
r.run (speed);
// specifying type of parameters
Runnable r1=(int carSpeed)->{
System.out.println("Running at the speed of "+ carSpeed);
};
r1.run(speed);
}
}
output:
Running at the speed of 100
100
12
Lambda Expression using return Statement
The return statement is optional with a lambda expression. We may use it to return a value to the caller, in this
example, we used two lambda expressions in which first does not use return statement but the second one use
return statement.
interface Runnable {
public String run (int speed, int distance);
}
public class Demo {
public static void main(String[] args) {
1
What is an Applet?
Unlike a Java application program, an applet is specifically designed to be executed within an HTML web document
using an external API.
They are basically small programs – more like the web version of an application – that require a Java plugin to run on
client browser. They run on the client side and are generally used for internet computing.
You can execute a Java applet in a HTML page exactly as you would include an image in a web page. When you see a
HTML page with an applet in a Java-enabled web browser, the applet code gets transferred to the system and is
finally run by the Java-enabled virtual machine on the browser.
2
Applets are also compiled using the javac command but can only run using the applet viewer command or with a
browser.
A Java applet is capable of performing all kinds of operations such as play sounds, display graphics, perform
arithmetic operations, create animated graphics, etc.
You can integrate an applet into a web page either locally or remotely. You can either create your own applets
locally or develop them externally. When stored on a local system, it’s called a local applet.
The ones which are stored on a remote location and are developed externally are called remote applets.
3
Browsers come with Java Runtime environment (JRE) to execute applets and these browsers are called Java-
enabled browsers.
The web page contains tags which specify the name of the applet and its URL (Uniform Resource Locator) – the
unique location where the applet bytecodes reside on the World Wide Web.
In simple terms, URLs refer to the files on some machine or network. Unlike applications, Java applets are
executed in a more restricted environment with harsh security restrictions. They cannot access the resources on the
system except the browser-specific services.
4
What is an Application?
It is a stand-alone Java program that runs with the support of a virtual machine in a client or server side. Also
referred to as an application program, a Java application is designed to perform a specific function to run on any
Java-compatible virtual machine regardless of the computer architecture.
An application is either executed for the user or for some other application program. Examples of Java applications
include database programs, development tools, word processors, text and image editing programs, spreadsheets,
web browsers etc.
5
Java applications can run with or without graphical user interface (GUI). It’s a broad term used to define any kind
of program in Java, but limited to the programs installed on your machine.
Any application program can access any data or information or any resources available on the system without any
security restrictions.
Java application programs run by starting the Java interpreter from the command prompt and are compiled
using the javac command and run using the java command.
Every application program generally stays on the machine on which they are deployed. It has a single start point
which has a main() method.
6
Difference between Application and Applet
Definition of Application and Applet – Applets are feature rich application programs that are specifically designed to be
executed within an HTML web document to execute small tasks or just part of it. Java applications, on the other hand, are
stand-alone programs that are designed to run on a stand-alone machine without having to use a browser.
Execution of Application and Applet– Applications require main method() to execute the code from the command line,
whereas an applet does not require main method() for execution. An applet requires an HTML file before its execution.
The browser, in fact, requires a Java plugin to run an applet.
Compilation of Application and Applet–Application programs are compiled using the “javac” command and further executed
using the java command. Applet programs, on the other hand, are also compiled using the “javac” command but are
executed either by using the “applet viewer” command or using the web browser 7
Security Access of Application and Applet – Java application programs can access all the resources of the system including
data and information on that system, whereas applets cannot access or modify any resources on the system except only
the browser specific services.
Restrictions of Application and Applet – Unlike applications, applet programs cannot be run independently, thus require
highest level of security. However, they do not require any specific deployment procedure during execution. Java
applications, on the other hand, run independently and do not require any security as they are trusted.
8
9