JAVA Material VR-17 PDF
JAVA Material VR-17 PDF
1. Introduction to OOP:
OOP Stands for Object Oriented Programming.
The main aim of OOPs is to design the object oriented programming languages (OOPL).
If any language supports all the OOPs principles is known as object oriented programming languages.
Examples: C++, JAVA, PHP, .NET, Python, Android, Selenium, Hadoop. Etc.
The main objective of OOP is to store the client input data in the form of “Objects” instead of
functions and procedures.
In OOPs, every object has data and behavior (methods), identify by a unique name, which achieves
through class and happened at object creation.
OOP is focuses mainly on classes and objects.
OOPs mainly used to develop System Softwares like driver softwares, operating system, compiler
softwares, interpreter softwares etc.
Page 1
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
2.2 Object Oriented Programming:
Object oriented programming language like C++ and Java uses classes and objects in the programs.
A class is a module that which contains collection of methods (functions) and data (variables) to
perform a specific task.
The main task is divided in to several modules and these are represented as classes.
The method of class that contains the logic to perform operations and variable is used to handle the
client data.
The Object is a memory holds the end users data as part of main memory.
The goal of this methodology is to achieve reliability, reusability and extensibility.
It is easy to modify and extend the features of application, which is possible with Inheritance principle
and no need any recreation.
2.3 Comparison:
Page 2
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3. OOPS Principles (Features):
Object Oriented Programming Structure (OOPS) is a concept with collection of principles named as
follows:
1) Class/Object
2) Encapsulation
3) Data Abstraction
4) Inheritance
5) Polymorphism
3.1 Class/Object:
3.1.1 Object:
Object is a memory that holds the end users data as a part of main memory (RAM).
Every object has properties and can perform certain actions.
The properties can be represented by variables in our programming.
For example: String name; int age; char sex;
The actions of object are performed by methods. For example, ‘Ravi’ is an object and he can perform
some actions like talking( ), walking( ), eating( ). etc.
So an object contains both variables and methods.
3.1.2 Class:
Page 3
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
It is mandatory to write every java program in the form of class then only JVM allows us to store the
end users data in the form of objects.
Syntax of class:
class classname
{
// List of variables
// List of Methods
}
Example of class:
class Person
{
String name;
int age;
char sex;
void talk( )
{
------
------
}
void eat( )
{
------
------
}
void walk( )
{
------
------
}
}
In the above example, a person class has 3 variables and 3 methods. This class code stored in JVM’s
method area. When we want to use this class, we should create an object to the class as follows:
The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before
executing the next time. So that it is highly recommended to access a single method of the class at a
time.
Page 4
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
‘Referenced’ and ‘unreferenced’ object is created by JVM in main memory based on its syntax.
In the above syntax 2, JVM will create a new object for the properties of the given class.
In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.
1) raju.walk( );
2) raju.talk( );
3) new Person( ).walk( );
In the above figure, multiple users are sending the request to the Banking application and the data will
be stored in the main memory in the form of objects and later it will be stored in the secondary
memory (Database).
Note: Without storing the data in the temporary memory, it will never be stored in the permanent
memory.
Page 5
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3.2 Encapsulation:
Example: Write a java class that the variables of the class are not available to any other program.
class Person
{
//variable declarations
private String name = “Vignan”;
private int age = 2002;
//Method
public void talk( )
{
System.out.println(“ Hello, I am” +name);
System.out.println(“ My year of establishment is:” +age);
}
}
class Customer
{
String name;
int accno;
float bal;
int mobno;
String email_id;
String addr;
Page 6
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void fundsTransfer( )
{
---------------
---------------
}
void updateContactDetails( )
{
---------------
---------------
}
}
In the above program, the variables ‘accno’ and ‘bal’ are necessary for fundsTransfer( ) method and
the remaining variables are not necessary (hidden).
The variables ‘mobno’, ‘email_id’ and ‘addr’ are necessary for updateContactDetails( ) method and
the remaining variables are not necessary.
3.4 Inheritance:
Creating or deriving a new class from the existing class is known as “Inheritance”.
So a new class can acquires the properties of the existing class and its own properties also.
In JAVA, Inheritance can be achieved by using “extends” keyword.
The class which is giving the properties is known as “parent/base/super” class.
The class which is acquiring the properties is known as “child/sub/derived” class.
The advantages of using inheritance are Code Re-usability, Re-Implementation and Extensibility.
class A
{
int a;
int b;
void method1( )
{
// method body
}
}
class B extends A
{
int c;
Page 7
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void method2( )
{
// method body
}
}
3.5 Polymorphism:
In java point of view, if the same method name is existed multiple times with different implementation
(logic) is known as “polymorphism”.
It can be categorized into two types: Static Polymorphism and Dynamic Polymorphism.
3.5.1 Static Polymorphism:
Whatever the method is verified at compile time and the same method is executed at runtime by
following polymorphism principle is known as “static polymorphism/compile time
polymorphism/static binding”.
In JAVA, static polymorphism can be achieved by using overloading.
Example: A java class on method overloading
class A
{
void f1(int x)
{
---------
---------
}
void f1(float y)
{
---------
---------
}
}
3.5.2 Dynamic Polymorphism:
Verifying super class method at compile time and executing derived class method at runtime by
following polymorphism principle is known as “Dynamic polymorphism or Runtime
polymorphism or late binding”.
In JAVA, Dynamic polymorphism can be achieved by using overriding.
Example: A java class on method overriding
class A
{
void f1(int x)
{
---------
---------
}
}
class B extends A
{
void f1(int x)
{
---------
---------
}
}
Page 8
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4. Introduction to Software:
Def of software:
Software is a collection of programs. A program is a collection of instructions used to perform an
operation.
Either programs or softwares can be designed by using programming languages.
Examples: C, C++, JAVA, VC++, .NET etc.
Types of softwares:
Software is divided in to two categories. 1) System Software 2) Application Software
4.1 System Softwares:
These are the softwares can be designed for physical hardware devices (embedded systems).
In real time, these softwares are mostly designed by using C/C++.
Examples: operating system, compilers, system drivers. Etc.
4.2Application Softwares:
These are the softwares can be designed for end users and these are again categorized into two types
named as:
a) Standalone (or) Desktop applications
b) Distributed (or) Internet based applications.
In real time, these softwares are mostly designed by using JAVA.
4.2.1 Standalone (or) Desktop applications:
These applications runs in a single computer and whose results are not sharable in multiple other
computers.
In real time mostly these are designed by using ‘.NET’ language.
Examples: Media player, M.S. office, calculator applications, etc.
4.2.2 Distributed (or) Internet based applications:
This is an application runs in a single computer but whose results can be shared in multiple other
computers.
These distributed applications are again divided in to two: Web applications and Enterprise
applications.
Web Application: This is an internet based application designed commonly for every end user in the
world. Examples: Facebook, YouTube, google, etc.
Enterprise application: This is an internet based application designed for specific organizations,
which means only limited end users can access these applications. Examples: Banking applications,
income tax applications, company mailing applications, etc.
Page 9
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
So finally java is a universal programming language can be used to design any of above softwares. But
it is very famous to design internet based applications.
5. History of JAVA:
JAVA is a programming language used to design the softwares; the main purpose of software is to
perform business-oriented operations in very less time.
Examples: Operating bank operations through online, searching a job through online, purchasing a
product through online etc.
Java was originally initiated in the year 1991 and it is designed by “Mr. James Gosling” and his team
members ‘Mr. Bill Joy’, ‘Mr. Mike Sheradin’, ‘Mr. Patrick’. N in the year 1995 at “SUN MICRO
SYSTEMS” named as JAVA 1.0.
The initial name was Oak but it was renamed to Java in 1995.
Right now SUN MICRO SYSTEMS was taken over by “ORACLE CORPORATION”.
JAVA 1.0:
In 23rd Jan 1996, Java Development Kit (JDK) 1.0 was released for free by the SUN
MICROSYSTEMS and named as OAK. It includes predefined 8 packages and 212 classes.
MICRSOFT and other companies licensed JAVA.
JAVA 1.1:
In 19th Feb 1997, JDK 1.1 was released with predefined 23 packages and 504 classes. It includes the
features of inner classes, event handling, improved JVM, AWT, JDBC, JAVA Bean Classes etc.
Microsoft developed its own 1.1 compatible JVM for internet explorer.
JAVA 1.2 (J2SE):
In 8th Dec 1998 JDK 1.2 was released with predefined 59 packages and 1520 classes.
It includes the features of Swings for improved graphics, JIT Compiler and Multithread methods like
suspend( ), resume( ) and stop( ) of Thread class.
JAVA API includes collection frameworks such as list, sets and hash map.
JAVA 1.3:
In 8th May 2000 JDK 1.3 was released with predefined 76 packages and 142 classes.
It includes the features of JAVA Sound (input and output of sound media), Java Naming and Directory
Interface (JNDI) and Java Platform Debugger Architecture (JPDA), etc.
JAVA 1.4:
In 6thFeb 2002 JDK 1.4 was released with predefined 135 packages and 2991 classes.
It includes the features of XML support, ‘assert’ keyword, Regular Expressions, Exception Handling,
Reading and writing image files etc.
JAVA SE 5 (Java 1.5):
In 30thSep 2004, JSE5 was released with predefined 165 packages and 3000 classes.
It includes the features of Generics, Annotations, Metadata, Auto boxing, Un-boxing, improved
collection framework, formatted I/O, for-each loop, Concurrency utilities etc.
JAVA SE6:
In 11thDec 2006, Java SE6 was released with features of scripting language support, JDBC 4.0
support, JVM improvements including Synchronization and compiler performance optimizations,
Garbage collection algorithms, etc.
Page 10
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
JAVA SE 7:
In 28thJul 2011, Java SE7 was released with features of JVM support for dynamic language, new
library for parallel computing on multi core, compressed 64 bit pointers, Automatic resource
management, Multi-catch Exception, underscore in numeric literals etc.
JAVA SE 8:
In 18thMar 2014, Java SE8 was released with features are lambda expressions, Enhanced security,
JDBC-ODBC bridge has been released etc.
5.1 Parts of JAVA:
SUN Micro Systems has divided java into 3 parts named as Java SE, Java EE and Java ME.
Java SE:
It is known as “Java Standard Edition”. It is used to develop basic java classes, standalone
applications, simple network based applications, standard APPLETS.
Java EE:
It is known as “Java Enterprise Edition”. It is used to develop Internet based applications on
providing business solutions.
Java ME:
It is known as “Java Micro Edition”. It is used to develop portable applications such as PDA or
Mobile devices. Code on these devices needs to be small in size and should take less memory.
6. JAVA Features:
Java is very famous in the market even multiple other programming languages are available because of
following features.
1) Simple
2) Object Oriented
3) Platform Independent
4) Architectural Neutral
5) Robust
6) Multi-Threaded
7) High Performance
8) Dynamic
9) Distributed
10) Secured
6.1 Simple:
Java is easy to learn and its syntax is quite simple, clean and easy to understand.
The ambiguous concept of C++ has been re-implemented in java in a clear way.
Java is simple programming language because of following reasons:-
Page 11
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) It supports very huge API (Application Program Interface) also known as java library. So that
application development becomes very easy and burden on the developer is reduced.
2) Java is free from pointers. It means java makes the developer free from writing of pointer code.
Therefore, the burden on the developer and code complexity is reduced.
Note: Java supports pointers and it will be handled internally / implicitly by the JVM.
Every java program can be written in simple English language. So that it is easy to understand by
developers.
Page 12
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
6.5 Robust:
Java is very strong because of exception handling mechanism.
If any error is generated at that time of compilation of program is known as “Compile time error /
Syntax error”. These errors are raised because of violating the syntax rules given by programming
languages. Example: Semicolon missing, writing keyword in uppercase, etc.
If any error is generated at run time is known as “Run time error / Exception”. Generally these are
raised because of providing invalid inputs by the end user.
Whenever exception is raised system defined / generated error message will be given to the end user, it
is unable to understandable. So that this message must be converted into user friendly message.
Exception Handling is a mechanism used to convert system defined error message into user friendly
error message.
In java it can be achieved by using “try-catch”.
6.6 Multi-Threaded
Java is a multi-threaded programming language. It means if the same program of same application
running simultaneously is known as “Multi-Threading”.
In the end user point of view, thread is a request.
In java point of view, thread is a “flow of execution”.
The main advantage with multi-threading is end users waiting time is reduced while performing
business oriented operations.
Page 13
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Garbage Collector: It is a predefined method in Java, runs automatically in the background of every
java program and deallocates un-used memory spaces.
6.8 Dynamic
Java is dynamic because of supporting “Runtime memory allocations”.
If the memory is allocated for input data at the time of compilation of program is known as “compile
time memory / static memory”.
If the memory is allocated for input data at the time of running of the program is known as “Dynamic
memory”.
Java strictly supports only “Dynamic Memory”.
6.9 Distributed:
Java is distributed. It means it supports to design distributed applications / network based applications
and it supports distributed architecture.
Based on the distance between the computer networks are categorized into LAN, MAN, WAN and
Internet.
Java supports to design all network categories based on two architectures.
1) Client-Server architecture
2) Distributed architecture.
Client-server Architecture:
In this architecture, multiple client machines depend on single server machine.
Client always sends the request to the server whereas server always gives the response to the client.
If any problem is occurred at server machine that will reflected on every client machine. This problem
is leads to “server down”.
Distributed Architecture:
In this architecture, multiple client machines depend on multiple server machines.
The main advantage is even if the problem is occurred at one server machine that won’t be reflected on
any client machine.
All client requests are shared to multiple server machines based on its distance.
Java supports to develop internet based applications. This architecture is mostly used in real time.
Page 14
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
6.10 Secured:
Java is more secured programming language among all other languages because of following reasons.
It is virus free programming language, which means if any application is designed by using java
language that does not allows virus in to the computer.
Java provides security to the applications in two ways. 1) Internal security 2) External security.
Internal Security: A security is provided by the data within the application is known as Internal
security. It can be achieved by OOPS.
External Security: Whenever security is provided to data by the outside applications is known as
external security. It can be achieved by Encryption and Decryption.
Encryption: Converting plain text into cypher text is known as encryption.
Decryption: Converting cypher text in to plain text is known as decryption.
Java supports all encryption and decryption techniques so that it provides high level external security
for the data.
JVM is a software available as a part of JDK software and it is a heart of entire Java program
execution process.
JVM is a platform dependent software mainly used to perform following operations:
1) Allocates sufficient memory space for the properties of class in main memory (RAM).
2) It takes the ‘.class’ file as an input and converting each byte code instruction in to the machine
language instruction that can be executed by the processor.
Page 15
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
First ‘javac’ converts the source code instructions in to ‘byte code’ and after successful compilation a
new ‘.class’ file will be created.
Now the ‘.class’ file is given to the JVM as an input and it converts in to machine level instructions.
The architecture of JVM is as follows:
In JVM, there is a module called “class loader sub system”, which performs the following functions:
1) First, it loads the “.class” file into main memory for all the properties of the class.
2) Then it verifies whether all byte code instructions are proper or not. If it finds any instruction
suspicious, the execution is rejected immediately.
3) If the byte code instructions are proper, then it allocates necessary memory to execute the program.
7.3 Heap:
This is the area where objects are created. In this area, memory is allocated for the ‘Instance Variables’
in the form of objects.
Page 16
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
7.5 Java Stacks:
Java stacks are memory area where Java methods are executed.
It also allocates the memory for ‘local variables’ and ‘object references’.
JVM uses a separate thread to execute each method.
C++ JAVA
1) C++ is platform dependent. 1) JAVA is platform independent.
2) It is mainly used to develop system 2) It is mainly used to develop application
softwares. softwares.
3) It is not a purely object oriented
3) It is a purely object oriented programming
programming language, since it is possible to
language, since it is not possible to write a
write C++ programs without using class or
java program without using class or object.
object.
4) Pointers are available in C++. 4) Java is free of pointers creation.
5) Allocation and deallocating memory is the 5) Allocation and deallocating memory will
responsibility of the programmer. be taken care of JVM.
6) C++ has goto statement. 6) C++ doesn’t have goto statement.
7) In some cases, implicit casting is available.
7) Automatic casting is available in C++. But it is advisable to the programmer should
use casting wherever required.
8) Multiple Inheritance feature is available in 8) Java doesn’t support Multiple Inheritance
C++. in class level. It can be achieved by interfaces.
9) Operator overloading is available in C++. 9) It is not available in java.
10) #define, typedef and header files are
10) These are not available in java.
available in C++.
11) C++ uses compiler only. 11) Java uses compiler and interpreter both.
12) C++ supports constructors and destructors. 12) Java supports constructors only.
Page 17
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
9. Structure of Java Program
9.1 Comments:
Writing comments is compulsory in any program. In java, there are three types of comments named as
single line, multi line and Java documentation.
1) Single line comments: These comments are used for marking a single line as a comment. These
comments starts with double slash symbol // until the end of the line.
Example: //Hello java programmer.
2) Multi line comments: These comments are used for representing several lines as comments. These
comments starts with /* and end with */.
Example: /* this multi line comment.
Hello java */
3) Java documentation comments: These comments starts with /** and ends with */. These are used
to provide description for every feature in a java program in JAVA API document.
Example: /** Description about a class */.
Page 18
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
9.3 example of java program structure
import packagename;
class ClassName1
{
List of variables;
List of methods;
}
class ClassName2
{
List of variables;
List of methods;
}
class MainClass
{
Public static void main(String args[])
{
-------
-------
}
Page 19
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
execute the code there, and substitute the result into the program. It increases the speed of the
processors time, no waste of memory and no code is copied.
“SUN MICRO SYSTEMS” given the following name conventions that must be followed while
writing java programs.
In the above naming conventions are mandatory while accessing predefined properties of Java API
but it is optional while creating user defined properties.
Page 20
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
11. Compilation of Java program:
Every java program is executed by JVM, but JVM can understand only “Byte Code” instructions.
‘Java compiler’ (javac) is responsible to convert the ‘source code’ instructions into ‘byte code’
instructions and also it will identify the ‘syntactical errors’ in the java program.
‘Byte code’ instructions represented in the form of “.CLASS” file whereas source code instructions
are represented in the form of ‘.java’ file.
Syntax to compile a program:
javac filename.java;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘Java compiler’
to compile the program.
Syntax to run a program:
After compilation of java program ‘JVM’ will execute the program and gives the result.
java filename;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘JVM’ to
execute the java program.
Example Programs
Program 1: Write a program to display the message
import java.lang.*;
class Sample1
{
public static void main(String args[])
{
System.out.println(“Welcome to Java Programming”);
}
}
OUTPUT:
javac Sample1.java
java Sample1
Welcome to Java Programming
Page 21
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
javac Sum.java
java Sum
30
- In the above program x+y performs the sum operation and the result is stored into z.
- ‘System’ is a class in ‘java.lang’ package and ‘System.out’ creates the PrintStream object which
represents the standard output device.
- System.out.println(z) is used to displays the value on the monitor.
}
}
OUTPUT:
javac Sum1.java
java Sum1
sum of two numbers=30
sum of two numbers=1020
sum of two numbers=30
- In the first display statement, “+” is used to join the string “sum of two numbers=” and the numeric
variable ‘z’. It is acting like a concatenation operation.
- In the second display statement, we are having sum of two numbers=” +x+y. Since left one is a string
and the next value of x is also converted in to a string; thus the value of x, i.e. 10 will be treated as
separate characters as 1 and 0 and are joined to string and also for the next variable y is 25. Thus we
get result as 1025.
- In the third display statement, we are having sum of two numbers=” +(x+y). The execution will start
from the inner braces. At left we got ‘x’ and right we got ‘y’, both are numbers and addition will be
done by the + operator, thus giving a result 35.
Page 22
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 4: Examples on System.out.println( ) statements:
Statement Output
1) System.out.println(“Hello”); Hello
2) System.out.println(“ “Hello” ”); Invalid
3) System.out.println(“ ‘Hello’ ”); ‘Hello’
4) System.out.println(“ \”Hello\” ”); “Hello”
5) System.out.println(“ \’Hello\’ ”); ‘Hello’
6) System.out.println(“ Hello \t friends ”); Hello friends
7) int x=10, y=40;
System.out.println(“ x ”); x
System.out.println(x); 10
System.out.println(“ x+y”); x+y
System.out.println(x+y); 50
System.out.println(“10” + “20”); 1020
System.out.println(“x=” +x); x=10
System.out.println(“y=” +y); y=40
System.out.println( x + “ ” +y); 10 20
System.out.println( x +y + “ ”); 30
System.out.println( “ ” +x +y); 1020
8) int rno=1; roll number is: 1
String name = “java”; name of the lab: java
System.out.println(“roll number is:” +rno);
System.out.println(“name of the lab:” +name);
9) System.out.println(“hello”); hello
System.out.println(“friends”); friends
System.out.println(“How are you”); How are you
10) System.out.print(“hello”); hellofriendsHowareyou
System.out.print(“friends”);
System.out.print(“How are you”);
Double quotations with in double quotations and single quotations with in single are not allowed in
java. But single with in double and double within single are allowed in Java.
Java supports escape sequences or backslash code to perform special operations:
Page 23
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
12. Variables in Java:
Variable is a container which holds the value while the java program is executed.
A variable is assigned with the data type.
A variable is used to identify the data either by the program or developer. So variable is a name of
memory location.
There are three types of variables in Java. They are:
1) Local variable
2) Static variable
3) Instance / Non-static variable
12.1 Local Variable:
If a variable defined or declared inside the method is known as “local variable” and also inside the
“formal parameters”.
Example on Local Variable
void method1( )
{
int x = 10; //local variable
}
Local variable must be initialized, why because JVM does not assign any default value for the local
variables.
Example on Formal Parameter
void method1( int x) // formal parameter
{
x = 10;
}
For local variables memory is allocated at that time of calling the method and memory is deallocated
once the control comes outside the method.
Local variables can be accessed only with in the same method.
In real time, it is recommended to define the local variable whenever that variable wants to be used
with in the single method at a time.
12.2 Instance / Non-static Variable:
If any variable defined outside the method and inside the class without ‘static’ keyword is known as
“Non-static variable” or “Instance Variable”.
For instance variables memory is allocated whenever a new object is created and memory is
deallocated once object is destroyed.
Instance variable can be accessed in any method of the same class.
Example:
class A
{
int x; //instance variable
void f1( )
{
x=20;
}
void f2( )
{
x=30;
}
}
Page 24
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
In real time, it is highly recommended to define the non-static variable whenever we want to maintain
a separate memory copy for that variable for every new object.
Page 25
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void insert( )
{
------
------
}
}
Def: It is a keyword in java which is used to represent the type of the data and it will tell to the JVM
how much memory should be allocated for the data.
Data types are categorized in to two types:
1) Primitive data types
2) Reference data types
Note: Every data type is keyword but not every keyword is a datatype.
Page 26
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
13.2.1 Primitive Data Types:
These are the data types whose variable can handle maximum one value at a time, these are
categorized into following 4 types:
1) Integer datatype
2) Floating point datatype
3) Character datatype
4) Boolean datatype
Integer Data Type: It is used to handle integer type of values without any fraction or decimal parts and
these are categorized into following types:
Example: byte rno=10; in this statement we declared a variable of type ‘byte’ for the variable ‘rno’
with the value 10.
Floating point Data Type: It is used to handle real type of values with fraction or decimal parts and
these are categorized into following types:
Example 1: float pi = 3.142f; in this statement the variable ‘pi’ which contains the value ‘3.142’. If ‘f’
is not written in the end, the JVM would have allocates 8 bytes of memory. The reason which is Java
takes default as ‘double’.
Example 2: Consider double distance = 1.96e8; this deceleration represents the scientific notation. It
means 1.96e8 means 1.96X108.
Character Data Type:
1) This is used to handle single character values at a time.
2) In java language, it can be represented with ‘char’ keyword.
3) In C-language, char data type occupies 1 byte of memory because of ASCII system. It means it
supports only international langua1ge characters English (256 characters).
4) In java language, char data type occupies 2 bytes of memory because of UNICODE system. It
means character data type in java allows 18 international languages. To store these characters 2
bytes of memory is required.
5) Range of char in java language: -215 to +215 – 1.
Boolean Data Type:
1) This is used to handle ‘boolean’ values like TRUE or FALSE.
2) It can be represented by using ‘boolean’ keyword.
3) True value always can be stored in the form of ‘1’and false can be stored in the form of ‘0’.
4) So 1-bit of memory is sufficient for boolean type.
5) Example: boolean response = true;
Page 27
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
13.2.3 String data Type:
It is used to handle the string type of data in java language and it will be treated as special data type
because of following reasons:
1) There is no fixed size for string data type. Example: “ABC”, “Vignan”… Etc.
2) Based on requirement it may acts a primitive data type or reference data type.
3) String not a keyword in java, it acts as a ‘predefined class’.
4) String is a collection of characters that must be enclosed in “double quotation”.
Note: The main purpose of maintaining sub data types is for handling efficient memory management.
That means based on the size of input values data type should be changed.
14. Identifiers:
Identifiers are name of the variable, method, classes, packages and interfaces.
For example: main, String, args and println( ) are identifiers in java program.
Identifiers are composed of letters, numbers, underscore, and the dollar ($) sign.
An identifier name must begin with the letter, underscore and dollar sign.
Example: age =20;
_age=20;
25age = 20; // Illegal
After the first character, an identifier can have any combination of characters.
Identifier always should exist in the left hand side of assignment operator.
Example: age = 30;
45 = age; // Illegal
No keyword should be assigned as an identifier.
Example: break = 15; // Illegal
In java, the maximum length of the identifier in java should be 32 characters.
No Spaces are allowed in the identifier declaration;
Example: my age = 20; // Illegal
Except underscore ( _ ) no special symbols are allowed in the middle of the identifier name.
Example: my_age = 20;
my@age = 20; //Illegal
my$age = 20; //Illegal
class Student
{
int rno;
String name;
float marks;
void setData( )
{
rno=1;
name=”james”;
marks=95.6f;
}
Page 28
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void display( )
{
System.out.println(rno);
System.out.println(name);
System.out.println(marks);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student( );
s1.display( )
s1.setData( );
s1.display( );
System.out.println(“………………….”);
System.out.println(“Hello Java”);
s1.display( );
System.out.println(“………………….”);
new Student( ).display( );
System.out.println(“………………….”);
new Student( ).setData( );
new Student( ).display( );
System.out.println(“………………….”);
s1.display( );
s1=null;
s1.display( );
}
}
Page 29
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
15.1 Integer Literals:
Integer literals represent the fixed integer values like 100, -53, 1235, etc.
All these numbers belonging to the decimal number system, which use (0 - 9) to represent any number.
Examples:
int dec = 26;
15.2 Float Literals:
Float literals represents fractional numbers. These are the numbers with decimal points like 2.1, -3.4,
etc, which should be used with float and double type variables.
Examples:
float f1 = 12.3f;
double x = 123.4;
15.3 Character Literals:
Character literals includes general characters like A, b, etc., special characters like @, ?, etc, escape
sequences like \n, \t etc.
These are enclosed in single quotations. But the escaping sequences can also be treated as string
literals.
15.4 String Literals:
String literals represent objects of “String” class. For example: “Hello”, “Never say die” etc. will
come under string literals, which can be stored directly in the string object.
These are enclosed in double quotations.
Example:
String a = “Hello java world”;
15.5 Boolean Literals:
It represents only two values namely: TRUE and FALSE. It means we can store either true or false
into boolean type variable.
Page 30
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example 1 on unary + + and - -
class Sample
{
public static void main(String args[])
{
int x=10;
System.out.println(-x);
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
OUTPUT:
-10
10
12
12
10
Example 2 on unary + + and - -
class Sample2
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);
}
}
OUTPUT:
22
21
Example 3 on !
class Sample3
{
public static void main(String args[])
{
boolean c=true;
boolean d=false;
System.out.println(!c);
System.out.println(!d);
}
}
OUTPUT:
false
true
Page 31
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
16.2 Arithmetic operator:
These are the operators used to perform fundamental arithmetic operations like addition, subtraction,
multiplication, etc.
It acts on the two operands at a time, called as binary operators.
While working with arithmetic operators the result type is depends on the following priorities of
datatypes.
Datatype Priority (High to Low)
1) double 1
2) float 2
3) long 3
4) int 4
5) short 5
6) byte 6
Examples:
- int + float -> float
- float / double -> double
- byte - short -> short
- long * double -> double
- float % int -> int // remainder should be in integer
- int % int -> int
- float % float -> int
- long % int -> long // long has highest priority
Example 1: Program on Arithmetic operators
class AirthmeticOperators
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}
}
OUTPUT:
15
5
50
2
0
Example 2: Program on Arithmetic operators
class SampleArithmetic
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
Page 32
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
21
Page 33
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
16.5 Relational operator:
These are used to check the conditions, it always returns either TRUE or FALSE.
The relational operators are of 6 types:
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
OUTPUT:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
Java AND Operator Example 1: Logical && and Bitwise &
class OperatorExample
{
public static void main(String args[ ])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
Page 34
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(a<b&a<c);//false & true = false
}
}
OUTPUT:
false
false
Java AND Operator Example 2: Logical && vs Bitwise &
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
OUTPUT:
false
10
false
11
Page 35
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
true
true
true
10
true
11
16.8 Ternary Operator:
This operator is can be used on 3 variables, it is also known as ‘conditional operator’;
Syntax: Expr1? Expr2 : Expr3;
In the above syntax, expr1 should be a condition, if it is TRUE then expr2 will be executed otherwise
expr3 will be executed.
Java Ternary Operator Example:
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
OUTPUT:
2
16.9 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.
Java Assignment Operator Example 1:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
OUTPUT:
14
16
Page 36
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Java Assignment Operator Example 2:
class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}
}
OUTPUT:
13
9
18
9
Page 37
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program on Widening Conversion
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
OUTPUT:
Int value 100
Long value 100
Float value 100.0
- If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
- This is useful for incompatible data types where automatic conversion cannot be done.
- Here, target-type specifies the desired type to convert the specified value to.
Page 38
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Double value 100.04
Long value 100
Int value 100
18.1.1 If Statement:-
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
if statement
if-else statement
else-if ladder
nested if statement
Simple If statement:
It can be used by performing any operation by checking each and every condition. It executes the logic
if the condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Page 39
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program:
class IfExample
{
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
OUTPUT:
Age is greater than 18
If else statement:
The Java if-else statement also tests the condition. It executes the code if condition is true otherwise
else block is executed.
In real time it can be used whenever we want to execute one logic among two logics.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example Program:
class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
OUTPUT:
odd number
Page 40
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
else-if statement:
In real time it can be used to execute only one logic among multiple logics.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
Example Program:
class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
Page 41
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
OUTPUT:
c grade
Nested-if statement:
In real time, if one ‘if-statement’ is existing inside another ‘if-statement’ is known as Nested-if
statement.
It can be used to improve the efficiency of simple if statement, if-else statement and else-if statement.
Syntax:
if(condtion1)
{
// executes when the condtion1 is true
ifcondtion2)
{
// executes when the condtion2 is true
}
}
Example Program:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
OUTPUT:
X = 30 and Y = 10
Page 42
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
18.1.2 Switch Statement:
It is same as ‘else-if statement’ used to executes only one logic among multiple logics.
The only difference between switch and ‘else-if’ is in performance. Switch is better than else-if
statement.
In ‘else-if’ statement every condition should be verified even to execute last block of statements, it
leads to increase the time consuming process and this problem can overcome using ‘switch’ statement.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
//code to be executed if all cases are not matched;
}
‘Java compiler’ will memorize all the case label name values and it will help to JVM to identify the
case blocks at runtime.
If no label name is matching with input choice then default block will be executed, default bloack can
exist anywhere in the switch statement.
Example Program 1:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20
Example Program 2:
public class SwitchExample2
{
public static void main(String[] args)
{
int number=20;
Page 43
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
switch(number){
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20
30
Not in 10, 20 or 30
Note: All conditional statements are executed only once.
for loop
while loop
do-while loop
18.2.1for loop:
These are used to execute repeatedly based on given range, it can be achieved using for loop.
The Java for loop is used to iterate a part of the program several times. If the number of iteration is
fixed then it is recommended to use for loop.
There are three types of for loops in java.
Simple For Loop
Nested For Loop
For-each or Enhanced For Loop
Labeled For Loop
Simple for Loop:
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr)
{
//code to be executed
}
Example Program on for loop:
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
System.out.println(i);
}
}}
Page 44
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
2
3
4
5
6
7
8
9
10
Nested loop:
If the ‘for loop’ is existed within another ‘for’ loop are called as Nested for-loops.
Syntax:
for(initialization;condition;incr/decr)
{
for(initialization;condition;incr/decr)
{
//code to be inner for loop
}
//code to be outer for loop
}
Page 45
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2
for-each loop:
The for-each loop is used to traverse array or group of elements in java.
It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Datatype var:array)
{
//code to be executed
}
Page 47
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program 3 on infinite for loop:
If you use two semicolons “;;” in the for loop, it will be infinitive for loop.
Syntax:
for(;;)
{
//code to be executed
}
Program:
public class ForExample
{
public static void main(String[] args)
{
for(;;)
{
System.out.println("infinitive loop");
}
}
}
OUTPUT:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c (To exit out of the program)
Page 48
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
2
3
4
5
Example Program 2 on infinite while loop:
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true)
{
//code to be executed
}
Program:
public class WhileExample2
{
public static void main(String[] args)
{
while(true){
System.out.println("infinitive while loop");
}
}
}
OUTPUT:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c (To exit out of the program)
Page 49
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
OUTPUT:
1
2
3
4
5
Syntax:
jump-statement;
break;
Page 50
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example program 1 on break statement:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4
Page 51
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
18.3.2 Continue Statement:
The continue statement is used in loop control structure when you need to immediately jump to the
next iteration of the loop. It can be used with for loop or while loop.
The Java continue statement is used to continue loop. It continues the current flow of the program and
skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement;
continue;
Example program on continue statement:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4
6
7
8
9
10
Page 52
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
19. JAVA Expressions:
Expressions are made up of variables, operators, literals and method calls that evaluates to a single
value according to the syntax of the language.
Operators may be used in building expressions, which compute values; expressions are the core
components of statements; statements may be grouped into blocks.
Example 1:
int abc;
abc = 100;
Here, abc = 100, is an expression that returns an int because the assignment operator returns a value of
the same data type as its LHS operand.
Example 2:
int a=10, b=30;
int c;
c = a + b;
Here, c = a + b, is an expression that returns an int.
Example 3:
If (number1 = = number2)
{
Sytem.out.println(“Hello java world”);
}
Here, number1 = = number2 is an expression that returns Boolean value and “Hello java world” is an
string expression.
Page 53
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
String band = "Beatles";
if (band == "Beatles")
{ // start of block
System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}
There are two statements System.out.print("Hey "); and System.out.print("Jude!"); inside the
mentioned block above.
20.2 Associativity:
When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity.
Associativity tells the direction of execution of operators that can be either left to right or right to left.
For example, in expression a = b = c = 8 the assignment operator is executed from right to left that
means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You
can parenthesize this expression as (a = (b = (c = 8))).
Note that, you can change the priority of a Java operator by enclosing the lower order priority operator
in parentheses but not the associativity.
For example, in expression (1 + 2) * 3 addition will be done first because parentheses has higher
priority than multiplication operator.
Page 54
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
20.3 Precedence and associativity of Java operators:
The table below shows all Java operators from highest to lowest precedence, along with their
associativity.
Page 55
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT - 2
21. Abstract Data Type:
Abstract Data Type (ADT) is a type (or class) for objects whose behavior is defined by a set of value
and a set of operations.
The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented.
It does not specify how data will be organized in memory and what algorithms will be used for
implementing the operations.
So it is called “abstract” because it gives an implementation independent view.
The process of providing only the essentials and hiding the details is known as abstraction.
In java, there are 3 ADTs namely List ADT, Stack ADT, Queue ADT.
Page 56
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
22. Classes and objects
In object-oriented programming every program is developed by using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
A class is a group of objects which have common properties. It is a logical entity. It can't be physical.
A class in Java can contain:
1. variable
2. methods
3. constructors
4. blocks
5. nested class and interface
Variable in Java:
A variable which is created inside the class but outside the method is known as instance variable.
Instance variable doesn't get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
Method in Java:
In java, a method is like function i.e. used to expose behavior of an object.
Advantages of method are: Code Reusability and Code Optimization.
Page 57
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before
executing the next time. So that it is highly recommended to access a single method of the class at a
time.
In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
‘Referenced object’ and ‘unreferenced object’ is created by JVM in main memory based on its syntax.
In the above syntax 2, JVM will create a new object for the properties of the given class.
In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student( );
s1.id=101;
s1.name="Abc";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
OUTPUT:
101 Abc
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="Abc";
s2.id=102;
s2.name="Xyz";
System.out.println(s1.id+" "+s1.name);
Page 59
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(s2.id+" "+s2.name);
}
}
OUTPUT:
101 Abc
102 Xyz
Page 60
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 11: A java program to Initialization through constructor
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display( );
s2.display( );
}
}
OUTPUT:
111 Karan
222 Aryan
Page 61
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display( );
e2.display( );
e3.display( );
}
}
OUTPUT:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Example Program:
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);
}
public static void main(String args[])
{
new Calculation( ).fact(5);//calling method with anonymous object
}
}
OUTPUT:
Factorial is 120
Page 62
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 13: A java program to store Bank details of customers
class Account
{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println("Insufficient Balance");
}
else
{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
void checkBalance( )
{
System.out.println("Balance is: "+amount);
}
void display( )
{
System.out.println(acc_no+" "+name+" "+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( );
Page 63
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
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.1 Private: ‘private’ members of a class are not accessible anywhere outside the class. They are accessible
only within the methods of the same class.
23.2 Public: ‘public’ members of a class are accessible everywhere outside the class. So any other program
can read them and use them.
23.3 Protected: ‘protected’ members of a class are accessible outside the class, but generally within the same
directory.
23.4 default: If no access specifier is written by the programmer, then the java compiler uses a ‘default’
access specifier. ‘default’ members are accessible outside the class but within the same directory.
Note:
In real time, we generally use ‘private’ for instance variables and ‘public’ for methods.
In java, classes cannot be declared by using ‘private’.
Page 64
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Within the derived Anywhere in same
Access Within the Within the
class of other and outside the
Modifier same class same package
package package
1) private YES NO NO NO
2) default YES YES NO NO
3) protected YES YES YES NO
4) pubic YES YES YES YES
If any variable or method is not preceded by “private/protected/public” then that properties are treated
as ‘default’ properties.
Page 65
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 15: A java program for default access modifier
//save by A.java
package pack;
class A
{
void msg( )
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );//Compile Time Error
obj.msg( );//Compile Time Error
}
}
OUTPUT:
Compile time error
Page 66
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
public static void main(String args[])
{
B obj = new B( );
obj.msg( );
}
}
OUTPUT:
Hello
//save by A.java
package pack;
public class A
{
public void msg( )
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );
obj.msg( );
}
}
OUTPUT:
Hello
Page 67
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
25. Methods in Java:
Def: A method represents a group of statements that performs a task. A task represents a calculation or
processing of data or generating a report etc.
A method has two parts:
1) Method header or Method prototype
2) Method body
The method header contains method return datatype, method name, method parameter.
The method body contains business logic.
Method Syntax:
returntype methodName (parameter 1, parameter 2, …)
{
// method body
}
In the above syntax, ‘methodname’ can be any user defined name and the main business logic must
be written inside the method body.
Parameters:
The ‘parameters’ represents the “input”, it can be any of following 3 types:
1) No parameter (empty):Method performs an operation without accepting any input.
2) Primitive datatype: Method performs an operation by accepting single input value.
3) Reference datatype: Method performs an operation by accepting multiple input values in the form
of “object”.
Returntype:
‘returntype’ represents “output”, it can be any of following 3 types:
1) No return type (void):Method does not return the output to other method from where it is calling.
2) Primitive datatype: Method returns a single output value to the other method.
3) Reference data type: Method returns multiple output values in the form of ‘object’ to the other
method.
Primitive data type: This is a data type whose variable can handle maximum one value at a time. For
example: byte, short, int, long, float, double, char and Boolean
Reference data type: It is a data type whose variable can handle more than one value in the form of
‘object’.
Note: If the result (output) of one method wants to be used inside the other method then the return
type of the first method should be either ‘primitive’ (or) ‘reference’ data type.
If any method definition is preceded by ‘static’ keyword is known as “static method”, it must be
accessed with ‘classname’.
If any method definition is not preceded by ‘static’ keyword is known as “non-static method” or
“instance method”, it must be accessed with ‘object’.
Syntax No 1:
void methodname( )
{
-----
-----
}
- In the above syntax 1, it is use to perform an operation without accepting any input values and
does not returns any output to the other method
- Syntax to call a non-static method:
object.methodname( );
Page 69
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
- Syntax to call a static method:
classname.methodname( );
Syntax No 2:
void methodname( primitivedatatype variable)
{
-----
-----
}
- In the above syntax 2, it is use to perform an operation by accepting single input value and does
not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( value);
- Syntax to call a static method:
classname.methodname( value);
Syntax No 3:
void methodname( Referencedatatype variable)
{
-----
-----
}
- In the above syntax 3, it is use to perform an operation by accepting multiple input values in the
form of object and does not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( object);
- Syntax to call a static method:
classname.methodname(object);
Syntax No 4:
primitivedatatype methodname( )
{
-----
-----
return value;
}
- In the above syntax 4, it is use to perform an operation without accepting any input values and
returns a single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename = object.methodname( );
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( );
Page 70
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Syntax No 5:
primitivedatatype methodname( primitivedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 5, it is use to perform an operation by accepting single input value and returns
single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename= object.methodname( value);
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( value);
Syntax No 6:
primitivedatatype methodname( referencedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 6, it is use to perform an operation by accepting multiple input values in the
form of object and returns single output value to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( object);
- Syntax to call a static method:
Classname objectreference = classname.methodname(object);
Syntax No 7:
Referencedatatype methodname( )
{
-----
-----
return object;
}
- In the above syntax 7, it is use to perform an operation without accepting any input values and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( );
- Syntax to call a static method:
Classname objectreference = classname.methodname( );
Page 71
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Syntax No 8:
Referencedatatype methodname(primitivedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 8, it is use to perform an operation by accepting single input value and returns
multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(value);
- Syntax to call a static method:
Classname objectreference = classname.methodname( value);
Syntax No 9:
Referencedatatype methodname(Referencedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 9, it is use to perform an operation by accepting multiple input value and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(object);
- Syntax to call a static method:
Classname objectreference = classname.methodname( object);
Following table shows how to access both static and non-static properties within the non-static and
static methods of same class or other class:
Within the non- Within the Within the non- Within the static
Type of
static method of static method static method of method of other
Property
same class of same class other class class
1. Non-static Can be used Can be accessed Can be accessed Can be accessed
method/variable directly by using object by using object by using object
Can be accessed Can be accessed Can be accessed Can be accessed
2. Static
directly / using directly / using by using class by using class
method/variable
class name class name name name
Page 72
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 18: A java program for method concept
class A
{
int x=10, y=20, z;
void add( )
{
z= x + y;
System.out.println(z);
}
}
class B
{
void show( )
{
new A( ).add( );
System.out.println(“In class B”);
}
}
class C
{
void f1( )
{
new B( ).show( );
System.out.println(“In class C”);
}
}
class TestDemo
{
public static void main(String args[])
{
new C( ).f1( );
System.out.println(“In class C”);
}
}
OUTPUT:
30
In class B
In class C
Page 73
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 19: A java program to work with all types of variables and methods
Class A
{
int y=8;
static int z = 3;
void f1( )
{
int x=5; //local variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
void f2( )
{
System.out.println(x); //local variable cannot be accessed outside the method
System.out.println(y);
System.out.println(z);
System.out.println(A.z);
f1( );
}
static void f3( )
{
A oa = new A( );
System.out.println(oa.y);
oa.f1( );
System.out.println(z);
}
}
class B
{
void f4( ) //non-static method
{
new A( ).f1( );
A.f3( );
}
static void f5( )
{
new A( ).f1( );
A.f3( );
}
}
class MethodDemo
{
public static method(String args[ ])
{
A.f3( );
new B( ).f4( );
B.f5( );
Page 74
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
B.f4( );//Not possible because f4( ) is a non-static method so we cannot call by class
//name. If requires we can access the f4( ) by creating an object.
}
}
Page 75
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class A
{
void f1(Student s)
{
System.out.println(“In class A”);
}
static int f2( )
{
return (5);
}
}
class Demo
{
public static void main(String a[ ])
{
new Student( ).display( );
Student s = new Student( );
new A( ).f1(s);
int i = A.f2( );
}
}
Program 22: A java program for a method without parameters and without return type
class Sample
{
private double, num1, num2;
void sum( )
{
double res = num1 + num2;
System.out.println(“Sum=” +res);
}
}
class Methods
{
public static void main(String a[ ])
{
Sampe s = new Sample( );
s.sum( );
}
}
Page 76
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 23: A java program for a method without parameters and with return type
class Sample
{
private double num1, num2;
double sum( )
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum( );
System.out.println(“Sum=” +x);
}
}
Program 24: A java program for a method with two parameters and with return type
class Sample
{
double sum(int num1, double num2)
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}
Page 77
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 25: A java program for a static method that accepts data and return the result
class Sample
{
static double sum(double num1, double num2)
{
double res = num1 + num2;
return res;
}
class Methods
{
public static void main(String a[ ])
{
double x = Sample.sum(10, 22.5);
System.out.println(“Sum=” +x);
}
}
Program 26: A java program to test whether a static method can access the instance variable or not
class Test
{
int x;
static void access( )
{
System.out.println(“x =”+x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}
Program 27: A java program to test whether a static method can access the static variable or not
class Test
{
static int x = 55;
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}
Page 78
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 28: A java program by taking an instance variable x in the Test class
class Test
{
int x = 10;
void display( )
{
System.out.println(x);
}
}
class InstanceDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );
}
}
OUTPUT:
X in obj1: 11
X in obj2: 10
Program 29: A java program by taking a static variable x in the Test class
class Test
{
static int x = 10;
static void display( )
{
System.out.println(x);
}
}
class StaticDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );
Page 79
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
X in obj1: 11
X in obj2: 11
In the program 30, we have created two methods, first add( ) method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
OUTPUT:
22
33
Page 80
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
26.2 Method Overloading: changing data type of arguments
In program 31, we have created two methods that differ in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
In method overloading, is not possible by changing the return type of the method only because of
ambiguity.
Example program:
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static double add(int a,int b)
{
return a+b;
}
}
class TestOverloading3
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));//ambiguity
}
Page 81
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:
Compile Time Error: method add(int,int) is already defined in class Adder
Page 82
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
In the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can
be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or
double and so on.
Page 83
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
26.5 Method overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.
Program 35: A Java Program with Type Promotion in case of ambiguity in method overloading
class OverloadingCalculation3
{
void sum(int a, long b)
{
System.out.println("a method invoked");
}
void sum(long a, int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
OverloadingCalculation3 obj=new OverloadingCalculation3( );
obj.sum(20,20);//now ambiguity
}
}
OUTPUT:
Compile Time Error
Page 84
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
27. Constructor in Java:
In Java, constructor is a block of codes similar to method.
It is called when an instance of object is created and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
Every time an object is created using ‘new’ keyword, at least one constructor is called. It is called a
default constructor.
It is called constructor because it constructs the values at the time of object creation.
It is not necessary to write a constructor for a class.
It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating java constructor:
1) Constructor name must be same as its class name.
2) Constructor must have no explicit return type
Types of java constructors. There are two types of constructors in java:
1) Default constructor (no parameterized constructor)
2) Parameterized constructor
Page 85
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class EmpDemo
{
public static void main(String args[ ])
{
Emp e1 = new Emp(1, “abc”, 75.6f);
e1.display( );
System.out.println(“……………..”);
Emp e2 = new Emp(2, “xyz”, 75.9f);
e1.display( );
System.out.println(“……………..”);
Emp e3 = new Emp(3, “lmn”, 83.7f);
e1.display( );
}
}
One class can have many number of constructors with different signature, this is technically called as
“Constructor Overloading”.
The main purpose of defining multiple constructors is to initialize the different objects with different
number of dynamic input values.
Page 86
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class EmpDemo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter number of inputs:”);
int ni = sn.nextInt( );
if(ni= = 3)
{
System.out.println(“Enter eid, ename, esal:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
float sl = sn.nextFloat( );
new Emp(id,nm,sl).display( );
}
else if(n= = 2)
{
System.out.println(“Enter eid, ename:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
new Emp(id,nm).display( );
}
else if(n= = 1)
{
System.out.println(“Enter eid:”);
int id = sn.nextInt( );
new Emp(id).display( );
}
}
Page 87
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 38: A java program of default constructor
class Bike1
{
Bike1( )
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1( );
}
}
OUTPUT:
Bike is created
Program 39: A java program on default constructor that displays the default values
class Student3
{
int id;
String name;
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3( );
Student3 s2=new Student3( );
s1.display( );
s2.display( );
}
}
OUTPUT:
0 null
0 null
Program 40: A java program for a method with two parameters and with return type with constructor
class Sample
{
Private double num1, num2;
Sample(double x, double y)
{
num1 = x;
num2 = y;
}
double sum(int num1, double num2)
{
double res = num1 + num2;
Page 88
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample(10.9,23.6 );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}
OUTPUT:
Sum = 23.5
Page 89
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
28. Difference between Method and Constructor in java:
Method Constructor
1) Method is used to expose behavior of an 1) Constructor is used to initialize the state
object. of an object.
2) Method must have return type. 2) Constructor must not have return type.
3) Method is invoked explicitly. 3) Constructor is invoked implicitly.
4) The java compiler provides a default
4) Method is not provided by compiler in any
constructor if you don't have any
case.
constructor.
5) Method name may or may not be same as 5) Constructor name must be same as the
class name. class name.
Page 90
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
29.2 Reading inputs using ‘Scanner’ class:
‘Scanner’ is a predefined class in “java.util” package used to read the input values from any input
component like ‘keyboard’, ‘file’, ‘client machine’ etc.
Syntax: Scanner sn = new Scanner(System.in);
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It
provides many methods to read and parse various primitive values.
System.in represents standard input device and System.out represents standard output device.
- Above all methods are non-static methods, so we must access with object.
Program 43: A java program to read the input values using ‘Scanner’ class
import java.util.Scanner;
class Demo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter first number:”);
int x = sc.nextInt( );
System.out.println(“Enter second number:”);
int y = sc.nextInt( );
int z = x + y;
System.out.println(“Result is:”+z);
}
}
OUTPUT:
Enter first number:
25
Enter second number:
10
Result is:
35
Page 91
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 44: A java program to read the student details dynamically
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt( );
System.out.println("Enter your name");
String name=sc.next( );
System.out.println("Enter your fee");
double fee=sc.nextDouble( );
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close( );
}
}
OUTPUT:
Enter your rollno
111
Enter your name
Ratan
Enter your fee
450000
Rollno:111 name: Ratan fee:450000
}
OUTPUT:
>javac CmdDemo.java
>java CmdDemo 10 20
Before Converting
1020
After Converting
30
Program 46: A java program to accept and display a character from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
//create BufferedReader object to accept data from keyboard
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a character:”);
Char ch = (char)br.read( );
System.out.println(“You entered:” +ch);
}
}
OUTPUT:
Enter a character: A
You entered: A
To read string a characters from the keyboard we required readLine( ) method in ‘BufferedReader’
class.
The readLine( ) method accepts a string from the keyboard and returns the string.
Here type casting not required because accepting and returning the same data type.
But this method can give to the runtime error: IOException.
Program 47: A java program to accept and display a String of characters from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a name:”);
Stringname =br.readLine( );
System.out.println(“You entered:” +name);
}
Page 94
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:
Enter a name: Java
You entered: Java
To accept an integer value from the keyboard, follow the below steps:
1) First, accept the integer number from the keyboard as a string using readLine( ) method.
String str = br.readLine( );
2) The readLine( ) method return type is Integer. So this should be converted into an int by using
parseInt( ) method of Integer class in ‘java.lang’ package and parseInt( ) is a static method in
Integer class so it can be called by using classname, as follows:
int n = Integer.parseInt(str);
3) We can combine the above two steps in a single statement as follows:
int n = Integer.parseInt(br.readLine( ));
OUTPUT:
Enter a value: 1234
You entered: 1234
Page 95
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
Enter a float: 12.34
You entered: 12.34
OUTPUT:
Enter a double value: 123456.789
You entered: 123456.789
Similarly, we can write different statements to accept many other data types from the keyboard as
follows:
1) To accept a byte value.
byte n = Byte.parseByte(br.readLine( ));
2) To accept a short value.
short n = Short.parseShort(br.readLine( ));
3) To accept a long value.
long n = Long.parseLong(br.readLine( ));
4) To accept a boolean value.
boolean n = Boolean.parseBoolean(br.readLine( ));
The classes like Byte, Short, Integer, Long, Float, Double and Boolean belongs to “java.lang”
package. These classes are called as WRAPPER CLASSES.
Page 96
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 51: A java program that accepting and displaying employee details
import java.io.*;
import java.lang.*;
class a
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Emp id:");
int id = Integer.parseInt(br.readLine( ));
System.out.println("Enter Emp name:");
String name = br.readLine( );
System.out.println("Enter Emp salary:");
float sal = Float.parseFloat(br.readLine( ));
//display the employee details
System.out.println("Emp Id is:" +id);
System.out.println("Emp name:" +name);
System.out.println("Emp sal is:" +sal);
}
}
Page 97
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
How many fibonaccies? 5
0
1
1
2
3
Page 98
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
The gc( ) is found in System and Runtime classes.
Syntax: public static void gc( ){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread
calls the finalize( ) method before object is garbage collected.
Page 99
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
In the above example, all students have its unique ‘rollno’ and ‘name’, so instance data member is
required and for college refer to the common property of all objects. If we make it static, this field will
get memory only once.
Page 100
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
1
1
In the above program 54, 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 to other objects.
So each objects will have the value 1 in the count variable.
class Counter2
{
static int count=0;//will get memory only once and retain its value
Counter2( )
{
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2( );
Counter2 c2=new Counter2( );
Counter2 c3=new Counter2( );
}
}
OUTPUT:
1
2
3
33.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 object of a class.
A static method can be invoked without the need for creating an instance of a class.
Static method can access static data member and can change the value of it.
Static method is a method that doesn’t act up on instance variables of a class.
Static methods are called with ‘classname’ that is the reason static methods are not accessed by JVM
with instance variables.
Student9(int r, String n)
{
rollno = r;
name = n;
}
void display ( )
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student9.change( );
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display( );
s2.display( );
s3.display( );
}
}
}
OUTPUT:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Program 57: A java program on static method that performs normal calculation
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:
125
Page 102
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 58: A java program on static method trying to access instance variable
class Test
{
int x;//instance variable
Test(int x)
{
this.x = x;
}
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test obj = new Test(10);
Test.access( );
}
}
OUTPUT: Run this program for better understanding
OUTPUT:
static block is invoked
Hello main
Page 103
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
34. ‘this’ keyword in Java:
It is a keyword in java language, represents the current class object, it can be used in following 2 ways:
1) this.
2)this( )
34.1 this.
It is used to differentiate “instance variables” with “formal parameters” of either method (or)
constructor if both are existing with same name.
Syntax: this.variablename;
OUTPUT:
Emp id: 1
Emp name: abc
Emp sal: 76.24
Emp id: 2
Emp name: xyz
Emp sal: 960.24
Page 104
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
34.2 this( ):
1) It is used to call one constructor inside another constructor same class.
2) The main advantage with this( ) is to call multiple constructors by creating single object.
3) The scope of ‘this’ keyword is within the same class.
4) This( ) must be the first statement while calling method or constructor.
5) Syntax:
o this(arguments) //used to call parameterized constructor
o this( ); //used to call no-parameterized constructor
Page 105
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
35. Arrays
An array is a data structure which represents a group of elements of same type.
By using arrays we can store group of int values or a group of float values or group of strings in the
array. But we cannot store all data type values in the same array.
In Java, arrays are created on dynamic memory allocated by JVM at runtime.
Types of arrays:
1) Single dimensional array
2) Multi-dimensional array(2D, 3D, .. arrays)
Advantage of Java Array:
1) Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.
2) Random access: We can get any data located at any index position.
Disadvantage of Java Array:
1) Size Limit: We can store only fixed size of elements in the array.
2) It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Program 61: A java program of single dimensional array with declaration and instantiation
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OUTPUT:
10
20
70
40
50
Page 106
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 62: A java program of single dimensional array with declaration, instantiation and
Initialization
class Testarray1
{
public static void main(String args[])
{
int a[]={9,13,6,3};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
OUTPUT:
9
13
6
3
Program 64: A java program to find out total marks and percentage of student with 1D array
import java.io.*;
class OneArray
{
public static void main(String args[ ])
{
BufferedReader br = new BufferedReader(new InputStream(System.in));
Sysytem.out.println(“How many subjects: ?”);
int n = Integer.parseInt(br.readLine( ));
int[ ] marks = new int[n];
Page 107
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//store elements into array
for(int i=0; i<n; i++)
{
System.out.println(“Enter marks”);
Mraks[i] = Integer.parseInt(br.readLine( ));
}
//find total marks
int tot = 0;
for(int i=0;i<n;i++)
{
tot = tot + marks[i];
}
System.out.println(“Total marks =” +tot);
// find percent
float percent = (float)tot/n;
System.out.println(“Percentage =”+percent);
}
}
Page 109
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 66: A java program Transpose of Matrix
import java.io.*;
import java.util.Scanner;
class Matrix
{
public static void main(String args[ ] ) throws IOException
{
Scanner sc = new Scanner(Sytem.in);
System.out.println(“Enter rows and column? “);
int r = sc.nextInt( );
int c = sc.nextInt( );
//creating an array
int arr[ ][ ] = new int [r][c];
//accept a matrix from keyboard
System.out.println(“Enter elements of matrix”);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
arr[i][j] = sc.nextInt( );
System.out.println(“The transpose matrix:”);
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
System.out.println(arr[j][i] +“ ”);
}
System.out.println(“\n”);
}
}
}
OUTPUT:
Enter rows, columns? 3 4
Enter elements of matrix:
1 2 3 4
5 6 7 8
9 9 -1 2
The transpose matrix:
1 5 9
2 6 9
3 7 -1
1 2
Page 110
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 67: A java program Addition of Matrix
class MatrixAdd
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
Page 111
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//Multiplication Program
public class MatrixMultiplication
{
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}};
Page 112
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
36. Nested Classes
In java, it is possible to define a class within another class, such classes are known as nested classes.
Syntax:
class Outer
{
//class Outer members
class Inner
{
//class Inner members
}
} //closing of class Outer
Advantages:
1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. It can lead to more readable and maintainable code.
Page 113
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("This is my nested class");
}
}
public static void main(String args[])
{
Outer.Nested_Demo nested = new Outer.Nested_Demo( );
nested.my_method( );
}
}
OUTPUT:
This is my nested class
Page 114
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT-III
37. Relations between classes
The main purpose of maintaining relations between classes is to achieve the “Reusability”.
Reusability means using the properties of one class into another class.
Java supports following 3 types of relations between the classes.
1) Uses-a relation (Weak (or) Association relation)
2) Has-a relation (Strong (or) Aggregation)
3) Is-a relation (Very strong (or) Composition)
Page 115
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
37.2 Has-a relation:
If one class object is created inside another class but outside the methods then those two classes are in
“Has-a” relation.
The scope of “has-a” relation is throughout the class.
Example program:
class A
{
void f1( )
{
System.out.println(“Hello Java”);
}
}
class B
{
A oa = new A( );
void f2( )
{
oa.f1( );
}
void f3( )
{
oa.f1( );//Valid method calling
}
}
class HasaRealtion
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f2( );
ob.f3( );
}
}
Page 116
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
38. Inheritance
Def:
1) Extending the properties of one class into another class is known as “Inheritance”.
(or)
2) Deriving a new class from the existing class is known as “Inheritance”.
In java language, inheritance can be achieved by using “extends” keyword.
The class which is giving the properties (variables and methods) is known as “parent/ super/ base
class”.
The class which is taking the properties is known as “child/sub/derived class”.
Page 117
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 71: A java program on simple Inheritance
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)
{
Child cobj = new Child( );
cobj.c1( ); //method of Child class
cobj.p1( ); //method of Parent class
}
}
OUTPUT:
Child method
Parent method
Page 118
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
38.1 Types of Inheritance in Java:
Inheritance always can be done from “Top-to-Bottom”, that means super class properties are inherited
into derived class but derived class properties does not inherit in superclass.
The various types are as follows:
1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
5) Hybrid Inheritance
In java, Single, multilevel and hierarchical is implemented at “class” level but multiple and hybrid
inheritance is implemented at “Interface” level only.
Page 119
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 73: A java program on single Inheritance
class Animal
{
void eat( )
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark( )
{
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[])
{
Dog d=new Dog( );
d.bark( );
d.eat( );
}
}
OUTPUT:
barking…
eating…
Page 120
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog( );
d.weep( );
d.bark( );
d.eat( );
}
}
OUTPUT:
weeping...
barking...
eating...
Page 121
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
meowing...
eating...
38.2 Why multiple inheritance is not supported in java?
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and
B classes have same method and you call it from child class object, there will be ambiguity to call
method of A or B class.
Program 76: A java program on why multiple inheritance is not supported in java?
class A
{
void msg( )
{
System.out.println("Hello");
}
}
class B
{
void msg( )
{
System.out.println("Welcome");
}
}
class C extends A,B
{//suppose if it were
Public Static void main(String args[])
{
C obj=new C( );
obj.msg( );//Now which msg( ) method would be invoked?
}
}
OUTPUT:
Compile Time Error
Page 122
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 77: A java program methods accessing in inheritance
class A
{
void f1( )
{
System.out.println(“f1( ) of class A”);
}
}
class B extends A
{
void f2( )
{
System.out.println(“f2( ) of class B”);
}
void f3( )
{
System.out.println(“f3( ) of class B”);
}
}
class Inh
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f2( );
ob.f1( );
ob.f3( );
System.out.println(ob);
System.out.println(“………………”);
A oa = new A( );
oa.f1( );
oa.f2( );//Invalid
System.out.println(“……………..”);
Object o = new B( );
o.f1( );//Invalid because object class is the top class
o.f2( );//Invalid because object class is the top class
}
}
Page 123
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
39. ‘Super’ Keyword in java
The super keyword in java language, which is used to refer super class object.
It can be used in two ways:
1) super. at variable level
2) super. at method level
3) super( )
Note: Without Inheritance, super keyword cannot be used.
Page 124
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
39.2 super. at method level
It can be used to differentiate super class method with derived class method, if both are existing with
same name.
Syntax: super.methodname( );
39.3 super( ):
It is used to call super class constructor within derived class constructor.
Syntax: super ( ); and super(arguments);
In real time, super( ) can be used to initialize instance variables of all the super classes along with
derived class by creating a single object.
Super( ) must be first statement while calling other method or constructor and same as for this( ).
Page 125
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class B extends A
{
B(double y)
{
super(10);
System.out.println(“B class constructor”);
}
}
class C extends B
{
C(String z)
{
super(10.34);
System.out.println(“C class constructor”);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
C oc = new C( “Java”);
}
}
OUTPUT:
A class constructor
B class constructor
C class constructor
Super( ) must be the first statement inside the constructor.
In every constructor the default first statement is super( ).
Syntax:
ClassName( )
{
------- //super( ) is the default first statement
-------
}
class A
{
A( )
{
System.out.println(“A class constructor”);
}
}
class B extends A
{
Page 126
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
B( )
{
System.out.println(“B class Constructor”);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
B ob = new B( );
}
}
OUTPUT
A class constructor
B class constructor
Page 127
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
40.2 Java final method:
If you make any method as final, you cannot override it.
But it is possible to inherit the final method.
Page 128
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
40.4 Can we initialize blank final variable?
Yes it is possible only in constructor.
Page 129
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public static void main(String args[])
{
Bike11 b=new Bike11( );
b.cube(5);
}
}
Output: Compile Time Error
Page 130
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 87: A java program on method overriding
class Vehicle
{
void run( )
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run( )
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2( );
obj.run( );
}
}
OUTPUT:
Bike is running safely
Page 131
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 89: A java program on bank application with method overriding
class Bank
{
int getRateOfInterest( )
{
return 0;
}
}
class SBI extends Bank
{
int getRateOfInterest( )
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest( )
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest( )
{
return 9;
}
}
class Test2
{
public static void main(String args[])
{
SBI s=new SBI( );
ICICI i=new ICICI( );
AXIS a=new AXIS( );
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest( ));
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest( ));
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest( ));
}
}
OUTPUT:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Page 132
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
42. Difference between method overloading and overriding
SNO Method Overloading Method Overriding
Method overriding is used to provide
Method overloading is used to increase the the specific implementation of the
1
readability of the program. method that is already provided by its
super class.
Method overriding occurs in two
Method overloading is performed within
2 classes that have IS-A (inheritance)
class.
relationship.
In case of method overloading, parameter In case of method overriding,
3
must be different. parameter must be same.
Method overloading is the example of Method overriding is the example of
4
compile time polymorphism. run time polymorphism.
In java, method overloading can't be
performed by changing return type of the
Return type must be same in method
5 method only. Return type can be same or
overriding.
different in method overloading. But you
must have to change the parameter.
Page 133
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example:
abstract class A
{
void f1( )
{
-------
-------
}
abstract void f2( );
abstract void f3( );
}
Program 90: A java program on abstract classes that all objects need different implementations of
the same method
abstract class MyClass
{
abstract void calculate(double x);
}
class Sub1 extends MyClass
{
void calculate(double x)
{
System.out.println(“Square=” +(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(doublex)
{
System.out.println(“Square root=” +Math.sqrt(x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
System.out.println(“Cube=” +(x*x*x));
}
}
Page 134
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class Sample
{
public static void main(String args[ ])
{
Sub1 obj1 = new Sub1( );
Sub2 obj1 = new Sub2( );
Sub3 obj1 = new Sub3( );
obj1.calculate(3);
obj1.calculate(3);
obj1.calculate(3);
}
}
OUTPUT:
Square = 9
Square root = 2.0
Cube = 125.0
We cannot create an object to abstract class, but we can create a reference variable to it, as shown
here:
MyClass ref;
ref = obj1;
ref.calculate(3);
ref = obj2;
ref.calculate(4);
ref = obj3;
ref.calculate(5);
Program 91: A java program on abstract class that has abstract method
abstract class Bike
{
abstract void run( );
}
class Honda4 extends Bike
{
void run( )
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4( );
obj.run( );
}
}
OUTPUT:
running safely.
Page 135
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 92: A java program on abstract class that has abstract method
Page 136
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI( );
System.out.println("Rate of Interest is: "+b.getRateOfInterest( )+" %");
b=new PNB( );
System.out.println("Rate of Interest is: "+b.getRateOfInterest( )+" %");
}
}
OUTPUT:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Program 94: A java program on Abstract class having constructor, data member, methods
abstract class Bike
{
Bike( )
{
System.out.println("bike is created");
}
abstract void run( );
void changeGear( )
{
System.out.println("gear changed");}
}
class Honda extends Bike
{
void run( )
{
System.out.println("running safely..");
}
}
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda( );
obj.run( );
obj.changeGear( );
}
} OUTPUT:
bike is created
running safely..
gear changed
Page 137
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 95: A java program on Abstract class to calculate electricity bill and domestic plans
abstract class Plan
{
protected double rate;
public abstract void getRate( );
public void calculateBill(int units)
{
System.out.println(“Bill amount for “ +units + “units:”);
}
}
class CommercialPlan extends Plan
{
public void getRate( )
{
rate = 5.00;
}
}
class DomesticPlan extends Plan
{
public void getRate( )
{
rate = 2.60;
}
}
class calculate
{
public static void main(String args[ ])
{
Plan p;
System.out.println(“Commercial connection”);
p = new CommericailPlan( );
p.getRate( );
p.calculateBill(250);
System.out.println(“Domestic connection”);
p = new DomesticPlan( );
p.getRate( );
p.calculateBill(150);
}
}
OUTPUT:
Commercial connection
Bill amount for 250 units: 1250
Domestic connection
Bill amount for 150 units: 390
Page 138
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
44. Relation between Concrete class and Abstract Classes
1) If the parameter of any method is concrete class then that method will accept either same class object
or its derived class object.
Example:
2) If the parameter of any method is an ‘abstract’ class then that method will accept only its derived class
object.
Example:
Page 139
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) If the parameter of any method is an ‘object’ class then that will accept any concrete class object.
Example:
4) If the return type of any method is concrete class then that method will return either same class object
(or) its derived class object.
Example:
Page 140
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
5) If the return type of a method is ‘object’ class then that method can return any concrete class object.
Example:
6) If the return type is an ‘abstract’ class then that method returns only its ‘derived’ class objects.
Example:
Page 141
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
45. Interfaces
The main disadvantage with ‘abstract class’ is, it doesn’t support “Multiple Inheritance” because of
‘ambiguity’ problem.
Ambiguity problem always occurs while working with ‘concrete classes’.
In the above example, java compiler will get confusion to verify which super class method of Class-C,
it is called ambiguity problem.
To overcome above disadvantage of abstract class “Interface” was introduced.
Interface is an alternative to abstract class mainly introduced to achieve the “Multiple Inheritance” in
java language.
Interface is by ‘default’ abstract type so that no object can be created but it is possible to create object
reference.
Interface is a collection of constant variables and abstract methods. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
In other words, you can say that interfaces can have methods and variables but the methods declared in
interface contain only method signature, not body.
Page 142
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example:
interface A
{
int x = 10; //constant
void f1( );
}
Interface can be inherited in any class using ‘implements’ keyword.
The java compiler adds public and abstract keywords before the interface method. More, it adds
public, static and final keywords before data members.
If the parameter of any method is “Interface” then that method will accept any of its derived class
object.
If the return type of any method is “Interface” then that method will return any of its derived class
object.
interface A
{
void f1( );
}
interface B
{
void f2( );
}
class C implements A, B//Multiple Inheritance
{
public void f1( )
{
System.out.println(“f1( ) of class C”);
}
public void f2( )
{
System.out.println(“f2( ) of class C”);
}
}
class InterfaceDemo
{
public static void main(String args[ ])
{
A oa = new C( );
Page 143
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
oa.f1( );
B ob = new B( );
Ob.f1( );
}
}
OUTPUT:
f1( ) of class C
f2( ) of class C
Memory organization of above example program 96:
interface Bank
{
float rateOfInterest( );
}
class SBI implements Bank
{
public float rateOfInterest( )
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest( )
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI( );
System.out.println("ROI: "+b.rateOfInterest( ));
}
}
OUTPUT:
ROI: 9.15
Page 145
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
45.3 Multiple inheritance in Java by interface
Any class allows to inherit both class and multiple inheritance at a time.
Syntax:
class DerivedClassName extends SuperClassName implements Interface1, Interface2
{
---------------------------
---------------------------
}
Every abstract method of an interface must be overridden in its derived class otherwise derived class
also becomes abstract class.
Page 146
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
F1( ) of class B
F2( ) of class B
F3( ) of class A
Page 147
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
interface Iface3 extends Iface2
{
void f3( );
}
class A implements Iface3
{
public void f1( )
{
System.out.println(“f1( ) of class A”);
}
public void f2( )
{
System.out.println(“f2( ) of class A”);
}
public void f3( )
{
System.out.println(“f3( ) of class A”);
}
}
class IFaceDemo
{
public static void main(String args[ ])
{
A oa = new A( );
oa.f1( );
oa.f2( );
oa.f3( );
}
}
OUTPUT:
f1( ) of class A
f2( ) of class A
f3( ) of class A
Page 148
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public void draw( )
{
System.out.println("drawing rectangle");
}
}
class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle( );
d.draw( );
System.out.println(Drawable.cube(3));
}
}
OUTPUT:
drawing rectangle
27
Page 149
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
47. Java Package
Package is a folder with collection of classes (concrete class or abstract class or Interface) and sub-
packages.
The main purpose of package in real time is to use the classes of one computer in another computer.
The main purpose of sub packages is to improve the searching the speed, identification of classes very
easily by the developer.
Packages are categorized into following two types:
1) Predefined package (built-in package)
2) User defined package
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package:
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Page 150
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
o It consists of sub package, ‘java.awt.event’, which is useful to provide action for components
like push buttons, radio buttons, menus etc.
5) javax.swing:
o This package helps to develop GUI like ‘java.awt’. The ‘x’ in javax represents that it is an
extended package which means it is a package developed from another package by adding new
features to it.
o In fact, ‘javax.swing’ is an extended package of ‘java.awt’.
6) java.net:
o ‘net’ stands for network. Client-server programming can be done by using this package.
o Classes related to obtaining authentication for a network, creating sockets at client and server
to establish communication between them.
7) java.applet
o Applets are programs which come from a server into a client and get executed on the client
machine on a network.
o Applet class of this package is useful to create and use applets.
8) java.sql:
o ‘sql’ stands for structure query language. This package is helpful to connect to databases like
Oracle, mySql, etc. to retrieve the data from them and use it in a java program.
Page 151
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
For example:
javac -d . A.java
The -d switch specifies the destination where to put the generated class file. If you want to keep
the package within the same directory, you can use . (dot).
package P2;
public class B
{
void f2( )
{
System.out.println("Welcome to package P2");
}
}
How to run java package:
To Compile: javac -d . A.java
To Run: java P1.A
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.
Page 152
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("Hello");
}
}
public class C
{
public void display( )
{
System.out.println(“In class C”);
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );
obj.msg( );
}
}
Output: Hello
Page 154
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//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
Example 2:
class Demo
{
public static void main(String args[ ])
{
java.util.Scanner sn = new java.util.Scanner(System.in);
System.out.println(“Enter first no”);
int n1=sn.nextInt( );
System.out.println(“Enter second no”);
int n2=sn.nextInt( );
System.out.println(n1+n2);
}
}
1) Predefined Exception:
If any exception class is already designed by “SUN MICRO SYSTEMS” and raised commonly
in every java program is known as ‘predefined exception’.
2) Asynchronous Exception:
These are the exceptions raised because of hardware failure or memory failures. These
exceptions cannot handle by developer.
3) Synchronous Exception:
These exceptions raised because of ‘invalid inputs’. Every synchronous can be handled using
‘try-catch( )’ block.
Page 156
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4) Checked Exceptions:
The exceptions that are checked at compilation time by the java compiler are called “Checked
Exceptions”.
Example: IOException, SQLException, etc.
5) Unchecked Exceptions:
The exceptions that are checked by the JVM are called ‘unchecked exceptions’.
Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
6) User defined exceptions:
If any exception class is created by the developer is known as ‘user defined exception’, in real
time these are out dated.
In checked exception, the programmer should either handle them with ‘try-catch( )’ or throw them
without handling them. Consider the following example:
public static void main(String args[ ]) throws IOException
Here, IOException is an example of checked exception. So we re-throwing to main( ) method without
handling it. This is done by ‘throws’ clause written after main( ) method.
All exceptions are declared as classes in Java. All these classes are descended from a super class called
“Throwable”.
Throwable is a most super class that represents all errors and exceptions which may occur in Java.
Exception is the super class of all exceptions in java.
Examples scenarios where exceptions may occur:
1) 'ArithmeticException occurs if we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) NullPointerException occurs if we have null value in any variable, performing any operation by the
variable occurs an NullPointerException.
String s=null;
System.out.println(s.length( ));//NullPointerException
Page 157
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) NumberFormatException occurs if the wrong formatting of any value, may occur
‘NumberFormatException’. Suppose I have a string variable that have characters, converting this
variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) ArrayIndexOutOfBoundsException occurs if you are inserting any value in the wrong index, it
would result ArrayIndexOutOfBoundsException as shown below:
int a[ ]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Page 158
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
In the above example, “System.out.println("rest of the code...");”statement is not going to
executed. If there can be 100 lines of code after exception. So all the code after exception will not
be executed.
Solution by exception handling:
Let's see the solution of above problem by java try-catch block.
Program 107: A java program solution of program No. 106 by exception handling
Now as displayed in the above example, rest of the code is executed i.e. rest of the code... statement
is printed.
Page 160
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 108: A java program on Number Format exception
class NFException
{
public static void main(String args[ ])
{
try
{
int fn = Integer.parseInt(s[0]);
int sn = Integer.parseInt(s[1]);
System.out.println(“Sum is:”+(fn+sn));
}
catch (NumberFormatException e)
{
System.out.println(“Pls provide only numeric inputs”);
}
}
}
OUTPUT:
java NFException 10 5
sum is: 15
java NFException Ten Five
Pls provide only numeric inputs
Page 161
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
java MulDemo 10 5
Result is: 2
java MulDemo 10 0
java.lang.ArithmeticException: / by zero
Page 162
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
48.4 Handling of unknown exceptions:
If developers knows which type of exception is going to be raised in “try-block( )” is known as
“Known exception”.
If developer doesn’t knows which type of exception is going to be raised in try-catch( ) block is
called as “Unknown Exception”.
Unknown exceptions can be handled by “Exception” class.
Syntax1:
try
{
-----
-----
}
catch(Exception e)//Exception class can handle any exception which is raised in try-block
{
String s = e.getMessage( );
System.out.println(s);//It will display only exception message
}
Syntax 2:
try
{
-----
-----
}
catch(Exception e)
{
System.err.println(e);//It will exception class name and message
}
Syntax 3:
try
{
-----
-----
}
catch(Exception e)
{
e.printStackTrace( );//It will exception class name, error message and line number
}
Page 163
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 111: A java program to handle multiple exceptions using common catch block
import java.util.Scanner;
class Edemo
{
public static void main(String s[ ])
{
try
{
int fn = Integer.parseInt(s[0]);
int sn = Integer.parseInt(s[1]);
int res = fn/sn;
System.out.println(res);
int a[ ] = {10, 20, 30};
System.out.println(a[sn]);
}
catch(Exception e)
{
e.printStackTrace( );
}
}
}
OUTPUT:
Page 164
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 112: A java program to handle exceptions with finally block
import java.util.Scanner;
class Edemo
{
public static void main(String args[ ])
{
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter index:");
int i = sc.nextInt( );
String s = "Visakhapatnam";
System.out.println(s.charAt(i));
}
catch(Exception e)
{
e.printStackTrace( );
}
finally
{
System.out.println("Hello Java");
}
}
}
OUTPUT:
Page 165
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
48.6 Finally Block:
Throws is a keyword in java language, used to throw the exception which is raised in method body
to its calling method.
Throws keyword always should be followed by ‘method header’.
Syntax 1:
returntype methodName( ) throws ExceptionClass1, ExceptionClass2, … //for known
exception
{
-----------
-----------
}
Syntax 2:
returntype methodName( ) throws Exception //for un-known exception
{
-----------
----------- }
Advantages:
1) Burden on the API developers are reduced.
2) Time consuming process will be reduced while working with exception handling.
Page 166
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example:
class Edemo
{
public static void main(String args[ ] ) throws Exception
{
Class C = Class.forName(s[0]);
Object o = C.newInstance( );
}
}
In the above example, whatever the exceptions are raised in main( ) method are re-throwing to JVM
without handling using ‘try-catch( )’ block.
The difference between ‘throw’ and ‘throws’ keyword is, throws is used to throw the predefined or
user defined exception whereas ‘throw’ keyword is used to throw the user defined exceptions only.
Page 168
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
49. Java Assertions
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion: It provides an effective way to detect and correct programming errors.
Syntax- 1 of using Assertion:
assert expression;
Syntax- 2 of using Assertion:
assert expression1 : expression2;
If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
OUTPUT:
Page 169
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
50. Collection Frameworks in Java
Collections in java is a framework that provides an architecture to store and manipulate the group of
objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects.
Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection represents a single unit of objects i.e. a group.
In traditional approach arrays concept was used to manipulate the data but because of some limitations
of arrays, that is replaced with ‘collections’.
Limitations of array:
1) Array is having fixed size.
2) Array can handle only similar type of data or objects.
3) It is very difficult to perform data manipulations on arrays like searching, sorting , insertion,
deletion, updation, appending, retrieving etc.
Advantages with collections:
1) It is grow able in size.
2) Every collection is a generic type so that it can handle dissimilar type of data.
3) It is very easy to perform data manipulations because of predefined API available of collections.
4) Collection supports both insertion and deletion operations.
All collection classes are available in ‘java.util’ package and the implementation classes of different
interfaces are as follows:
Page 170
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Sets:
1) A set represents a group of elements arranged just like an array.
2) The set will grow dynamically when the elements are stored into it.
3) A set will not allow duplicate elements.
4) If we try to pass same elements that is already available in the set, then it is not stored into the
set.
Lists:
1) Lists are like sets. They store a group of elements.
2) Lists allows duplicate values to be stored.
Queues:
1) A queue represents arrangement of elements in FIFO order.
2) This means that an element that is stored as a first element into the queue will be removed first
from the queue.
Maps:
1) Maps store elements in the form of key and value pairs. If the key is provided then its
corresponding value can be obtained. All the keys should have unique values.
For any collection class object can be created as shown below:
CollectionClass <Element Type> ref = new CollectionClass<Element Type>( );
It is predefined class in ‘java.util’ package contains predefined methods to perform data manipulation
operations on retrieved data from database.
1) sort( ): It is a predefined static method in collections class used to arrange the given elements in
ascending order.
2) reverse( ): It is a predefined method in collections class used to reverse the order which is currently
available in collection object.
Page 171
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 117: A java program on Stack class
import java.util.*
class stackdemo
{
pubic static void main(String[ ] args)
{
Stack <integer> s=new Stack <integer>( );
s.push(40);
s.push(30);
s.push(16);
s.push(25);
System.out.println(s);
boolean b=s.empty( );
System.out.println (b);
int i=s.peek( );
System.out.println (i);
int p=s.search(10);
System.out.println (p);
Collections.sort(s);
System.out.println ("ascending order :"+s);
Collections.reverse(s);
System.out.println ("descending order "+s);
s,pop( );
System.out.println (s);
s.pop( );
System.out.println (s);
}
}
Page 173
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
e) In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if
any element is removed from the array list.
Array List Methods:
a) void add(int index, Object element)- It is used to insert the specified element at the specified
position index in a list.
b) boolean addAll(Collection c): It is used to append all of the elements in the specified
collection to the end of this list, in the order that they are returned by the specified collection's
iterator.
c) void clear( ): It is used to remove all of the elements from this list.
d) int lastIndexOf(Object o): It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.
e) Object[] toArray( ): It is used to return an array containing all of the elements in this list in
the correct order.
f) Object[] toArray(Object[] a): It is used to return an array containing all of the elements in
this list in the correct order.
g) boolean add(Object o): It is used to append the specified element to the end of a list.
h) boolean addAll(int index, Collection c): It is used to insert all of the elements in the specified
collection into this list, starting at the specified position.
i) int indexOf(Object o): It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
j) void trimToSize( ): It is used to trim the capacity of this ArrayList instance to be the list's
current size.
//display again
System.out.println("Contents after removing: "+arl);
//display its size
System.out.println("Size of Arraylisrt: "+arl.Size( ));
Page 174
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//extract elements using Iterator
System.out.println("Extracting using Iterator);
//add an Iterator to ArrayList to retreive elements
Iterator it = arl.iterator( );
while(it.hasNext( ))
{
System.out.println("it.next( ));
}
}
}
Page 175
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
hs.clear( );
System.out.println(hs);
}
}
Page 179
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60. Multi-Threading
Multi-Tasking:
1) If multiple applications are running simultaneously is known as “Multi-tasking”. It is also known as
process based multi-tasking.
2) Example: In windows O.S. playing a song using media player, downloading a software from any
website, performing operations in calculator etc. can be done simultaneously.
3) Following two concepts were introduced from multi-tasking, these are designed at programming
language level.
a) Multi Processing
b) Multi Threading
Multi-Processing:
If multiple programs of same application is running simultaneously for multiple requests is
known as ‘Multi-processing”.
Multi Threading:
If the same program of same application is running simultaneously for multiple requests of end
user is known as “Multi Threading”.
Java Supports both ‘Multiprocessing’ and ‘Multithreading’. But multithreading can be used in the
development of ‘server softwares’ to control number of requests of end users.
Page 180
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.1 Multithreading in Java:
Task:
1) A task is nothing but executing set of instructions.
2) Performing or executing more than one task simultaneously is called mutli tasking.
3) Multi tasking is of two types:
a) Process based multi tasking
b) Thread based multitasking
Process based multi tasking:
1) A process is an instance of a program that is being executed.
2) Process based multi tasking means executing more than one process simultaneously.
3) A program is the smallest unit of code that can be dispatched by the scheduler.
4) Processes are light weight tasks that require their own separated address space.
Thread based multi threading:
1) A thread is an independent path of execution with in a program.
2) Thread is the smallest unit of dispatchable code.
3) A single program can perform two or more tasks simultaneously.
4) A thread is a light weight task that share same address space.
5) In java, if multiple threads are running simultaneously is known as “Multi-Threading”.
6) In end user point of view, thread is a request and JVM point of view thread is flow of execution.
7) The main advantage with multi-threading is to reduce the end users waiting time while sending
multiple requests to the same program of same application.
8) Thread doesn't block the user because threads are independent and you can perform multiple
operations at same time.
9) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Page 181
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) New: When a new request is send to the server, a new thread will be created. The thread is in new
state if you create an instance of Thread class but before the invocation of start( ) method.
2) Runnable: The thread is in runnable state after invocation of start( ) method, but the thread
scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it, which means the
thread is in under execution.
4) Non-Runnable(Blocked): This is the state when the thread is still alive, but the execution is
stopped temporarily.
5) Terminated (Dead): A thread is in terminated or dead state when its run( ) method exits.
The thread will be executed only once if it is in ‘new’ and ‘dead’ state.
If thread is in runnable/running/waiting state, memory is available for that and also these operations
will be performed multiple times.
Thread Class:
1) It is predefined class also can be used to create our own user defined ‘Thread’ class, it was
implemented from ‘Runnable’ interface.
2) Thread class provides constructors and methods to create and perform operations on a thread.
3) Constructors of Thread class:
a) Thread( ): Allocates a new thread object and gives default name for thread like thread-0, thread-
1, etc.
b) Thread(String name): Allocates a new thread object and gives user defined name for that
thread.
c) Thread(Runnable thread): Allocates a new thread object for given resource and gives default
name for thread.
d) Thread(Runnable thread, String name): Allocates a new thread object for given resource and
gives user defined name for that thread.
Page 182
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4) Methods of Thread Class:
a) public void run( ): is used to perform action for a thread.
b) public void start( ): starts the execution of the thread. JVM calls the run( ) method on the
thread.
c) public void sleep(long milliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
d) public void join( ): waits for a thread to die/terminate.
e) public void join(long milliseconds): waits for a thread to die/terminate for the specified
milliseconds.
f) public int getPriority( ): returns the priority of the thread.
g) public int setPriority(int priority): changes the priority of the thread.
h) public String getName( ): returns the name of the thread.
i) public void setName(String name): changes the name of the thread.
j) public Thread currentThread( ): returns the reference of currently executing thread.
k) public int getId( ): returns the id of the thread.
l) public boolean isAlive( ): tests if the thread is alive.
m) public void yield( ): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
n) public void suspend( ): is used to suspend the thread.
o) public void resume( ): is used to resume the suspended thread.
p) public void stop( ): is used to stop the thread.
q) public void interrupt( ): interrupts the thread.
r) public boolean isInterrupted( ): tests if the thread has been interrupted.
s) public ThreadState getState( ): returns the state of the thread.
t) public boolean isDaemon( ): Tests if the thread is daemon thread.
u) public void setDaemon(boolean b): Marks the thread as daemon or user thread.
Page 183
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
f) Call the run( ) method with the help of start( ) method.
Example:
t1.start( );
t2.start( );
Page 184
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) Class object of the class that is implementing Runnable is passed as parameter to Thread
constructor, so that class ‘run( )’ method may execute.
OUTPUT:
Note:
1) When we extend Thread class there is no scope to extend any other class. This is a limitation.
2) When we implement Runnable interface there is scope for extending any other class.
If you are not extending the Thread class, your class object would not be treated as a thread object. So
you need to explicitly create Thread class object.
Page 185
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 127: A java program to stop a Thread in middle
import java.io.*;
class MyThread implements Runnable
{
boolean stop =false;
public void run( )
{
for(int i=1; i<=1000; i++)
{
System.out.println(i);
if(stop) return;
}
}
}
class TDemo
{
public static void main(String args[ ]) throws IOException
{
//Create an object to MyThread class
MyThread obj = new MyThread( );
//attach an object to obj.
Thread t1 = new Thread(obj);
//start thread
t1.start( );
//Accept enter key from keyboard
System.in.read( );
//then make stop as true
obj.stop=true;
}
}
OUTPUT:
Page 186
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 128: Example of sleep method in java
class TestSleepMethod1 extends Thread
{
public void run( )
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TestSleepMethod1 t1=new TestSleepMethod1( );
TestSleepMethod1 t2=new TestSleepMethod1( );
t1.start( );
t2.start( );
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time, the thread scheduler picks up another thread and so on.
Page 187
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(c);
}
catch(Exception e)
{
System.err.println(e);
}
}
}
class Tdemo
{
public static void main(String a[ ])
{
Page 188
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TDemo t1=new TDemo( );
TDemo t2=new TDemo( );
t1.start( );
t2.start( );
}
}
OUTPUT:
Page 189
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.4 Creating Multiple Threads on different objects
In muti tasking, several tasks are executed at a time. For this purpose, we need more than one thread.
For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks and these tasks
are executed simultaneously by the two threads.
So, using more than one thread is called “Multi-Threading”.
Program 132: A Java program to create multiple threads that act upon different object on Theatre
Management
import java.io.*;
class MyThread implements Runnable
{
String str;
MyThread(String str)
{
this.str = str;
}
public void run( )
{
for(int i=1;i<=10;i++)
{
System.out.println(str +":" +i);
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
}
}
class TDemo
{
public static void main(String args[])
{
MyThread obj1 = new MyThread("Cut Ticket");
MyThread obj2 = new MyThread("Show Chair");
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start( );
t2.start( );
}
}
Page 190
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Program 133: A Java program to create multiple threads that act upon single object
import java.io.*;
class Reserve implements Runnable
{
int available=1;//available berths are 1
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run( )
{
//display available berths
System.out.println("Available berths =" +available);
//if availble berths are more than wanted berths
if(available>=wanted)
{
//get name of the passenger
String name = Thread.currentThread( ).getName( );
Page 191
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//allot the berth to the passenger
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);//wait for printing the ticket
available = available -wanted;//update the no.of available berths
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are availble");
}
}
class TDemo
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
//attach first thread to the object
Thread t1 = new Thread(obj);
//attach second thread to the same object
Thread t2 = new Thread(obj);
//set name to the thread
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}
OUTPUT:
Page 192
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.6 Thread Synchronization:
When two or more threads need access to a shared resource, they need some way to ensure that the
resources will be used by only one thread at a time.
When a thread is already acting on a object, preventing any other from acting on the same object is
called “Thread Synchronization” or “Thread safe”.
Thread synchronization is recommended when multiple threads are used on the same object.
Synchronized object is like a locked object, locked on a thread called as “mutually exclusive lock”.
Synchronization can be achieved in two ways:
1) Using synchronized block: Here, we can embed a group of statements inside run( ) method in a
synchronized block.
Syntax:
synchronized(object)
{
statements;
}
The statements inside the synchronized block are all available to only one thread at a time. They are
not available to more than one thread simultaneously.
2) Using synchronized keyword: Here, we can synchronize an entire method by using synchronized
keyword.
Example:
synchronized void display( )
{
statements;
}
Program 134: A Java program to create multiple threads that act upon single object using
synchronized block
import java.io.*;
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run( )
{
synchronized(this)
{
System.out.println("Available berths =" +available);
if(available>=wanted)
{
String name = Thread.currentThread( ).getName( );
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);
Page 193
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
available = available -wanted;
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are availble");
}
}
}
class TDemo1
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}
OUTPUT:
Program 135: A Java program to create multiple threads that act upon single object using
synchronized keyword
import java.io.*;
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
synchronized public void run( )
{
Page 194
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println("Available berths =" +available);
if(available>=wanted)
{
String name = Thread.currentThread( ).getName( );
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);
available = available -wanted;
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are available");
}
}
class TDemo1
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}
OUTPUT:
Page 195
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.7 Thread Communication:
In some cases, two or more threads should communicate with each other.
For example: Producer - Consumer problem.
A Consumer thread is waiting for a Producer to produce the data. When the Producer thread
completes production of data, then the Consumer thread should take that data and use it.
Program 136: A Java program shows how two threads can communicate with each other
import java.io.*;
class Communicate1
{
public static void main(String args[]) throws Exception
{
//Producer produces some data which Consumer consumes
Producer obj1 = new Producer( );
//Pass Producer object to Consumer so that it is then available to Consumer
Consumer obj2 = new Consumer(obj1);
//Creation of threads and attach to Producer and Consumer
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//Run the threads
t2.start( );//Consumer waits
t1.start( );//Producer starts production
}
}
class Producer extends Thread
{
//For adding data, we use string buffer object
StringBuffer sb;
//data provider will be true when data production is over
boolean dataprovider = false;
Producer( )
{
sb=new StringBuffer( );//allocating memory
}
public void run( )
{
for(int i=1;i<=10;i++)
{
try
{
sb.append(i+":");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
System.err.println(e);
}
Page 196
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
dataprovider=true;
}
}
class Consumer extends Thread
{
//create Producer reference to refer to Producer object from Consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run( )
{
//If the data production is not over, sleep for 10 milli seconds and check again.
try
{
while(!prod.dataprovider)//This while llop will be broken if ‘dataprovider’ is true
{
Thread.sleep(10);
}
}
catch(Exception e)
{
System.err.println(e);
}
//When the data production is over, display data of StringBuffer
System.out.println(prod.sb);
}
}
OUTPUT:
Key Points:
In the above program 136: The communication between Producer and Consumer is not in a effective
way because at some point Consumer finds the ‘dataprovider’ is false and it goes into sleep for the
next 10milliseconds.
Page 197
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Mean while, the data production may be over. But Consumer comes out of after 10 milliseconds and
then only it can find ‘dataprovider’ is true.
This means that there may be a time delay of 1 to 9 milliseconds to receive the data after its actual
production is completed.
So to improve the efficiency of communication between threads “java.lang.Object” class provides 3
methods:
1) obj.notify( ):This method releases an object and sends a notification to a waiting thread that the
object is available.
2) obj.notifyAll( ):This method is useful to send notification to all waiting threads at once that the
object is available.
3) obj.wait( ): This method makes a thread wait for the object till it receives a notification from
notify( ) or notifyAll( ) methods.
It is recommended to use the above methods inside a synchronized block.
Program 137: A Java program to demonstrate thread communication using wait( ) and notify( )
methods
import java.io.*;
class Communicate1
{
public static void main(String args[]) throws Exception
{
//Producer produces some data which Consumer consumes
Producer obj1 = new Producer( );
//Pass Producer object to Consumer so that it is then available to Consumer
Consumer obj2 = new Consumer(obj1);
//Creation of threads and attach to Producer and Consumer
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//Run the threads
t2.start( );//Consumer waits
t1.start( );//Producer starts production
}
}
class Producer extends Thread
{
//For adding data, we use string buffer object
StringBuffer sb;
//dataprovider will be true when data production is over
Producer( )
{
sb=new StringBuffer( );//allocating memory
}
public void run( )
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
Page 198
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
try
{
sb.append(i+":");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
System.err.println(e);
}
}
//data production is over, so notify to Consumer thread
sb.notify( );
}
}
}
class Consumer extends Thread
{
//create Producer reference to refer to Producer object from Consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run( )
{
synchronized(prod.sb)
{
//wait till a notification is received from producer thread. Here there is no
wastage //of time of evena single millisecond
try
{
prod.sb.wait( );
}
catch(Exception e)
{
System.err.println(e);
}
//When the data production is over, display data of StringBuffer
System.out.println(prod.sb);
}
}
}
Page 199
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
KeyPoints:
In the above program 137: there will not be any wastage of a single millisecond time to receive the
adat by the consumer.
There is no need to use ‘dataprovider’ variable at Producer side. We can directly send a notification
immediately after the data production is over.
Here, sb.notify( )is sending a notification to the Consumer thread that the StringBuffer object sb is
available and it can be used now.
Page 201
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61. I/O Streams
Definition of stream:Stream is flow of data or sequence of data.
If the data is flow from input component to java program is known as “Input Stream” and if the data
is flow from java program to output component is known as “Output Stream”.
Input component can be keyboard, file, client machine, etc. and output components can be monitor,
server machine etc.
Java supports ‘I/O streams’ concept to perform reading and writing operations on input and output
components respectively with the help of predefined classes which are available in ‘java.io.’ package.
Java supports to perform writing and reading operations on any type of files like text file, image file,
audio file, video file etc.
In java, System class is found in “java.lang” package and has three fields as follows:
1)System.in: This represents “InputStream” class object, by default represents standard input device
i.e. keyboard.
2) System.out: This represents “OutputStream” class object, by default represents standard output i.e.
monitor. It is used to display normal messages and results.
3) System.err:This filed also represents “PrintStream” object, which by default represents monitor. It
is used to display error messages.
In ‘java.io’ package all the stream classes are categorized in to following two types:
1) Character Stream Classes: These are the predefined classes used to perform both reading and
writing operations on ‘character data’. Example: doc, pdf, txt files etc.
2) Byte Stream Classes: These are the predefined classes used to perform both reading and writing
operations on ‘character data’ and ‘binary data’. Example: jpeg, png, etc.
Hierarchy of I/O Stream Classes:
Page 202
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Operations on Files:
1) Open the file.
2) Writing data into the file.
3) Reading data from the file.
4) Copy the file from one location to another file.
5) Delete the file.
6) Create a new file
Writer:
It is the most super class for all writing related classes used to perform writing operations on character
data.
Reader:
It is the most super class for all reading related classes used to perform reading operations on character
data.
OutputStream:
It is the most super class for all writing related classes used to perform writing operations on binary
data and character data.
InputStream:
It is the most super class for all reading related classes used to perform reading operations on binary
data and character data.
Following predefine classes can be used while performing operations on files:
1) File
2) FileReader
3) FileWriter
4) FileInputStream
5) FileOutputStream
File:
It is a predefined class in ‘java.io’ package can be used to represent given file in the form of
object, it provides predefined methods to perform various operations on files like finding length on the
file, finding name, extension of the file, creation of new file, removing the existing file etc.
Syntax: File ref = new File(String pathofthefile);
61.1 FileWriter:
It is used to perform writing operations on character files like txt, pdf, doc etc.
Syntax 1: FileWriter fw = new FileWriter(String pathofthefile);
In the above syntax 1, it always verifies the file in the given location, if it is available that file
will be opened and setting writing mode. If the file is not available it creates a new file in the same
location.
Syntax 2: FileWriter fw = new FileWriter(String pathofthefile, true);
In the above syntax2, opens the file in appending mode.
Syntax 3: File f = new File(String pathofthefile);
FileWriter fw = new FileWriter(f);
In the above syntax 3, opens the file in writing mode.
Syntax 4: File f = new File(String pathofthefile);
FileWriter fw = new FileWriter(f, true);
In the above syntax 4, opens the file in the appending mode.
Note: It is highly recommended to close the file once its operation is completed.
Page 203
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61.2 FileReader:
1) It is a predefined class used to perform reading operation on character files.
2) FileReader class open the given file in reading mode, if the file is not existing then it raises
‘FileNotFoundException’.
Syntax 1: FileReader fr = new FileReader(String pathofthefile); //open the file in reading mode
Syntax 2: File f = new File(String pathofthefile);
FileReader fr = new FileReader(f);// open the file in reading mode.
Program 139: A java program to write the string data in to text file using ‘FileWriter’ class
import java.io.*;
class FWDemo
{
public static void main(String args[])
{
try
{
FileWriter fw = new FileWriter("D:\\sample.txt");
fw.write("Hello Java Programming");
fw.close( );
System.out.println("File writing successful");
}
catch(IOException e)
{
System.err.println(e);
}
}
}
Note: It is highly recommended to close the file once its operation is completed.
Program 140: A java program to read the string data from the text file using ‘FileReader’ class
import java.io.*;
class FrDemo
{
public static void main(String args[])
{
try
{
FileReader fr = new FileReader("D:\\sample.txt");
int ch;
while((ch=fr.read( ))!=-1)
{
System.out.println((char)ch);
}
fr.close( );
Page 204
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
catch(IOException e)
{
System.err.println(e);
}
}
}
61.3 FileOutputStream:
1) It is a predefined class used to perform writing operation both on binary files like image, audio,
video files etc. and on character files.
2) While working with ‘FileOutputStream’ if the file is not available then it creates a new file.
Syntax 1: FileOutputStream fos = new FileOutputStream(String pathofthefile); //open file in writing
//mode
Syntax 2: FileOutputStream fos = new FileOutputStream(String pathofthefile, true); //open file in
//appending mode
Syntax 3: File f = new File(String pathofthefile);
FileOutputStream fos = new FileOutputStream(f); //open file in writing mode
Syntax 4: File f = new File(String pathofthefile);
FileOutputStream fos = new FileOutputStream(f, true); //open file in appending mode
Page 205
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61.4 FileInputStream:
1) It is a predefined class used to perform reading operation both on binary files like image, audio,
video files etc. and on character files.
2) While working with ‘FileInputStream’ if the file is not available then it raises File not found
exception.
Syntax 1: FileInputStream fis = new FileInputStream (String pathofthefile); //open file in reading
//mode
Syntax 2: File f = new File(String pathofthefile);
FileInputStream fos = new FileInputStream (f); //open file in reading mode
Program 142: A java program to read the data from character file using ‘FileInputStream’ class
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read( ))!=-1)
{
System.out.print((char)i);
}
fin.close( );
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Page 207
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT IV
62. Applets in java
Applet is a Java byte code program embedded in a HTML (Hyper Text Markup Language) page.
It runs inside the browser and works at client side. So applet = java byte code + HTML page.
The Applet class is contained in the java.applet package.
Page 208
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) public void stop( ):
This method is called by the browser when the applet is to be stopped.
If the user minimizes the web page, then this method is called and when the user again comes
back to this page then start( ) method is called.
In this way start( ) and stop( ) methods can be called repeatedly.
4) public void destroy( ):
This method is called when the applet is being terminated from memory.
The stop( ) method will always be called before destroy( ).
The code related to releasing the memory allocated to the applet and stopping any running
threads should be written in this method.
Hierarchy of Applet
Executing init( ), start( ), stop( ) and destroy( ) methods in a sequence is called as “Life Cycle of an
Applet” .
Note that the ‘public static void main(String args[])’ method is not available in applets. It means we
can
compile the applet code but we cannot run it by JVM.
Once the applet is created, we can compile and obtain its byte code. This byte code is embedded in
HTML page and the page is sent to the client computer.
The client machine contains a various browsers which are used to execute the applet program.
The browser contains a small virtual machine called “applet engine” which understands and run the
applet code.
Applets can show images and animations, play sounds, take user input and send it to the server.
AWT-based applets also override the paint( ) method, which is defined by the AWT Component class.
This method is called when the applet’s output must be redisplayed.
Page 209
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
62.5 java.awt.Component class
This Component class provides one life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
62.6 Example of Applet skeleton:
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init( )
{
//initialization
}
public void start ( )
{
//start or resume execution
}
public void stop( )
{
//suspend execution
{
public void destroy( )
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
Page 210
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//Myapp.html
<html>
<applet code = “Myapp.class” height = 300 width = 400>
</applet>
</html>
appletviewer Myapp.html
OUTPUT:
// GraphicsDemo.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Page 211
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Page 212
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 147: A java program on displaying image in applet
import java.awt.*;
import java.applet.*;
public class Myapp extends Applet
{
Image picture;
public void init( )
{
picture = getImage(getDocumentBase( ),"a.jpg");
}
public void paint(Graphics g)
{
g.drawImage(picture, 30,30, this);
}
}
OUTPUT:
Page 213
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63. Event Handling
Changing the state of an object is known as event. Events are generated as result of user interaction
with the graphical user interface (GUI) 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.
The way in which an event is handled and controlled is called “eventhandling”.
Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
Events are supported by a number of packages, including java.util, java.awt, and java.awt.event.
63.1 Types of events:
1) Foreground Events:
The 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.
2) Background Events:
Some events can occur without human interaction such as operating system interrupts, hardware or
software failure, timer expires, an operation completion etc.
Page 214
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.4 Event Listeners:
A listener is an object that is notified when an event occurs.
It has two major requirements: First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to receive and process
these notifications.
The methods that receive and process events are defined in a set of interfaces, such as those found in
java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.
Page 215
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.6 The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected.
The ActionEvent class defines four integer constants that can beused to identify any modifiers
associated with an action event as follows:ALT_MASK, CTRL_MASK,META_MASK, and
SHIFT_MASK.
ActionEvent has these three constructors:
1) ActionEvent(Object src, int type, String cmd)
2) ActionEvent(Object src, int type, String cmd, int modifiers)
3) ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here, src is a reference to the object that generated this event.
The type of the event is specified by type, and its command string is cmd.
The argument modifiers indicates which modifier keys (alt, ctrl, meta, and/or shift) were pressed when
the event was generated.
The when parameter specifies when the event occurred.
The ActionEvent has following methods:
1) getActionCommand( ):This method returns the name of the command for invoking the
ActionEvent object. The form is: String getActionCommand( )
2)getModifiers( ): This method returns a value that indicates which modifier keys(alt, ctrl, meta,
and/or shift) were pressed when the event was generated. Its formis: int getModifiers( )
3) getWhen( ): This method returns the time at which the event took place. This is called the event’s
timestamp. Itsform is:long getWhen( )
Page 216
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.8 The ComponentEvent Class:
A ComponentEvent is generated when the size, position, or visibility of a component is changed.
The ComponentEvent class defines integer constants and their meanings are shown here:
Page 217
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) You can determine the other component by calling getOppositeComponent( ).
Itsform is: Component getOppositeComponent( ). The opposite component is returned.
2) isTemporary( ): This method indicates if this focus change is temporary.
Its form is: boolean isTemporary( ). The method returns true if the change is temporary. Otherwise, it
returns false.
To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods. The forms of
these methods are shown here:
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
The ItemEvent defines one integer constant named as ITEM_STATE_CHANGED, that signifies a
change of state.
ItemEvent has one constructor:
ItemEvent(ItemSelectable src, int type, Object entry, int state)
Here, src is a reference to the component that generated this event. For example, this might be a list or
choice element.
The type of the event is specified by type. The specific item that generated the item event is passed in
entry. The current state of that item is in state.
The ‘ItemEvent’ has following methods:
1)getItem( ): This method can be used to obtain a reference to the item that changed.
Its form is: Object getItem( )
2)getItemSelectable( ): This method an be used to obtain a reference to the ItemSelectable object that
generated an event. Its form is:ItemSelectable getItemSelectable( ).
3)getStateChange( ): This method returns the state change (SELECTED orDESELECTED) for the
event. Its form is:int getStateChange( ).
Page 218
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.13 The KeyEvent Class:
A KeyEvent is generated when keyboard input occurs. The KeyEvent is a subclass of InputEvent.
There are three types of key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event occurs only
when a character is generated.
Remember, not all keypresses result in characters. For example, pressing shift does not generate a
character.
There are many other integer constants that are defined by KeyEvent. For example,VK_0 through
VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbersand letters. Here are
some others:
Page 219
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
The ‘MouseEvent’ has following methods:
1) getX( ): This method return the X coordinates of the mouse when the event occurred. Its form is: int
getX( ).
2)getY( ): This method return the Y coordinates of the mouse when the event occurred. Its form is: int
getY( ).
3)getPoint( ): This method returns X and Y coordinates of the mouse. Its form is: Point getPoint( ).
4)translatePoint( ): This method changes the location of the event. Its form is: void translatePoint(int
x, int y).
5)getClickCount( ): This method obtains the number of mouse clicks for this event. Its form is: int
getClickCount( ).
6)isPopupTrigger( ): This method tests if this event causes a pop-up menu to appear on this
platform.Its form is: boolean isPopupTrigger( ).
7)getButton( ): This method returns a value that represents the button that caused the event.For most
cases, the return value will be one of these constants defined by MouseEvent:
Page 220
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.16 The TextEvent Class:
This class describe text events. These are generated by text fields and text areaswhen characters are
entered by a user or program.
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The TextEventhas one constructor:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type.
Page 221
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
64. Sources of Event
The below table lists some of the user interface components that can generate the events.
Page 222
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
65.2 The AdjustmentListener Interface:
This interface defines the adjustmentValueChanged( ) method that is invoked when anadjustment
event occurs. Its general form is:
void adjustmentValueChanged(AdjustmentEvent ae)
Page 223
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
65.8 The The MouseListener Interface:
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked.
When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the
mouse is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Page 225
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Notice that the two variables, mouseX and mouseY, store the location of the mouse when a mouse
pressed, released, or dragged event occurs.
These coordinates are then used by paint( ) to display output at the point of these occurrences.
Page 226
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "Down";
repaint( );
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "Up";
repaint( );
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint( );
}
// Handle mouse moved.When dragging the mouse, a * is shown, which tracks with
the mouse pointer as it is dragged.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX( ) + ", " + me.getY( ));
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
OUTPUT SCREENS:
Page 227
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
68. Handling Keyboard Events
To handle keyboard events by implementing the KeyListener interface.
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed(
) event handler.
When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is
executed.
If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked.
Page 228
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar( );
repaint( );
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
OUTPUT:
Page 229
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 150: A java program on Adapter Classes
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init( )
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
adapterDemo.showStatus("Mouse dragged");
}
}
Page 230
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
70. Inner classes
An inner class is a class defined within another class or within another expression.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet
{
public void init( )
{
addMouseListener(new MyMouseAdapter( ));
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}
70.1 Anonymous Inner Class:
An anonymous class is a class whose name is not written and for which only one objecy is created.
Page 232
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT - V
Page 233
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
72. Handling Buttons:
When a button ispressed an event is generated, this event is sent to appropriate listener that is
registered with the button.
The listener then implements ActionListenerinterface, defines the actionPerformed( ) method.
An ActionEvent object is passed as parameter to the method. It contains reference to button that
generated the event and reference to the action command string.
ActionCommand string is used to label the button by default.
getActionCommand( ) method is used to get the label of the button that is pressed.
//Button1.html
<html>
<applet code ="Button1.class" width = 500 height = 200>
</applet>
Page 234
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Page 235
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
g.drawString(msg,150,140);
msg="Undefined:" +c3.getState( );
g.drawString(msg,150,180);
}
}
//CheckBoxDemo.html
<html>
<applet code ="CheckBoxDemo.class" width = 500 height = 200>
</applet>
OUTPUT:
Program 155: A java program that handling the Radio Buttons/Checkbox Groups
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RadioDemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
CheckboxGroup cbg;
public void init( )
{
cbg = new CheckboxGroup( );
c1 = new Checkbox("Bold",cbg,true);
c2 = new Checkbox("Italic",cbg,false);
c3 = new Checkbox("Undefined",cbg,false);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
Page 236
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox( ).getLabel( );
g.drawString(msg, 6, 100);
}
}
//RadioDemo.html
<html>
<applet code ="RadioDemo.class" width = 500 height = 200>
</applet>
OUTPUT:
OUTPUT:
Page 238
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
77. Handling TextArea:
TextArea is called as simple multi line editor.
Constructors of TextArea:
1) TextArea( ) throws HeadlessException
2) TextArea(int numlines, int numchars) throws HeadlessException
3) TextArea(String str ) throws HeadlessException
4) TextArea(String str, int numlines, int numchars ) throws HeadlessException
5) TextArea(String str, int numlines, int numchars, int sBars ) throws HeadlessException
Note: ‘numlines’ specifies height of the text area, numchars specifies width of the text area, sBars
specify scrollbars.
It contains constants such as: SCROLLBAR_BOTH, SCROLLBAR_NONE,
SCROLLBAR_HORIZONTAL_ONLY, SCROLLBAR_VERTICAL_ONLY.
TextArea is a subclass of TextComponent.
The method supported are: getText( ), setText( ), getSelectedText( ), select( ), isEditable( ) and
setEditable( ).
Other methods that are supported by TextArea are:
1) append( ):Appends the specified string to the end of the current text.
Syntax: void append(String str)
2) insert( ): Inserts the string passed in ‘str’ at specified index.
Syntax:void insert(String str, int index)
3) replaceRange( ): Used to replace the text.
Syntax: void replaceRange(String str, int startIndex, int endIndex)
// TextAreaDemo.html
<html>
<applet code ="TextAreaDemo.class" width = 500 height = 200>
</applet>
Page 239
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
OUTPUT 1:
Page 241
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT 2:
Page 242
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 159: A java program on Handling Lists
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ListDemo extends Applet implements ActionListener
{
List veh, comp;
String msg=" ";
public void init( )
{
veh = new List(4,true);
comp = new List(4, false);
veh.add("car");
veh.add("Bus");
veh.add("Bike");
veh.add("Lorry");
comp.add("Hero Motors");
comp.add("Honda");
comp.add("Maruthi");
comp.add("Ford");
comp.add("AshokLeyland");
comp.select(1);
add(veh);
add(comp);
veh.addActionListener(this);
comp.addActionListener(this);
}
public void actionPerformed(ActionEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
int ind[ ];
msg = "Selected Vehicle";
ind=veh.getSelectedIndexes( );
for(int i=0;i<ind.length;i++)
msg+=veh.getItem(ind[i])+ " ";
g.drawString(msg,100,150);
msg="Selected Company";
msg+=comp.getSelectedItem( );
g.drawString(msg,100,180);
}
}
Page 243
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Page 245
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
81. Layout Managers:
A layout manager is an instance of any class that implements the LayoutManager interface.
The layout manager is set by the setLayout( ) method. Its form is:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager.
If no call to setLayout( ) is made, then the default layout manager is used by JVM.
OUTPUT:
>javac FlowLayoutDemo.java
>appletviewer FlowLayoutDemo.java
Page 247
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
81.2 Handling Border Layout:
The BorderLayout class implements a common layout style for top-level windows.
It has four narrow, fixed-width components at the edges and one large area in the center.
The four sides are referred to as north, south, east, and west. The middle area is called the center.
The constructors defined by BorderLayout:
a) BorderLayout( ): The first form creates a default border layout.
b) BorderLayout(int horz, int vert): The second allows you to specify the horizontal and vertical
space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
a) BorderLayout.CENTER
b) BorderLayout.EAST
c) BorderLayout.NORTH
d) BorderLayout.SOUTH
e) BorderLayout.WEST
The add( ) method is used to adding the components. Its form is:
void add(Component compRef, Object region)
Here, compRef is a reference to the component to be added, and region specifies where the component
will be added.
Page 250
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
82 Window Fundamentals
82.1 Component:
At the top of the AWT hierarchy is the Component class.
Component is an abstract class that encapsulates all of the attributes of a visual component.
Except for menus, all user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component. For example: mouse and keyboard events, positioning and sizing
the window and repainting.
A Component object is responsible for remembering the current foreground and background colors
and the currently selected text font.
82.2 Container:
The Container class is a subclass of Component.
It has additional methods that allow other Component objects to be nested within it.
A container is responsible for laying out (that is, positioning) any components that it contains.
82.3 Panel:
The Panel class is a concrete subclass of Container and it is the superclass for Applet.
A Panel is a window that does not contain a title bar, menu bar, or border. So for this reason see these
items when an applet is run inside a browser.
When you run an applet using an applet viewer, the applet viewer provides the title and border.
Other components can be added to a Panel object by its add( ) method (inherited from Container).
Once these components have been added, you can position and resize them manually using the
setLocation( ), setSize( ), setPreferredSize( ), or setBounds( ) methodsdefined by Component.
82.4 Window:
The Window class creates a top-level window. A top-level window is not contained within any other
object; it sits directly on the desktop.
Generally, you cannot create Window objects directly. Instead, wecan use a subclass of Window
called Frame.
82.5 Frame:
Frame is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.
Page 251
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
83. Working with Frame Windows
A frame creates a standard-style window and a Frame’s has two constructors:
1) Frame( ) throws HeadlessException
2) Frame(String title) throws HeadlessException
The first form creates a standard window that does not contain a title and the second form creates a
window with the title specified by title.
A HeadlessException is thrown if an attempt is made to create a Frame instancein an environment
that does not support user interaction.
Frame has several methods are as follows:
1) setSize( ): It is used to set the dimensions of the window. Its signature is:
a) void setSize(int newWidth, int newHeight)
b) void setSize(Dimension newSize)
The new size of the window is specified by newWidth and newHeight, or by the width and
height fields of the Dimension object passed in newSize.
The dimensions are specified in terms of pixels.
2) getSize( ):This method returns the current size of the window contained within the width and height
fields of a Dimension object. Its form is: Dimension getSize( ).
3) setVisible( ):
After a frame window has been created, it will not be visible until you call setVisible( ).
Its form is: void setVisible(boolean visibleFlag).
The component is visible if the argument to this method is true. Otherwise, it is hidden.
4) setTitle( ):
5) windowClosing( ):
6) The drawstring( ) method of Graphics class can be used to display the text in Frame.
7) Components can be added to the Frame by using add( ) method.
8) A components can be displayed with required font by using setFont( ) method.
Syntax: Font f = new Font(“name”, style, size);
setFont(f);
9) A component can be placed in a particular location in the Frame by using setBounds( ) method.
10) To set color we can use setColor( ) method.
Example 1: setColor(Color.yellow);
Example 2: Color c = new Color(r,g,b);
setColor(c);
11)To display images in the Frame we can use drawIamge( ) method of Graphics class.
Page 252
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
83.1. Creating a Frame:
There are two ways we can create a Frame.
a) Create an object to Frame class.
Syntax: Frame obj = new Frame( );
b) Create a class that exteds Frame class
Example:
class MyFrame extends Frame
//Now create an object to the user defined class MyFrame
Obj = new MyFrame( );
Page 253
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public static void main(String args[ ])
{
MyFrame f = new MyFrame( );
f.setSize(400,300);
f.setTitle(“First Frame”);
f.setVisible(true);
f.addWindowListener(new MyClass( ) );
}
}
class MyClass implements WindowListener
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Program 164: A java Button Example with ActionListener Event Handling by using Frames
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener
{
public ButtonDemo( )
{
FlowLayout fl = new FlowLayout( );// set the layout to frame
setLayout(fl);
Button rb = new Button("Red");
Button gb = new Button("Green");
Button bb = new Button("Blue");
rb.addActionListener(this);// link the Java button with the ActionListener
gb.addActionListener(this);
bb.addActionListener(this);
add(rb);// add each Java button to the frame
add(gb);
add(bb);
}
// override the only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand( );// to know which Java button user clicked
System.out.println("You clicked " + str + " button");
if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);
Page 254
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}
public static void main(String args[])
{
ButtonDemo obj = new ButtonDemo( );
obj.setTitle("Button in Action");
obj.setSize(300, 350);
obj.setVisible(true);
}
}
OUTPUT:
Program 165: A java CheckBox Example with ItemListener Event Handling by using Frames
import java.awt.*;
import java.awt.event.*;
public class CheckTest extends Frame implements ItemListener
{
Checkbox nameBox, boldBox, italicBox, exitBox;
Label lab;
public CheckTest( )
{
nameBox = new Checkbox("Monospaced");
boldBox = new Checkbox("Bold", true);
italicBox = new Checkbox("Italic");
lab = new Label("Way 2 Java");
Page 255
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
exitBox.setForeground(Color.blue);
exitBox.setFont(new Font("Serif", Font.BOLD, 12));
nameBox.addItemListener(this);
boldBox.addItemListener(this);
italicBox.addItemListener(this);
exitBox.addItemListener(this);
add(nameBox, "North");
add(boldBox, "West");
add(italicBox, "East");
add(exitBox, "South");
add(lab, "Center");
if(nameBox.getState( ) == true)
fontName = "Monospaced";
else
fontName = "Dialog";
if(boldBox.getState( ) == true)
b = Font.BOLD;
else
b = Font.PLAIN;
if(italicBox.getState( ) == true)
i = Font.ITALIC;
else
i = Font.PLAIN;
if(exitBox.getState( ) == true)
System.exit(0);
Page 256
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
new CheckTest( );
}
}
OUTPUT:
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand( );// know the menu item selected by the user
System.out.println("You selected " + str);
}
public static void main(String args[])
{
new SimpleMenuExample( );
setTitle("Simple Menu Program"); // frame creation methods
setSize(300, 300);
setVisible(true);
}
}
OUTPUT:
Page 258
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
INTRODUCTION TO SWINGS:
Page 259
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is
ButtonUI.
89. JLabel:
JLabel is the Swing component that creates a label, which is a component that displays text and/or an
icon.
The label is Swing’s simplest component because it does not respond to user input and just displays
output.
Page 260
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 167: A java program on JLabel in Swings
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
OUTPUT:
90. JButton
In order to create buttons we will create objects to JButton class in Swings.
The following are the constructors in JButton class.
1) JButton(Icon icon)
2) JButton(String str)
3) JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
Whenever a button is pressed an ActionEvent is generated.
To handle this event ActionListener interface is to be implemented and actionPerformed( )method
should be overridden.
Page 261
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 168: A java program on JButton in Swings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonInAction extends JFrame implements ActionListener
{
Container c;
public JButtonInAction( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout
Page 262
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
91. JCheckBox
Checkboxes in swings can be used by creating objects to JCheckBox class.
The constructor of this class is: JcheckBox(String str)
Whenever a checkbox is checked and unchecked an ItemEvent is generated.
In order to handle it ItemListener interface is to be implemented and itemStateChanged( ) method
should be overridden.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBox1 extends JFrame implements ItemListener
{
JCheckBox rb,gb,bb;
Container c;
public JCheckBox1( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout
rb = new JCheckBox("Yellow");
gb = new JCheckBox("Pink");
bb = new JCheckBox("Blue");
rb.addItemListener(this); // linking to listener
gb.addItemListener(this);
bb.addItemListener(this);
c.add(rb); // adding buttons
c.add(gb);
c.add(bb);
Page 263
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
setTitle("Check Boxes In Action"); // usual set methods of AWT frame
setSize(300, 350);
setVisible(true);
}
// override the abstract method of ActionListener
public void itemStateChanged(ItemEvent e)
{
if(rb.isSelected( ))
c.setBackground(Color.yellow);
else if(gb.isSelected( ))
c.setBackground(Color.pink);
else if(bb.isSelected( ))
c.setBackground(Color.blue);
}
public static void main(String args[])
{
new JCheckBox1( );
}
}
OUTPUT:
92. JRadioButton
Radio Buttons are supported by JRadioButton class.
It supports one of the constructor: JRadioButton(String str)
Here, str is the label for the button.
Whenever a Radio Buttion is selected an ItemEvent is generated.
In order to handle it ItemListener interface is to be implemented and itemStateChanged( ) method
should be overridden.
Page 264
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 170: A java program on JRadioButton in Swings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButton1 extends JFrame implements ItemListener
{
JRadioButton rb,gb,bb;
Container c;
public JRadioButton1( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout
rb = new JRadioButton("Yellow");
gb = new JRadioButton("Pink");
bb = new JRadioButton("Blue");
rb.addItemListener(this); // linking to listener
gb.addItemListener(this);
bb.addItemListener(this);
c.add(rb); // adding buttons
c.add(gb);
c.add(bb);
setTitle("Radio Buttons In Action"); // usual set methods of AWT frame
setSize(300, 350);
setVisible(true);
}
// override the abstract method of ActionListener
public void itemStateChanged(ItemEvent e)
{
if(rb.isSelected( ))
c.setBackground(Color.yellow);
else if(gb.isSelected( ))
c.setBackground(Color.pink);
else if(bb.isSelected( ))
c.setBackground(Color.blue);
}
public static void main(String args[])
{
new JRadioButton1( );
}
}
Page 265
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
93. JList
Radio Buttons are supported by JList class.
It supports one of the constructor: JList(E[ ]items). This creates a JList that contains the items in the
array specified by items.
A JList generates a ListSelectionEvent when the user makes or changes a selection.
In order to handle it ListSelectionListener interface is to be implemented and valueChanged( )
method should be overridden.
A JList allows the user to select multiple ranges of items within the list, but
you can change this behavior by calling setSelectionMode( ).
Its signature is: void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
1) SINGLE_SELECTION
2) SINGLE_INTERVAL_SELECTION
3) MULTIPLE_INTERVAL_SELECTION
Page 266
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
String names[] = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow" }; //Add all
items into array.
colors = new JList(names); // creating JList object
colors.setVisibleRowCount(5);
colors.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
c.add(new JScrollPane(colors));
colors.addListSelectionListener(this);
setTitle("Practcing JList");
setSize(300,300);
setVisible(true);
}
public void valueChanged(ListSelectionEvent e)
{
String str = (String) colors.getSelectedValue( );
if(str.equals("Red"))
c.setBackground(Color.red);
else if(str.equals("Green"))
c.setBackground(Color.green);
else if(str.equals("Blue"))
c.setBackground(Color.blue);
else if(str.equals("Cyan"))
c.setBackground(Color.cyan);
else if(str.equals("Magenta"))
c.setBackground(Color.magenta);
else if(str.equals("Yellow"))
c.setBackground(Color.yellow);
}
public static void main(String args[])
{
new JList1( );
}
}
OUTPUT:
Page 267
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
94. JComboBox(JChoiceBox)
The object of JComboBox class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu. It inherits JComponent class.
Page 268
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
95. JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
It has following constructors:
1) JTable(Object[][] rows, Object[] columns): It Creates a table with the specified data.
Page 269
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:
96. JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation
of a scrollbar.
It inherits JComponent class.
Page 270
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
97. JMenu
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
Page 272
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam